【详解】Python logging 的用法:从概念、场景到三种配置方式

前言

创作开始时间: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()
提出warninglogging.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. 输出到控制台
  2. 输出到日志文件

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")

注意:

二、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

参考文献

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值