不灭的焱

革命尚未成功,同志仍须努力

作者:php-note.com  发布于:2020-10-08 00:09  分类:Python/数据分析  编辑

项目需求

  1. 控制台输出所有日志;
  2. 单独文件记录Error/Critical级别的日志;

日志配置封装

自定义的 log_util.py 文件内容:

import logging

logger = logging.getLogger("stock_trader")
logger.setLevel(logging.INFO)
logger.propagate = False  # 关闭向上传递的功能

# 文本格式
formatter = logging.Formatter(
    "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
    "%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s\n"
    "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
    "%(message)s"
)

# 控制台 处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.handlers.append(console_handler)

# 文本 Error/Critical 处理器
file_error_handler = logging.FileHandler('log_error.txt', encoding='UTF-8')
file_error_handler.setLevel(logging.ERROR)
file_error_handler.setFormatter(formatter)
logger.handlers.append(file_error_handler)


# 针对 exception() 特殊设置封装一下
def logger_exception(err_msg):
    logger.exception(err_msg, stack_info=True)

使用示例

logger.debug('aaa')  # 注意:此条日志不会被输出
logger.info('bbb')
logger.error("发生一个严重错误")

logger.setLevel(logging.DEBUG)  # 动态改变 日志级别
logger.debug('ccc')
logger.info('ddd')

输出:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2020-10-08 10:17:37,456 [INFO] test.py:6
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
bbb
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2020-10-08 10:17:37,456 [ERROR] test.py:7
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
发生一个严重错误
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2020-10-08 10:17:37,456 [DEBUG] test.py:10
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ccc
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2020-10-08 10:17:37,456 [INFO] test.py:11
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ddd

 

 

相关文章:

Python日志处理,logging模块 入门教程 (1)

Python日志处理,logging模块 捕获异常 logger.exception()