2019独角兽企业重金招聘Python工程师标准>>>

python 的日志logging模块学习

分类: python 2011-08-02 23:51 8338人阅读 评论(0) 收藏 举报

loggingpythonhttp服务器streamclasssun

目录(?)[+]

1.简单的将日志打印到屏幕

import logging

logging.debug('This is debug message')

logging.info('This is info message')

logging.warning('This is warning message')

屏幕上打印:

WARNING:root:This is warning message

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;

日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

import logging

logging.basicConfig(level=logging.DEBUG,

format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

datefmt='%a, %d %b %Y %H:%M:%S',

filename='myapp.log',

filemode='w')

logging.debug('This is debug message')

logging.info('This is info message')

logging.warning('This is warning message')

./myapp.log文件中内容为:

Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message

Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message

Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函数各参数:

filename: 指定日志文件名

filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'

format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:

%(levelno)s: 打印日志级别的数值

%(levelname)s: 打印日志级别名称

%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]

%(filename)s: 打印当前执行程序名

%(funcName)s: 打印日志的当前函数

%(lineno)d: 打印日志的当前行号

%(asctime)s: 打印日志的时间

%(thread)d: 打印线程ID

%(threadName)s: 打印线程名称

%(process)d: 打印进程ID

%(message)s: 打印日志信息

datefmt: 指定时间格式,同time.strftime()

level: 设置日志级别,默认为logging.WARNING

stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

3.将日志同时输出到文件和屏幕

import logging

logging.basicConfig(level=logging.DEBUG,

format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',

datefmt='%a, %d %b %Y %H:%M:%S',

filename='myapp.log',

filemode='w')

#################################################################################################

#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#

console = logging.StreamHandler()

console.setLevel(logging.INFO)

formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

console.setFormatter(formatter)

logging.getLogger('').addHandler(console)

#################################################################################################

logging.debug('This is debug message')

logging.info('This is info message')

logging.warning('This is warning message')

屏幕上打印:

root        : INFO     This is info message

root        : WARNING  This is warning message

./myapp.log文件中内容为:

Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message

Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message

Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日志回滚

import logging

from logging.handlers import RotatingFileHandler

#################################################################################################

#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M

Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)

Rthandler.setLevel(logging.INFO)

formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

Rthandler.setFormatter(formatter)

logging.getLogger('').addHandler(Rthandler)

################################################################################################

从上例和本例可以看出,logging有一个日志处理的主对象,其它处理方式都是通过addHandler添加进去的。

logging的几种handle方式如下:

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件

logging.FileHandler: 日志输出到文件

日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler

logging.handlers.BaseRotatingHandler

logging.handlers.RotatingFileHandler

logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: 远程输出日志到TCP/IP sockets

logging.handlers.DatagramHandler:  远程输出日志到UDP sockets

logging.handlers.SMTPHandler:  远程输出日志到邮件地址

logging.handlers.SysLogHandler: 日志输出到syslog

logging.handlers.NTEventLogHandler: 远程输出日志到Windows NT/2000/XP的事件日志

logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer

logging.handlers.HTTPHandler: 通过"GET"或"POST"远程输出到HTTP服务器

由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中,

上述其它处理方式的使用请参见python2.5手册!

5.通过logging.config模块配置日志

#logger.conf

###############################################

[loggers]

keys=root,example01,example02

[logger_root]

level=DEBUG

handlers=hand01,hand02

[logger_example01]

handlers=hand01,hand02

qualname=example01

propagate=0

[logger_example02]

handlers=hand01,hand03

qualname=example02

propagate=0

###############################################

[handlers]

keys=hand01,hand02,hand03

[handler_hand01]

class=StreamHandler

level=INFO

formatter=form02

args=(sys.stderr,)

[handler_hand02]

class=FileHandler

level=DEBUG

formatter=form01

args=('myapp.log', 'a')

[handler_hand03]

class=handlers.RotatingFileHandler

level=INFO

formatter=form02

args=('myapp.log', 'a', 10*1024*1024, 5)

###############################################

[formatters]

keys=form01,form02

[formatter_form01]

format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s

datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]

format=%(name)-12s: %(levelname)-8s %(message)s

datefmt=

上例3:

import logging

import logging.config

logging.config.fileConfig("logger.conf")

logger = logging.getLogger("example01")

