Python自带日志处理模块logging
默认的日志级别有DEBUG,INFO,WARNING,ERROR,CRITICAL,对应的函数是debug(),info(),warning(),error()和critical()
In [490]: import logging In [491]: LOG_FILENAME='/tmp/example.log' In [492]: logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) In [493]: logging.debug('This message should go to the log file')
查看/tmp/example.log的内容
$ cat /tmp/example.log DEBUG:root:This message should go to the log file
不断执行
logging.debug('This message should go to the log file')
/tmp/example.log会不断地刷新
日志轮转
In [639]: import glob In [640]: import logging In [641]: import logging.handlers In [642]: LOG_FILENAME='/tmp/logging_rotatingfile_example.out' In [643]: my_logger=logging.getLogger('MyLogger') In [644]: my_logger.setLevel(logging.DEBUG) In [645]: handler=logging.handlers.RotatingFileHandler(LOG_FILENAME,maxBytes=20,backupCount=5) In [646]: my_logger.addHandler(handler) In [648]: for i in range(20): my_logger.debug('i=%d' % i) .....: .....: In [650]: logfiles=glob.glob('%s*' %LOG_FILENAME) In [651]: for filename in logfiles: .....: print filename .....: .....: /tmp/logging_rotatingfile_example.out.1 /tmp/logging_rotatingfile_example.out.2 /tmp/logging_rotatingfile_example.out.5 /tmp/logging_rotatingfile_example.out.3 /tmp/logging_rotatingfile_example.out.4 /tmp/logging_rotatingfile_example.out
最近的日志文件总是名为logging_rotatingfile_example.out,一旦大小达到maxBytes设置的20字节,就将轮转。
logging模块最重要的一个功能就是可以根据设置的不同的日志级别输出不同的日志信息。
import logging import sys LEVELS={'debug':logging.DEBUG, 'info' :logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'critical':logging.CRITICAL } if sys.argv > 1: level_name = sys.argv[1] level=LEVELS.get(level_name,logging.NOTSET) logging.basicConfig(level=level) logging.debug('This is a debug message') logging.info('This is a info message') logging.warning('This is a warning message') logging.error('This is a error message') logging.critical('This is a critical error message') ~ ~
$ python logging_level_example.py debug DEBUG:root:This is a debug message INFO:root:This is a info message WARNING:root:This is a warning message ERROR:root:This is a error message CRITICAL:root:This is a critical error message $ python logging_level_example.py info INFO:root:This is a info message WARNING:root:This is a warning message ERROR:root:This is a error message CRITICAL:root:This is a critical error message $ python logging_level_example.py warning WARNING:root:This is a warning message ERROR:root:This is a error message CRITICAL:root:This is a critical error message $ python logging_level_example.py error ERROR:root:This is a error message CRITICAL:root:This is a critical error message $ python logging_level_example.py critical CRITICAL:root:This is a critical error message
logging模块包括logger,handler,filter和formatter。
Logger.setLevel()设置日志级别
Logger.addFilter()
Logger.removeFilter()
Logger.debug()
Logger.info()
Logger.warning()
Logger.error()
Logger.critical()
Logger.exception()
Logger.log()
logging.Formatter
定义日志格式
%(name)s Name of the logger (logging channel)
| %(levelno)s Numeric logging level for the message (DEBUG, INFO,
| WARNING, ERROR, CRITICAL)
| %(levelname)s Text logging level for the message ("DEBUG", "INFO",
| "WARNING", "ERROR", "CRITICAL")
| %(pathname)s Full pathname of the source file where the logging
| call was issued (if available)
| %(filename)s Filename portion of pathname
| %(module)s Module (name portion of filename)
| %(lineno)d Source line number where the logging call was issued
| (if available)
| %(funcName)s Function name
| %(created)f Time when the LogRecord was created (time.time()
| return value)
| %(asctime)s Textual time when the LogRecord was created
| %(msecs)d Millisecond portion of the creation time
| %(relativeCreated)d Time in milliseconds when the LogRecord was created,
| relative to the time the logging module was loaded
| (typically at application startup time)
| %(thread)d Thread ID (if available)
| %(threadName)s Thread name (if available)
| %(process)d Process ID (if available)
| %(message)s The result of record.getMessage(), computed just as
| the record is emitted
案例程序
def info(str): logger=logging.getLogger('test') FileHandler=logging.FileHandler('/tmp/'+'2015-06-26'+'.log') FileHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(FileHandler) logger.setLevel(logging.INFO) logger.info(str) logger.removeHandler(FileHandler) FileHandler.close() def error(str): logger=logging.getLogger('test') FileHandler=logging.FileHandler('/tmp/'+'2015-06-26'+'.log') FileHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) logger.addHandler(FileHandler) logger.setLevel(logging.ERROR) logger.error(str) logger.removeHandler(FileHandler) FileHandler.close() info('Starting agent process') error('Starting error')
输出结果
2015-06-26 22:31:10,489 INFO Starting agent process 2015-06-26 22:31:10,489 ERROR Starting error 2015-06-26 22:31:12,961 INFO Starting agent process 2015-06-26 22:31:12,961 ERROR Starting error 2015-06-26 22:31:13,709 INFO Starting agent process 2015-06-26 22:31:13,709 ERROR Starting error 2015-06-26 22:31:14,201 INFO Starting agent process 2015-06-26 22:31:14,201 ERROR Starting error 2015-06-26 22:31:14,626 INFO Starting agent process 2015-06-26 22:31:14,626 ERROR Starting error 2015-06-26 22:31:15,032 INFO Starting agent process 2015-06-26 22:31:15,032 ERROR Starting error 2015-06-26 22:31:15,455 INFO Starting agent process 2015-06-26 22:31:15,455 ERROR Starting error 2015-06-26 22:31:16,500 INFO Starting agent process 2015-06-26 22:31:16,500 ERROR Starting error 2015-06-26 22:31:17,100 INFO Starting agent process 2015-06-26 22:31:17,100 ERROR Starting error 2015-06-26 22:31:17,536 INFO Starting agent process 2015-06-26 22:31:17,536 ERROR Starting error
参考文档:
https://docs.python.org/2.6/library/logging.html#configuration-file-format