【发布时间】:2019-03-19 10:11:46
【问题描述】:
我打包了一个类Logger。
class Logger:
def __init__(self, logfile):
self.log_file = logfile
def debug(self, message):
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s %(levelname)s %(module)s %(funcName)s %(lineno)d %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename=self.log_file,
filemode='w')
logging.debug(message)
然后我在主函数中创建记录器实例。 然后我在另一个类文件file1中使用了这个记录器。
def is_path_valid(self, dc_path):
self.logger.debug('Entering with parameter dc_path: %s' %(dc_path))
但是这个日志写入日志文件是“Tue, 19 Mar 2019 05:41:15 DEBUG logger debug 14 Entering with parameter dc_path: /disks”。 我期望的是“Tue, 19 Mar 2019 05:41:15 DEBUG file1 is_path_valid #line_number Entering with parameter dc_path: /disks”
我该怎么办?
【问题讨论】:
-
为什么要创建自己的记录器类,至少在这个例子中,它没有提供任何超出正常记录模块的额外内容。使用后者,您为包或模块设置记录器(不是默认的根记录器,即不使用
logging.basicConfig),在模块内部,您使用logger = logging.getLogger(__name__)。 -
您的自定义记录器仅公开其中一个日志级别,并在每次
debugged 时重新配置日志记录。我建议查看the docs 并坚持使用上述更传统的模式。 -
旁白:不要使用
%将您的日志字符串与要记录的变量连接起来。使用logger.debug('Entering with parameter dc_path: %s', (dc_path))(逗号而不是第二个%符号)。这节省了一些幕后时间,因为格式化仅在使用日志级别时完成。 -
我只是在这个logger类中粘贴了部分代码(比如error level print logging.exception)。我需要在几个模块中记录数据,所以我认为最好创建自己的记录器类。