python

python中的logging模块怎么使用

小亿
82
2024-01-04 01:29:16
栏目: 编程语言

Python中的logging模块用于记录应用程序的运行日志。下面是使用logging模块的基本步骤:

  1. 导入logging模块:
import logging
  1. 配置日志记录器:
logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')
  1. 记录日志:
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
  1. 在控制台输出日志(可选):
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

这样配置后,除了将日志写入文件外,还会在控制台输出日志。

以上是使用logging模块的基本步骤,可以根据实际需求进行更高级的配置和使用。

0
看了该问题的人还看了