我有一个python日志服务器,两个测试应用程序和一个共享模块(submod.py)我希望两个应用程序能够将日志事件发送到服务器,并让服务器决定如何将它们存储到单独的日志文件中。这很容易,直到共享模块开始记录,我不知道如何允许服务器识别子模块发送日志事件的程序以存储到正确的日志文件。
我的日志记录服务器是我找到的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__)
当test_01和test_02都在调用时,如何让日志记录服务器智能地知道从submod.py记录消息的位置。
我为格式化和令人困惑的解释道歉,这个问题在这一点上造成了脑损伤。
编辑: 为了清楚起见并重写一个不好的解释。
答案 0 :(得分:0)
只需使用配置文件,您可以根据使用它的程序预定义日志文件的目标。 Python" logging"模块完成您需要的所有任务;以下是配置文件的示例:http://www.zetadev.com/software/aspen/trunk/doc/html/logging-conf.html