我有一个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"
我认为我可能没有正确地解决这个问题,但是我不清楚哪种方法更好。任何意见,将不胜感激。
答案 0 :(得分:0)
您在守护程序中创建的记录器与您在ipython中创建的记录器不同。您可以通过只打印两个记录器对象本身来进行测试,以确保它们的内存地址。
我认为更好的模式是在运行守护程序时是否要处于“调试”模式。换句话说,像这样调用popen:
subprocess.Popen( ["python" , "daemon_script.py", "debug"] )
完全由您决定,您可以像上面那样传递一个表示“调试模式已打开”的字符串,也可以传递表示“调试”的日志级别常量,例如: subprocess.Popen([“ python”,“ daemon_script.py”,“ 10”]) (https://docs.python.org/2/library/logging.html#levels)
然后在守护程序的init
函数中,例如使用argv来获取该参数并使用它:
...
import sys
def __init__(self):
self.daemon_name = __name__
logging.basicConfig() # <--- required, or I don't get any log messages
log_level = int(sys.argv[1]) # Probably don't actually just blindly convert it without error handling
self.logger = logging.getLogger(self.daemon_name)
self.logger.setLevel(log_level)
...