【发布时间】:2018-08-05 20:49:03
【问题描述】:
我有一个 python-daemon 进程,它通过 ThreadedTCPServer 记录到一个文件(受食谱示例的启发:https://docs.python.org/2/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network,因为我将有许多这样的进程写入同一个文件)。我正在使用 ipython 控制台中的 subprocess.Popen 控制守护进程的生成,这就是应用程序的运行方式。我能够从主 ipython 进程和守护进程成功写入日志文件,但我无法通过简单地设置 ipython 中的根记录器的级别来更改两者的级别。这应该是可能的吗?还是需要自定义功能来单独设置守护进程的 logging.level?
编辑:根据要求,这里尝试提供一个伪代码示例来说明我想要实现的目标。我希望这是一个足够的描述。
daemon_script.py
import logging
import daemon
from other_module import function_to_run_as_daemon
class daemon(object):
def __init__(self):
self.daemon_name = __name__
logging.basicConfig() # <--- required, or I don't get any log messages
self.logger = logging.getLogger(self.daemon_name)
self.logger.debug( "Created logger successfully" )
def run(self):
with daemon.daemonContext( files_preserve = [self.logger.handlers[0].stream] )
self.logger.debug( "Daemonised successfully - about to enter function" )
function_to_run_as_daemon()
if __name__ == "__main__":
d = daemon()
d.run()
然后在 ipython 中我会运行类似的东西
>>> import logging
>>> rootlogger = logging.getLogger()
>>> rootlogger.info( "test" )
INFO:root:"test"
>>> subprocess.Popen( ["python" , "daemon_script.py"] )
DEBUG:__main__:"Created logger successfully"
DEBUG:__main__:"Daemonised successfully - about to enter function"
# now i'm finished debugging and testing, i want to reduce the level for all the loggers by changing the level of the handler
# Note that I also tried changing the level of the root handler, but saw no change
>>> rootlogger.handlers[0].setLevel(logging.INFO)
>>> rootlogger.info( "test" )
INFO:root:"test"
>>> print( rootlogger.debug("test") )
None
>>> subprocess.Popen( ["python" , "daemon_script.py"] )
DEBUG:__main__:"Created logger successfully"
DEBUG:__main__:"Daemonised successfully - about to enter function"
我认为我可能没有正确处理这个问题,但是我不清楚什么会更好。任何意见,将不胜感激。
【问题讨论】:
-
你好@bazza1988,欢迎来到stackoverflow,没有一个具体、简洁和最小的代码示例来展示你的问题,很难判断你的问题可能是什么。
-
@zmo - 见编辑。我原本希望我的描述足以得到定性的答案。如果您需要更多信息,请告诉我。
标签: python logging python-daemon