了解python中的logging

在写python的时候碰到个有关日志的问题, 究其原因, 还是在于自己不了解logging的使用方法, 这里简单记录一下.

有关logging

有关logging的说明在官方文档上面写得很详细, 基础用法很简单:

from document
1
2
3
4
5
### 这里使用的是root logger

import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything

同样的, 我们可以创建不同的日志对象, 然后使用这些日志对象来打日志:

from document
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

问题

在写程序的时候, 一开始就调用了logging.basicConfig来设置一些值, 这里会有问题:

logging.basicConfig([**kwargs])

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already has handlers configured for it

如果像这样, 之后在应用中又自己创建了日志对象来写日志, 就会遇到日志重复写的问题. stackoverflow上有个类似的问题.

另外一个值得注意的是Loggoer.propate的说明:

f you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times.

附上一张官方的图:

还是理解比较重要~

Comments