PHP笔记网

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

作者:Albert.Wen  添加时间:2020-10-08 00:13:48  修改时间:2024-11-29 00:37:09  分类:10.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()