Python中不同级别的日志记录

0 投票
1 回答
2168 浏览
提问于 2025-04-18 00:38

不知道为什么,我无法同时让这两个都工作。只有第一个能生效。有没有人知道这是为什么呢?

logging.basicConfig(filename='logs/debug2.log',level=logging.DEBUG)
logging.basicConfig(filename='logs/critical.log',level=logging.CRITICAL)

我不能为不同的日志级别设置不同的日志文件吗?这是Python 2.7的内容。

谢谢大家!

1 个回答

1

看起来你只有一个日志记录器对象,而你在改变它的输出文件和级别。其实你需要创建两个日志记录器对象,并分别配置它们。

下面是来自帮助文档的例子:

import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

撰写回答