文章目录
前言
创作开始时间:2021年3月25日11:35:28
如题。之前其实写过一篇logging博客,但是那时候不求甚解,所以不得劲。这里再仔细研究一下,并记录之。
主要参考:
一、logging介绍
1.1 基本概念
Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the level or severity.
logging是一个追踪软件运行过程中发生事件的一种方式。
logging用level或者severity来表示事件的重要性。
1.2 使用场景
场景/需求 | 日志方式 |
---|---|
终端展示输出 | print()就行 |
记录程序状态 | logging.info() 或者logging.debug() |
提出warning | logging.warning() |
报告error(错误) | Raise an exception |
处理/抑制error不报错 | logging.error(), logging.exception() or logging.critical() |
1.3 logging level(日志级别分类)
Level | 用法 |
---|---|
DEBUG | 调试需要的详细信息 |
INFO | 确认程序正常工作 |
WARNING | 程序仍旧正常工作,但是报警未来可能出现的问题(如空间不够) |
ERROR | 程序某些功能不能继续运行 |
CRITICAL | 非常严重的错误,程序无法继续运行 |
The default level is WARNING, which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise.
默认是WARNING级别。
logging的两种方式:
- 输出到控制台
- 输出到日志文件
1.4 示例代码
import logging
import os
# 路径获取
cur_dir = os.path.abspath(__file__).rsplit("/", 1)[0]
log_path = os.path.join(cur_dir, "example.log")
# encoding='utf-8'
logging.basicConfig(filename=log_path, level=logging.DEBUG,
filemode = 'w', format='%(levelname)s:%(asctime)s:%(message)s', datefmt='%Y-%d-%m %H:%M:%S')
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like? resund and Malm?')
logging.critical("critical")
注意:
- 有的python版本的logging.basicConfig()没有
encoding
这个参数! level=logging.DEBUG
表明所有>= DEBUG 这个level的都会被输出;filemode = 'w'
表示不会追加写,而是会重新写;format='%(levelname)s:%(asctime)s:%(message)s'
参考:https://docs.python.org/3/library/logging.html#logging.basicConfigdatefmt
参考https://docs.python.org/3/library/time.html#time.strftime
二、logging的三种配置方式
2.1 直接配置
Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
下面这串代码功能还挺强大:
1)可以输出到控制台(终端);
2)还可以同时写入到文件,
3)而且配置也很方便,功能挺强大的
以下供参考。
logger = logging.getLogger(__file__)
logger.setLevel(logging.DEBUG)
# set two handlers
log_file = "{}.log".format(__file__)
# rm_file(log_file)
fileHandler = logging.FileHandler(os.path.join(cur_dir, log_file), mode = 'w')
fileHandler.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
# set formatter
formatter = logging.Formatter('[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
consoleHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
# add
logger.addHandler(fileHandler)
logger.addHandler(consoleHandler)
logger.info("test")
这个很好理解的,尤其是看了:
- https://docs.python.org/3/howto/logging.html
之后,是真的好理解,所以这里就不多讲了。而且vscode可以一键直接点到第三方库的函数(比如logging.Formatter
)里面去看,里面的注释也很丰富。所以这里就不多解释了。
注意: 后面两种就不解读了,有一种我觉得就已经很简洁,也够用了。所以后续更新再说。
2.2 从配置文件中读取配置
Creating a logging config file and reading it using the fileConfig() function.
2.3 从包含配置信息的字典配置
Creating a dictionary of configuration information and passing it to the dictConfig() function.
小结
以上。
创作结束时间:2021年3月25日19:11:02