Issue
I study logging module recording some message recently. I want to pass a self-defined log path to the dict configuration. For the sake of calling it conveniently, I encapsulate some code into a class.
Now my problem is when I call it, which does't work. The effect which I expect is logging the message both into the console and /tmp/xxxx.log.
Here is the code.(Sorry about my poor English)
#!/usr/bin/env python3
import logging
from logging.config import dictConfig
debug = True
class RequireDebugTrue(logging.Filter):
def filter(self, record):
return debug
logconf_dict = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'debug_fmt': {
'format': '[%(asctime)s][%(threadName)s:%(thread)d][%(name)s:'
'%(levelname)s][%(module)s:%(funcName)s(%(lineno)d)]:%(message)s'
},
'prod_fmt': {
'format': '[%(asctime)s][%(name)s:%(levelname)s]'
'[%(module)s:%(funcName)s(%(lineno)d)]:%(message)s'
}
},
'filters': {
'require_debug_true': {
'()': RequireDebugTrue,
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'debug_fmt',
'filters': ['require_debug_true']
},
'localfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'prod_fmt',
'filename': '/tmp/running.log',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'encoding': 'utf8'
},
},
'loggers': {
'debug_mode': {
'handlers': ['console', 'localfile'],
'level': 'DEBUG',
'propagate': True,
},
'prod_mode': {
'handlers': ['localfile'],
'level': 'DEBUG',
'propagate': True,
},
}
}
class Get_Logger(object):
def __init__(self, logfile, log_handler):
self.log_handler = log_handler
self.logfile = logfile
def get_logger(self):
logconf_dict["handlers"]["localfile"]["filename"] = self.logfile
dictConfig(logconf_dict)
logger = logging.getLogger(self.log_handler)
return logger
if __name__ == '__main__':
logfile = "/tmp/xxxx.log"
logger_obj = Get_Logger("debug_mode", logfile)
logger = logger_obj.get_logger()
logger.debug("This is one test.")
If I disable the encapsulated code, and call the code inside directly, which works fine. Good codes like this:
logconf_dict["handlers"]["localfile"]["filename"] = "/tmp/xxxx.log"
dictConfig(logconf_dict)
logger = logging.getLogger("debug_mode")
logger.debug("This is one test.")
Can anyone give me some help?
Solution
The solution is just changing the position between logfile and log_handler. Wrong code line: def init(self, logfile, log_handler): Right code line: def init(self, log_handler, logfile): Silly of me. Sorry to interrupt.
Answered By - a_noob
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.