【590】Python logging 模块

参考:python logging模块,升级print调试到logging

参考:Python之日志处理(logging模块)


  个人理解:通过日志记录来进行程序调试的各种输出信息,可以设置不同的输出级别,因此可以根据级别的设置来输出不同的信息。

  输出级别:

  • DEBUG
  • INFO
  • NOTICE
  • WARNING
  • ERROR
  • CRITICAL
  • ALERT
  • EMERGENCY

  测试代码:

import logging
import sys

# 获取logger实例,如果参数为空则返回root logger
logger = logging.getLogger("AppName")

# 指定logger输出格式
formatter = logging.Formatter('%(asctime)s %(levelname)-8s: (%(name)s)%(pathname)s %(message)s')

# 文件日志(存储在当前文件的路径内)
file_handler = logging.FileHandler("test.log")
file_handler.setFormatter(formatter)  # 可以通过setFormatter指定输出格式

# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.formatter = formatter  # 也可以直接给formatter赋值

# 为logger添加的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# 指定日志的最低输出级别,默认为WARN级别
logger.setLevel(logging.DEBUG)

# 输出不同级别的log
logger.debug('this is debug info')
logger.info('this is information')
logger.warning('this is warning message')
logger.error('this is error message')
logger.fatal('this is fatal message, it is same as logger.critical')
logger.critical('this is critical message')
# 记录异常信息

try:
    1 / 0
except:
    logger.exception('except:')

# 移除文件日志处理器,那么log文件就不记录这些日志了
logger.removeHandler(file_handler)
logger.debug('this is debug info----2')
#修改日志输出级别
logger.setLevel(logging.ERROR)
logger.info('this is information----2')
logger.warning('this is warning message----2')
logger.error('this is error message----2')
logger.fatal('this is fatal message, it is same as logger.critical----2')
logger.critical('this is critical message----2')

  显示效果:

2021-07-02 15:31:51,522 DEBUG   : (AppName)<ipython-input-1-f60e9cd2b07f> this is debug info
2021-07-02 15:31:51,523 INFO    : (AppName)<ipython-input-1-f60e9cd2b07f> this is information
2021-07-02 15:31:51,524 WARNING : (AppName)<ipython-input-1-f60e9cd2b07f> this is warning message
2021-07-02 15:31:51,525 ERROR   : (AppName)<ipython-input-1-f60e9cd2b07f> this is error message
2021-07-02 15:31:51,526 CRITICAL: (AppName)<ipython-input-1-f60e9cd2b07f> this is fatal message, it is same as logger.critical
2021-07-02 15:31:51,527 CRITICAL: (AppName)<ipython-input-1-f60e9cd2b07f> this is critical message
2021-07-02 15:31:51,528 ERROR   : (AppName)<ipython-input-1-f60e9cd2b07f> except:
Traceback (most recent call last):
  File "<ipython-input-1-f60e9cd2b07f>", line 35, in <module>
    1 / 0
ZeroDivisionError: division by zero
2021-07-02 15:31:51,529 DEBUG   : (AppName)<ipython-input-1-f60e9cd2b07f> this is debug info----2
2021-07-02 15:31:51,529 ERROR   : (AppName)<ipython-input-1-f60e9cd2b07f> this is error message----2
2021-07-02 15:31:51,530 CRITICAL: (AppName)<ipython-input-1-f60e9cd2b07f> this is fatal message, it is same as logger.critical----2
2021-07-02 15:31:51,530 CRITICAL: (AppName)<ipython-input-1-f60e9cd2b07f> this is critical message----2

  

原文地址:https://www.cnblogs.com/alex-bn-lee/p/14963735.html