TL;DR
INDEX = 0
logger.handlers[INDEX].setStream( open('/path/to/new/log/file.log', 'a') )
import sys
logger.handlers[INDEX].setStream( sys.stdout )
logger.handlers[INDEX].setStream( open('/dev/ttys010', 'a') )
注册了一个
logging.FileHandler
到你的记录器之后,你可以进入其内部并在运行时更改它所输出的流。
确保
INDEX
访问记录器中正确的处理程序。如果你只添加了一个
FileHandler
,那么它应该是索引
0
。
首先,根据日志记录文档建议的习惯用法,你需要获取一个以特定包、模块、类或函数的 __name__ 命名的新记录器实例。
#: class
>>> class A:
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
>>>A().logger
<Logger A (WARNING)>
>>> def func():
logger = logging.getLogger(func.__name__)
print(logger)
>>> func()
<Logger func (WARNING)>
>>> logger = logging.getLogger( __name__ )
>>> logger
<Logger __main__ (WARNING)>
>>> logger = logging.getLogger( __package__ )
>>> logger
<RootLogger pkg (WARNING)>
接下来,如果您为记录器注册了一个
logging.FileHandler
处理程序,如下所示:
logger.addHandler( logging.FileHandler('/tmp/logfile.log', 'a') )
然后,您可以通过替换输出流来更改它输出的文件:
INDEX = 0
logger.handlers[INDEX].setStream( open('/path/to/new/log/file.log', 'a') )
import sys
logger.handlers[INDEX].setStream( sys.stdout )
logger.handlers[INDEX].setStream( open('/dev/ttys010', 'a') )
If your curious, found this in a few minutes, by doing a bit of digging like so (in ipython
and python
interpreters):
>>> import logging
>>> logger = logging.getLogger( __name__ )
>>> logger.addHandler( logging.FileHandler('/tmp/logfile', 'a') )
>>> globals()
>>> dir(logger)
>>> dir(logger.handlers)
>>> logger.handlers
>>> logger.handlers[0]
>>> dir(logger.handlers[0])
>>> logger.handlers[0].__dict__
>>> logger.handlers[0].__dict__['baseFilename']
>>> logger.handlers[0].__dict__['baseFilename'] = '/tmp/logfile.log'
>>> logger.info(f'hello world')
>>> logger.handlers[0].__dict__['stream']
>>> dir(logger.handlers[0].__dict__['stream'])
>>> logger.handlers[0].__dict__['stream'].__dict__
>>> logger.handlers[0].__dict__['stream'] = open('/tmp/logfile.log','a')
>>> logger.info(f'hello world again')
>>> logger.info(f'hey it worked')
>>> logger.handlers[0].setStream( open('/tmp/otherlogfile.log','a') )
>>> logger.info(f'hello world again')
>>> logger.info(f'hey it worked')