更新时间:2023-02-07 18:35:21
之所以会发生这种情况,是因为默认情况下,您的logger_3
也是
This happens because your logger_3
by default also propagates log events to its parent logger, the root logger.
如果您使用 basicConfig()
,则是根记录器默认情况下会附加StreamHandler
,这也会导致您的消息也出现在控制台上.
If you use basicConfig()
, the root logger will have a StreamHandler
attached to it by default which causes your message to also end up on the console.
为防止这种情况,您可以设置logger_3.propagate = False
,或仅将处理程序直接附加到根记录器(这是最常用的设置),然后使用过滤器以控制输出的位置.
To prevent this, you can either set logger_3.propagate = False
, or only attach handlers directly to your root logger (which is the most common used setup) and use logging levels and filters to control where your output goes.
仅将处理程序附加到根记录器的示例如下:
An example for only attaching your handlers to the root logger could look like this:
import logging
from logging.handlers import TimedRotatingFileHandler
format = '%(asctime)s: %(levelname)s: %(message)s'
logging.basicConfig(format=format, level=logging.INFO)
logger = logging.getLogger(__name__)
handler = TimedRotatingFileHandler('timerotate.log',
when='s',
interval=2,
backupCount=10)
handler.setLevel(logging.DEBUG)
logging.root.addHandler(handler)
logger.info('This will end up on console and in timerotate.log')
logger.debug('This will only end up in timerotate.log')
basicInfo()
将级别为INFO
的StreamHandler
附加到登录到stdout
的根记录器-但仅级别为
basicInfo()
attaches a StreamHandler
with level INFO
to the root logger that logs to stdout
- but only messages with level INFO
or higher.
然后再附加一个级别为DEBUG
的处理程序,这样它将把级别为DEBUG
或更高级别的每条消息记录到timerotate.log
.这是一个非常简单的示例,它使用不同的日志级别来确定输出最终到达的位置-使用这种方法,您无法将特定的 only 语句发送到控制台,而不能将另一条 only 到文件.
You then attach a second handler with level DEBUG
, so it will log every message with level DEBUG
or higher to timerotate.log
. This is a very simple example that uses different log levels to determine where output ends up - using this approach you can't send a particular statement only to the console, and a different one only to a file.
如果您需要更精细的控制,则可以例如在 extra
关键字参数,在登录时使用
If you need more fine grained control, you could for example pass some data in the extra
keyword argument when logging, and add a filter to any of your handlers to only emit messages that match certain criteria.
但是,如果您只是想直接从代码中控制一条特定消息应该发送到一个文件,并且只发送到该文件,那么将logger_3.propagate
设置为False
并使用它可能是最简单的您已经描述的设置.
But, if you simply want to be able to directly control from your code that a particular message should go to a file, and only that file, then it's probably easiest to simply set logger_3.propagate
to False
, and use the setup you already described.