Python日志记录 - dictConfig - 子模块的日志记录目标

Python日志记录 - dictConfig - 子模块的日志记录目标

问题描述:

我有一个python日志记录服务器,两个测试应用程序和一个共享模块(submod.py)我希望这两个应用程序都能够将日志事件发送到服务器并使服务器决定如何将它们存储到单独的日志文件中。这很容易,直到共享模块开始记录,我不知道如何让服务器识别子模块发送哪些程序的日志事件以存储到正确的日志文件。Python日志记录 - dictConfig - 子模块的日志记录目标

我的日志服务器是我发现here

的代码稍加修改的版本我试图修改它使用类似于以下的字典日志记录配置:

test_log.conf

"handlers": { 
      "console": { 
       "class": "logging.StreamHandler", 
       "level": "DEBUG", 
       "formatter": "complex", 
       "stream": "ext://sys.stdout" 
      }, 
      "test_01": { 
       "class": "logging.handlers.RotatingFileHandler", 
       "level": "INFO", 
       "formatter": "complex", 
       "filename": "test_01.log", 
       "mode": "a", 
       "backupCount": 5, 
       "encoding": "utf8" 
      }, 
      "test_02": { 
       "class": "logging.handlers.RotatingFileHandler", 
       "level": "INFO", 
       "formatter": "complex", 
       "filename": "test_02.log", 
       "mode": "a", 
       "backupCount": 5, 
       "encoding": "utf8" 
      }, 
      "file": { 
       "class": "logging.handlers.RotatingFileHandler", 
       "level": "INFO", 
       "formatter": "complex", 
       "filename": "root.log", 
       "mode": "a", 
       "backupCount": 5, 
       "encoding": "utf8" 
      } 
     }, 
     "loggers": { 
      "root": { 
       "level": "INFO", 
       "handlers": ["console", "file"] 
      }, 
      "test_01":{ 
       "level": "INFO", 
       "handlers": ["console", "test_01"] 
      }, 
      "test_02": { 
       "level": "INFO", 
       "handlers": ["console", "test_02"] 
      } 
     } 

test_01.py

main_logger = logging.getLogger('') 
main_logger.setLevel(logging.DEBUG) 

socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) 

main_logger.addHandler(socketHandler) 

logging.info('Test 01 main program') 

a = submod.SubClass() 

test_02.py

main_logger = logging.getLogger('') 
main_logger.setLevel(logging.DEBUG) 

socketHandler = logging.handlers.SocketHandler('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT) 

main_logger.addHandler(socketHandler) 

logging.info('Test 02 main program') 

a = submod.SubClass() 

submod.py

class SubClass(object): 
    def __init__(self): 
     log = logging.getLogger() 
     log.debug('Debug') 
     log.info('Info') 
     log.warn('Warning') 
     log.error('Error') 
     log.critical('Critical') 
     print(__name__) 

我怎么能有日志服务器智能地知道从哪里submod.py日志消息当两个test_01和test_02正在调用它。

我对格式化和令人困惑的解释表示歉意,这个问题对我造成了脑损伤。

被修改: 为了清晰和重新措辞不好的解释。

只需使用一个配置文件,您可以在其中根据使用它的程序预定义日志文件的目标。 Python“日志记录”模块完成您需要的所有任务;这里是一个配置文件的例子:http://www.zetadev.com/software/aspen/trunk/doc/html/logging-conf.html

+0

据我了解你引用它的配置并不能解决问题。我试图建立一个动态配置,可以应用于多个使用相同子模块的程序,但需要服务器智能地确定子模块的消息应该保存到每个主程序的日志文件中。 – Chex

+0

知道了,那么这个怎么样? https://docs.python.org/2/howto/logging-cookbook.html#using-logging-in-multiple-modules – postoronnim

+0

这可以工作,我希望在应用程序之间重新使用模块,以便静态分配父项有点痛苦。有没有一种方法来确定调用的“父”?或者,我应该只传递父级的名称,将其作为变量并设置它。 – Chex