首页 > 代码库 > python logging system

python logging system

官方教程:https://docs.python.org/2/library/logging.html 

1.  用法1

import loggingimport logging.handlersLOG_FILE = ‘tst.log‘handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCount = 5) # 实例化handler fmt = ‘%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s‘formatter = logging.Formatter(fmt)   # 实例化formatterhandler.setFormatter(formatter)      # 为handler添加formatterlogger = logging.getLogger(‘tst‘)    # 获取名为tst的loggerlogger.addHandler(handler)           # 为logger添加handlerlogger.setLevel(logging.DEBUG)logger.info(‘first info message‘)logger.debug(‘first debug message‘)

formatter

  采用的是%(<dict key>)s的形式,就是字典的关键字替换。提供的关键字包括:

FormatDescription
%(name)sName of the logger (logging channel).
%(levelno)sNumeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).
%(levelname)sText logging level for the message (‘DEBUG‘‘INFO‘‘WARNING‘‘ERROR‘‘CRITICAL‘).
%(pathname)sFull pathname of the source file where the logging call was issued (if available).
%(filename)sFilename portion of pathname.
%(module)sModule (name portion of filename).
%(funcName)sName of function containing the logging call.
%(lineno)dSource line number where the logging call was issued (if available).
%(created)fTime when the LogRecord was created (as returned by time.time()).
%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(asctime)sHuman-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).
%(msecs)dMillisecond portion of the time when the LogRecord was created.
%(thread)dThread ID (if available).
%(threadName)sThread name (if available).
%(process)dProcess ID (if available).
%(message)sThe logged message, computed as msg args.

 level

The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.

LevelNumeric value
CRITICAL50
ERROR40
WARNING30
INFO20
DEBUG10
NOTSET0

 如果指定level 为INFO, 则小于它的所有message都不会打印出来。

2. 用法2

  采用配置文件的方式去配置logging system, 这种方法简单方便,可以在多模块间调用而不需要传入logger对象。

现在我准备一个配置文件logging.conf如下

[loggers]keys=root,uploader,msgChanger   #[handlers]keys=consoleHandler,uploaderHandler,msgChangerHandler[formatters]keys=fmt[logger_root]level=INFOhandlers=consoleHandlerqualname=root[logger_uploader]level=INFOqualname=uploaderhandlers=uploaderHandler[logger_msgChanger]level=INFOqualname=msgChangerhandlers=msgChangerHandler[handler_consoleHandler]class=StreamHandlerlevel=INFOformatter=fmtargs=(sys.stdout,)[handler_uploaderHandler]class=logging.handlers.RotatingFileHandlerlevel=INFOformatter=fmtargs=(‘log/uploader.log‘,‘w‘,1024*1024*1024,5,)[handler_msgChangerHandler]class=logging.handlers.RotatingFileHandlerlevel=INFOformatter=fmtargs=(‘log/msg_changer.log‘,‘w‘,1024*1024*1024,5,)[formatter_fmt]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=

 called in code:

‘‘‘init log module‘‘‘    logging.config.fileConfig(‘config/logging.conf‘)   # parse config file as above       msgChanger_logger = logging.getLogger(‘msgChanger.main‘) # get a logger instance, msgChanger must be included 
  msgChanger_logger.info(‘test log system in main.‘)

 可以在任何module下写入上述代码调用logger, 只需要传入一个名字就好了,名字必须在config文件里配置了的,否则实例失败。