logging模块_小结

logging模块

距离上次写博客已经快几近一年,短短一年的时间发生的事情改变了博主的一生。命运弄人,博主能做的唯有将失去的东西,用十倍的努力成倍的拿回来
the best revenge is massive success.我又再次回来,再次打开网页,打开markdown继续我的“创作”(搬运)。

logging概念:用于在程序运行时追踪和记录事件,告警和错误之用

logging何时使用:
logging模块_小结
官网doc的截图,简述:输出正常操作的信息用print(),记录事件流程用logging.info(),解决告警信息用logging.warning(),报告并抛出错误用raise,报告,记录但是不抛出异常用logging.error()

logging分为5个等级 :DEBUG INFO WARNING ERROR CRITICAL
设置logging的等级时使用:

logging.basicConfig(filename='myapp.log', level=logging.INFO)

函数的完整参数列表

filename Specifies that a FileHandler be created, using the specifiedfilename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified(if filemode is unspecified, it defaults to a)
datefmt Use the specified date/time format.
format Use the specified format string for the handler.
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with ‘filename’ - if both are present, ‘stream’ is ignored.

(format参数既可以使用%s %d %f ,又可以使用更高级的template和format函数来定制)


logger

  • Logger:提供基本的方法
  • Handler:提供指向的目标文件
  • Filter:过滤日志文件
  • Formatter:自定义化输出

best practice

logger = logging.getLogger(__name__)

logger的名称随模块名的变更而变更

logger常用函数:
Logger.setLevel()
Logger.addHandler()
Logger.addFilter()

handler常用函数:
setLevel()
setFormatter()
addFilter() and removeFilter()

formatter通过%s,template和format函数来自定义输出

demo:

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

其中配置文件可以写为配置文件的形式,如下:

logging.config.fileConfig('logging.conf')
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=