测试环境:
Python版本:Python 2.7
简单的将日志打印到屏幕
import logging
logging.debug('this is a debug level message')
logging.info('this is info level message')
logging.warning('this is warning level message')
logging.error('this is error level message')
logging.critical('this is critical level message')
运行结果:
>>>
WARNING:root:this is warning level message
ERROR:root:this is error level message
CRITICAL:root:this is critical level message
>>>
默认情况下,logging将日志打印到屏幕,日志级别为WARNING,低于此级别的不显示;
日志级别从高到低:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
通过logging.basicConfig函数对日志的输出格式及方式做相关配置
logging.basicConfig(**kwargs)
注:该函数必须在main线程除外的子线程启动之前调用,否则可能会造成日志重复记录
支持的常见关键词参数如下
filename 将使用指定的文件名,创建文件句柄(FileHandler),而非使用流处理器(StreamHandler)
filemode 指定打开文件的模式,如果指定了filename,但未指定filemode,则filemode默认为‘a’)。
format 指定handler使用的format.
datefmt 指定时间格式,同time.strftime()
level 设置root logger level为指定的level,默认为logging.WARNING
import logging
fmt = '%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s: %(message)s'
logging.basicConfig(level=logging.DEBUG,
format=fmt,
filename='d:/logs.txt',
filemode='w',
datefmt='%a, %d %b %Y %H:%M:%S'
)
logging.debug('this is a debug level message')
logging.info('this is info level message')
logging.warning('this is warning level message')
logging.error('this is error level message')
logging.critical('this is critical level message')
查看d:/logs.txt,文件内容如下
Sun, 17 Jan 2016 20:14:21 test2[line: 11] DEBUG: this is a debug level message
Sun, 17 Jan 2016 20:14:21 test2[line: 12] INFO: this is info level message
Sun, 17 Jan 2016 20:14:21 test2[line: 13] WARNING: this is warning level message
Sun, 17 Jan 2016 20:14:21 test2[line: 14] ERROR: this is error level message
Sun, 17 Jan 2016 20:14:21 test2[line: 15] CRITICAL: this is critical level message
format参数值说明:
%(name)s: 打印Logger的名字
%(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: 打印日志信息
将日志同时输出到文件和屏幕
import logging
fmt = '%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s: %(message)s'
logging.basicConfig(level=logging.DEBUG,
format=fmt,
filename='d:/logs.txt',
filemode='w',
datefmt='%a, %d %b %Y %H:%M:%S'
)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter(fmt)
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
logging.debug('this is a debug level message')
logging.info('this is info level message')
logging.warning('this is warning level message')
logging.error('this is error level message')
logging.critical('this is critical level message')
控制台输出如下:
>>> ================================ RESTART ================================
>>>
2016-01-14 23:01:42,592 test.py[line: 18] INFO: this is info level message
2016-01-14 23:01:42,595 test.py[line: 19] WARNING: this is warning level message
2016-01-14 23:01:42,596 test.py[line: 20] ERROR: this is error level message
2016-01-14 23:01:42,598 test.py[line: 21] CRITICAL: this is critical level message
>>>
d:/logs.txt文件内容如下:
Thu, 14 Jan 2016 23:01:42 test.py[line: 17] DEBUG: this is a debug level message
Thu, 14 Jan 2016 23:01:42 test.py[line: 18] INFO: this is info level message
Thu, 14 Jan 2016 23:01:42 test.py[line: 19] WARNING: this is warning level message
Thu, 14 Jan 2016 23:01:42 test.py[line: 20] ERROR: this is error level message
Thu, 14 Jan 2016 23:01:42 test.py[line: 21] CRITICAL: this is critical level message
注意:logs.txt中记录比控制台输出的记录多一条,因为设置的level级别不一样
RotatingFileHandler介绍
该模块主要用于自动切换日志写入文件,将日志写入不同文件,保证单个日志文件不会太大。
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
filename:指定初始文件名
mode:指定filename的打开方式
maxBytes:指定单个日志文件的文件最大值,当文件大小近乎maxBytes值时,自动关闭当前文件,自动创建一个新的文件,往新文件写入日志。如果为0,则不会发生日志切换事件。
backupCount:设置允许保留的最大文件数量,如果是非0值,当达到指定数量时,系统会创建新文件并自动删除最先创建的文件。
例子:比如设置filename为app.log,设置maxBytes=1024M, backupCount=5,那么当第一个文件app.log达到1024M时,自动关闭app.log,然后重命名为app.log.1,同时新建app.log,往里写入日志,当达到1024M时,自动关闭app.log,然后重命名为app.log.2,一直重复这样的操作,直到app.log.5,如果没达到app.log.5之前,如果app.log.x已存在,则重命名为app.log.x 1,如果达到5,则会删除之前的文件,顺序为按创建时间先后,如先删除app.log.1,自动关闭app.log, 然后重命名app.log.1,接着如果app.log文件又写满了,重复前面的删除操作,删除app.log.2……
例1:
import logging
from logging.handlers import RotatingFileHandler
rt_file_handler = RotatingFileHandler('d:/test1.log', maxBytes=10*1024*1024, backupCount=5)
rt_file_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(me
ssage)s')
rt_file_handler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(rt_file_handler)
#logger.setLevel(logging.DEBUG) #设置日志级别,这里不能通过rt_file_handler.setLevel(logging.DEBUG)设置日志级别,不起作用
logger.debug('this is a debug level message')
logger.info('this is info level message')
logger.warning('this is warning level message')
logger.error('this is error level message')
logger.critical('this is critical level message')
运行查看结果:控制台无输出,d:test1.log内容如下:
2016-01-17 23:34:35,200 test2[line:14] WARNING this is warning level message
2016-01-17 23:34:35,201 test2[line:15] ERROR this is error level message
2016-01-17 23:34:35,201 test2[line:16] CRITICAL this is critical level message
说明:可以设置maxBytes的值小一点,查看是会生成多个日志文件
通过logging.config模块配置日志
注意:配置文件必须包含[loggers],[handlers], [formatters],且每个结点下的logger,handler,formatter都必须有对应的结点,且格式必须正确:[loggers_logger], [handlers_handler], [handlers_formatter]
注:[logger_root],为root logger专用
D:/log.conf文件如下:
[loggers]
keys=root,eg01,eg02
[logger_root]
level=NOTSET
handlers=handler01, handler02
[logger_eg01]
handlers=handler01
qualname=eg01
propagate=0
[logger_eg02]
handlers=handler02
qualname=eg02
propagate=0
[handlers]
keys=handler01,handler02
[handler_handler01]
class=StreamHandler
level=WARNING
formatter=form01
args=(sys.stdout,)
[handler_handler02]
class=FileHandler
level=ERROR
formatter=form02
args=('d:/logs.txt', 'a')
[formatters]
keys=form01,form02
[formatter_form01]
format=%(name)s: %(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=
例:
import logging
import logging.config
logging.config.fileConfig('D:/log.conf')
logger = logging.getLogger('')
logging.debug('this is a debug level message')
logging.info('this is info level message')
logging.warning('this is warning level message')
logging.error('this is error level message')
logging.critical('this is critical level message')
运行结果
控制台输出:
>>> ================================ RESTART ================================
>>>
root: (asctime)s test2.py[line:9] WARNING this is warning level message
root: (asctime)s test2.py[line:10] ERROR this is error level message
root: (asctime)s test2.py[line:11] CRITICAL this is critical level message
>>>
说明:输出由handler_handler01 的level=WARNING控制
d:logs.txt输出
root : ERROR this is error level message
root : CRITICAL this is critical level message
说明:输出由handler_handler012的level=ERROR控制
修改logger_root结点下的level为DEBUG,如下
[logger_root]
level=DEBUG
执行后发现,输出结果不变
说明:
1. 如果设置日志级别为NOTSET,意味着所有消息都会被记录
2. propagete=0,表示输出日志,但消息不传递;propagate=1是输出日志,同时消息往更高级别的地方传递。若上面配置文件参数progagate=1,那么将会看到重复的消息记录
3.qualname指定logger的名称
4. class指定handler的类型
5.args根据class的不同而不同,即handler类型的初始化参数,详情可参考官方logging.config模块
对比实验1
修改logger_root结点下的level为NOTSET,修改 logger = logging.getLogger('')为:
logger = logging.getLogger('eg01'),,再次运行,查看输出结果:
控制台输出:
>>> ================================ RESTART ================================
>>>
eg01: (asctime)s test2.py[line:9] WARNING this is warning level message
eg01: (asctime)s test2.py[line:10] ERROR this is error level message
eg01: (asctime)s test2.py[line:11] CRITICAL this is critical level message
>>>
说明:输出由handler_handler01 的level=WARNING控制
d:logs.txt为空
对比实验2
修改logger_root结点下的level为NOTSET,修改 logger = logging.getLogger('eg01')为:
logger = logging.getLogger('eg02'),,再次运行,查看输出结果:
控制台无输出
d:logs.txt
eg02 : ERROR this is error level message
eg02 : CRITICAL this is critical level message
说明:输出由handler_handler012的level=ERROR控制
对比实验3:
修改logger_eg01结点,增加level为DEBUG,修改 logger = logging.getLogger(' eg02')为:
logger = logging.getLogger('eg01'),,再次运行,查看输出结果:
[logger_eg01]
level=DEBUG
结果,和没增加level时一样。
说明:当[logger_logname]和[handler_handlername]中同时指定了level值时,使用[handler_handlername]中设置的level。
对比实验4
在以上基础上,去掉[handler_handler01]中的level=WARNING,,同时,修改[logger_root]结点下
level=NOTSET为level=INFO,,再次运行
控制台输出:
>>> ================================ RESTART ================================
>>>
eg01: (asctime)s test2.py[line:7] DEBUG this is a debug level message
eg01: (asctime)s test2.py[line:8] INFO this is info level message
eg01: (asctime)s test2.py[line:9] WARNING this is warning level message
eg01: (asctime)s test2.py[line:10] ERROR this is error level message
eg01: (asctime)s test2.py[line:11] CRITICAL this is critical level message
说明:当[logger_logname]中设置了level,而[handler_handlername]未指定level值时,使用[handler_ logname]中设置的level
对比实验5
在以上基础上,去掉[logger_eg01]中的level=WARNING,,再次运行,查看结果
控制台输出:
>>> ================================ RESTART ================================
>>>
eg01: (asctime)s test2.py[line:8] INFO this is info level message
eg01: (asctime)s test2.py[line:9] WARNING this is warning level message
eg01: (asctime)s test2.py[line:10] ERROR this is error level message
eg01: (asctime)s test2.py[line:11] CRITICAL this is critical level message
说明:当[logger_logname]和[handler_handlername]都未指定level值时,使用[handler_root]中设置的level,如果[handler_root]未指定level则默认level为WARNING
对比实验6
修改[logger_eg02]结点handlers为:handlers=handler02,handler01,修改logger = logging.getLogger('eg01')为logger = logging.getLogger('eg02'),再次运行,查看结果
控制台输出:
>>> ================================ RESTART ================================
>>>
eg02: (asctime)s test2.py[line:8] INFO this is info level message
eg02: (asctime)s test2.py[line:9] WARNING this is warning level message
eg02: (asctime)s test2.py[line:10] ERROR this is error level message
eg02: (asctime)s test2.py[line:11] CRITICAL this is critical level message
>>>
d:/logs.txt输出:
eg02 : ERROR this is error level message
eg02 : CRITICAL this is critical level message
说明:可在一个[logger_logname]结点中指定多个handlername以支持多个处理器
对比实验6
修改[handler_handler01]结点中args=(sys.stdout,)为args=(sys.stderr,), 运行后发现:控制台输出的记录都变成红色,类似如下:
>>> ================================ RESTART ================================
>>>
eg02: (asctime)s test2.py[line:8] INFO this is info level message
eg02: (asctime)s test2.py[line:9] WARNING this is warning level message
eg02: (asctime)s test2.py[line:10] ERROR this is error level message
eg02: (asctime)s test2.py[line:11] CRITICAL this is critical level message
>>>
注:上述本该显示时间的地方都显示为(asctime)s了,原因是format (astime)s前漏了%,修正如下:
format=%(name)s: %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
参考网络文章:
http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html