python.logging:为什么我的non-basicConfig设置不起作用? [英] python.logging: Why does my non-basicConfig setting not work?

查看:325
本文介绍了python.logging:为什么我的non-basicConfig设置不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从主模块和所有子模块登录到单个日志文件.

I want to log to a single log file from main and all sub modules.

从主文件(我在其中定义记录器)发送的日志消息按预期工作.但是缺少从调用发送到导入函数的函数.

The log messages send from a main file, where I define the logger, work as expected. But the ones send from a call to an imported function are missing.

如果我使用下面的示例1中的logging.basicConfig,它可以正常工作. 但是第二个允许更多自定义设置的示例不起作用.

It is working if I use logging.basicConfig as in Example 1 below. But the second example which allows for more custom settings does not work.

有什么想法吗?

# in the submodule I have this code
import logging
logger = logging.getLogger(__name__)

示例1-工作

我在这里创建两个处理程序,然后将它们传递给basicConfig:

Here I create two handlers and just pass them to basicConfig:

# definition of root looger in main module

formatter = logging.Formatter(fmt="%(asctime)s %(name)s.%(levelname)s: %(message)s", datefmt="%Y.%m.%d %H:%M:%S")   

handler = logging.FileHandler('logger.log')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

handler2 = logging.StreamHandler(stream=None)
handler2.setFormatter(formatter)
handler2.setLevel(logging.DEBUG)

logging.basicConfig(handlers=[handler, handler2], level=logging.DEBUG)
logger = logging.getLogger(__name__)

示例2-不起作用

在这里,我创建两个处理程序,并将它们addHandler()到根记录器:

Here I create two handlers and addHandler() them to the root logger:

# definition of root looger in main module

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

handler = logging.FileHandler('logger.log')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
#handler.setLevel(logging.ERROR)
logger.addHandler(handler)

handler = logging.StreamHandler(stream=None)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

推荐答案

您需要在软件的主模块中配置(唯一的)根记录器.这是通过调用

You need to configure the (one and only) root logger in the main module of your software. This is done by calling

logger = logging.getLogger() #without arguments

代替

logger = logging.getLogger(__name__)

(有关记录的Python文档)

第二个示例使用您的脚本名称创建一个单独的子记录器.

The second example creates a separate, child logger with the name of your script.

如果子模块中未定义任何处理程序,则日志消息将传递给根记录器以进行处理.

If there are no handlers defined in the submodules, the log message is being passed down to the root logger to handle it.

一个相关的问题可以在这里找到: Python日志记录-如何继承根记录器级别&处理程序

A related question can be found here: Python Logging - How to inherit root logger level & handler

这篇关于python.logging:为什么我的non-basicConfig设置不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