此代码段创建一个日志记录筛选器,将ERROR级别及更高级别放入控制台,将DEBUG及更高级别放入日志文件中。我似乎无法弄明白的是如何在我的各种模块中重用该配置,以便我写入相同的日志文件,但名称正确指示生成的模块消息。
提前致谢!
import logging
default_formatter = logging.Formatter(
"%(asctime)s:%(name)s:%(levelname)s:%(message)s")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(default_formatter)
file_handler = logging.FileHandler("error.log", "a")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)
noralog = logging.getLogger(__name__)
noralog.setLevel(logging.DEBUG)
noralog.addHandler(console_handler)
noralog.addHandler(file_handler)
noralog.debug('PUT ME ONLY IN THE FILE')
noralog.error('STREAM AND FILE')
答案 0 :(得分:0)
这似乎有效,但我不确定它是最好的解决方案: #noralog.py def setup_logging(localname): 导入日志记录
default_formatter = logging.Formatter(
"%(asctime)s:%(name)s:%(levelname)s:%(message)s")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(default_formatter)
file_handler = logging.FileHandler("error.log", "a")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)
noralog = logging.getLogger(localname)
noralog.setLevel(logging.DEBUG)
noralog.addHandler(console_handler)
noralog.addHandler(file_handler)
return noralog
#othermod.py
import noralog
ff = noralog.setup_logging(__name__)
ff.debug('PUT THIS ONLY IN FILE LOG')
ff.error('PUT THIS IN STREAM AND FILE LOG')