Python 如何记录函数名和文件名
我打包了一个类记录器Python 如何记录函数名和文件名,python,logging,Python,Logging,我打包了一个类记录器 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 %(fu
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)
然后在main函数中创建logger实例。
然后我在另一个类文件file1中使用了这个记录器
def is_path_valid(self, dc_path):
self.logger.debug('Entering with parameter dc_path: %s' %(dc_path))
但写入日志文件的日志是“Tue,2019年3月19日05:41:15调试记录器调试14输入参数dc_路径:/disks”。
我所期望的是“2019年3月19日星期二05:41:15调试文件1是有效的#行号与参数dc_path:/disks一起输入”
我该怎么做?您最终可以使用该模块: 您可以通过以下方式转换debug()方法来实现这一点:
def debug(self, message):
logging.debug('%s - %s', traceback.extract_stack()[-1], message)
注意:您不需要每次调用debug()方法时都调用basicConfig
方法,只要在记录器实例化时调用它即可;请在此处查看有关日志记录的良好实践的更多信息:
根据本节中的说明,为了获得预期的日志输出:
2019年3月19日星期二05:41:15调试文件1为有效路径行号
输入参数dc\u path:/disks
您的格式日志记录属性应如下所示:
'%(asctime)-15s %(levelname)s %(module)s %(filename)s %(lineno)d %(message)s'
请注意从
funcName
到filename
的更改,因为您要查找的是文件名,并且您将获得路径名的:filename部分。已修复此问题,不需要编写自己的记录器类。为什么要创建自己的记录器类,至少在本例中,不提供超出正常日志记录模块的任何额外功能。使用后者,您可以为包或模块设置记录器(不是默认的根记录器,即不使用logging.basicConfig
),并且在模块内部使用logger=logging.getLogger(\uu name\uu)
。自定义记录器仅公开其中一个日志级别,并在每次执行debug
时重新配置日志记录。我建议查看并坚持上面提到的更传统的模式。旁白:不要使用%
将日志字符串与要记录的变量连接起来。使用logger.debug('输入参数dc\u路径:%s',(dc\u路径))
(逗号而不是第二个%
符号)。这在幕后节省了一些时间,因为格式化只在使用日志级别时完成。我只是在这个日志类中粘贴了部分代码(例如错误级别print logging.exception)。我需要在几个模块中记录数据,所以我认为最好创建自己的logger类。谢谢。但如果它太重而无法获得跟踪堆栈?我想找到一个简单的方法。为什么它会“太重而无法获取堆栈跟踪”?我认为traceback.extract_stack()[-1]应该很慢,我不需要获取堆栈跟踪,只想使用日志记录来记录信息。不,这不是根本原因,我也尝试了filename,但它仍然是logger.py,没有在日志文件中调用模块filename。
'%(asctime)-15s %(levelname)s %(module)s %(filename)s %(lineno)d %(message)s'