python基础:logging的使用

  log里的优先级如下表,DEBUG优先级最低,CRITICAL优先级最高

LevelWhen it’s used
DEBUG Detailed information, typically of interest only when diagnosing problems.
INFO Confirmation that things are working as expected.
WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR Due to a more serious problem, the software has not been able to perform some function.
CRITICAL A serious error, indicating that the program itself may be unable to continue running.

1、在控制台输出log信息

# 在控制台打印log
import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything
# 输出为: WARNING:root:Watch out!

  以上代码之所以不会输出info信息,是因为log默认优先级为warning

2、将log信息输出保存到文件中

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

  以上代码会在当前路径下创建一个example.log文件,文件内容如下:

    DEBUG:root:This message should go to the log file

    INFO:root:So should this

    WARNING:root:And this, too

  运行代码多次时,每次都会在example.log文件末尾追加新的内容。可以设置参数filemode='w’,改变文件写入模式。例如:

# 每次从头开始刷新example.log文件,以前的日志信息会丢失
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

3、打印多个模块里的日志信息

假如你的程序中有多个python文件,logging可以输出每个文件中的log信息,代码如下:

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()
# mylib.py
import logging

def do_something():
    logging.info('Doing something')

  运行myapp.py文件,myapp.log日志文件中将会保存以下日志内容:

    INFO:root:Started

    INFO:root:Doing something

    INFO:root:Finished

4、Logging variable data

一个简单的代码示例,给打印的日志信息传入参数

import logging
logging.warning('%s before you %s','Look','leap!')
#输出:WARNING:root:Look before you leap!

可以指定日志输出信息的格式,代码如下:

import logging
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this,too')
'''
输出:
    DEBUG:This message should appear on the console
    INFO:So should this
    WARNING:And this,too
'''

在日志中输出时间信息:

import logging
logging.basicConfig(format='%(asctime)s:%(message)s',level=logging.DEBUG)
logging.warning('is when this event was logged')
'''
输出:
    2017-12-19 14:18:54,656:is when this event was logged
'''

设置输出时间信息的格式:

import logging
logging.basicConfig(format='%(asctime)s:%(message)s',level=logging.DEBUG, datefmt='%m/%d/%Y/ %I:%M:%S %p')
logging.warning('is when this event was logged')
'''
输出:
    12/19/2017/ 02:23:07 PM:is when this event was logged
'''

logging进阶

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  • Loggers expose the interface that application code directly uses.
  • Handlers send the log records (created by loggers) to the appropriate destination.
  • Filters provide a finer grained facility for determining which log records to output.
  • Formatters specify the layout of log records in the final output.

Log event information is passed between loggers, handlers, filters and formatters in a LogRecord instance.

给logger命名,一般使用模块名给logger命名,方便跟踪logger的位置信息,代码如下:

logger=logging.getLogger(__name__)

更多用法,请参考python官方文档:https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial

原文地址:https://www.cnblogs.com/hypnus-ly/p/8065878.html