logger.debug('This is debug message')

logger.info('This is info message')

logger.warning('This is warning message')

上例4:

import logging

import logging.config

logging.config.fileConfig("logger.conf")

logger = logging.getLogger("example02")

logger.debug('This is debug message')

logger.info('This is info message')

logger.warning('This is warning message')

6.logging是线程安全的

转载于:https://my.oschina.net/u/2245485/blog/479122

python 的日志logging模块学习相关推荐

  1. [zz]很详细,涵盖了多数场景!推荐 - python 的日志logging模块学习

    http://blog.csdn.net/yatere/article/details/6655445 1.简单的将日志打印到屏幕 import logging logging.debug('This ...

  2. python中日志logging模块和异常捕获traceback模块的使用

    python中日志logging模块和异常捕获traceback模块的使用 参考文章: (1)python中日志logging模块和异常捕获traceback模块的使用 (2)https://www. ...

  3. python logging模块学习

    python 的日志logging模块学习 1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.in ...

  4. python中的logging记录日志_[ Python入门教程 ] Python中日志记录模块logging使用实例...

    python中的logging模块用于记录日志.用户可以根据程序实现需要自定义日志输出位置.日志级别以及日志格式. 将日志内容输出到屏幕 一个最简单的logging模块使用样例,直接打印显示日志内容到 ...

  5. Python 日志logging模块初探及多线程踩坑(2)

    系列文章: Python 日志logging模块初探及多线程踩坑(1) Python 日志logging模块初探及多线程踩坑(2) 接着上面一篇文章,我们这篇来写一个多进程兼容且无损性能的 Timed ...

  6. Python实战之logging模块使用详解

    用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所 ...

  7. python 日志 logging模块(详细解析)

    1 基本使用 转自:https://www.cnblogs.com/wf-linux/archive/2018/08/01/9400354.html 配置logging基本的设置,然后在控制台输出日志 ...

  8. Python牛刀小试(五)--logging模块

    由于想给自己的Python程序添加日志功能,学习下Python的日志模块. 一个简单的例子: 点击(此处)折叠或打开 import logging ##第一个简单的例子 logging.warning ...

  9. 二十八、深入浅出Python中的 logging模块

    @Author: Runsen logging模块是Python内置的标准模块,主要用于输出脚本运行日志,可以设置输出日志的等级.日志保存路径等. 文章目录 日志 五个级别 日志信息的输出格式 log ...

最新文章

  1. 新生赛(2) problem 2 丁磊养猪
  2. jQuery.extend 函数使用详解
  3. 什么时候需要用到RCC_APB2Periph_AFIO--复用IO时钟的使用
  4. Docker-创建和分享应用(3)
  5. 【专栏】国内外物联网平台初探(篇二:阿里云物联网套件)
  6. java数据链表 有什么用_链表(linked list)这一数据结构具体有哪些实际应用?
  7. 《南溪的目标检测学习笔记》——图像预处理的学习笔记
  8. 微信小程序点餐页面实现完整版
  9. 税务计算机类考试题型,税务师考试题型分值分配、计算器要求及2020年考试时间...
  10. 运维面试和笔试常见问题
  11. Cypress前端测试左移分享
  12. 计算机白板培训心得,电子白板学习的心得体会
  13. 'Periodic workspace save .' has encountered a problem
  14. HOJ 2706 Key Task
  15. 如何自己编写一个交通仿真软件(二)原野。
  16. android 面试题(史上最全)
  17. Houdini 求中点,点连成线
  18. 打开桌面计算机投屏到扩展屏,将Win10电脑屏幕内容投屏到小米电视的操作方法...
  19. python猫抓老鼠_利用python如何实现猫捉老鼠小游戏
  20. linux通过iphone usb上网,Ubuntu下iphone拖电脑上网

热门文章

  1. 理解Linux中断 (2)【转】
  2. VIM 命令使用大全
  3. C++11新特性中的匿名函数Lambda表达式的汇编实现分析(二)
  4. 输入框中默认的值,判断是否输入内容
  5. Linux视频教程系列汇总
  6. JavaScript Table排序
  7. Strongswan — 常用配置说明
  8. 2021 年 ICT 行业预测
  9. 互联网协议 — UDP 用户数据报协议
  10. 分布式任务队列 Celery — 实践