如何在Python中记录源文件名和行号 [英] How to log source file name and line number in Python

查看:152
本文介绍了如何在Python中记录源文件名和行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能装饰/扩展python标准的日志记录系统,以便在调用日志记录方法时也将文件和被调用文件的行号或调用它的方法记录在日志中?

Is it possible to decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it?

推荐答案

当然,请检查格式化程序.具体来说就是lineno和pathname变量.

Sure, check formatters in logging docs. Specifically the lineno and pathname variables.

%(pathname)s (发出日志记录调用的源文件的完整路径名)(如果有).

%(pathname)s Full pathname of the source file where the logging call was issued(if available).

%(文件名)s 路径名的文件名部分.

%(filename)s Filename portion of pathname.

%(module)s 模块(文件名的名称部分).

%(module)s Module (name portion of filename).

%(funcName)s 包含日志记录调用的函数的名称.

%(funcName)s Name of function containing the logging call.

%(lineno)d 发出记录调用的源行号(如果有).

%(lineno)d Source line number where the logging call was issued (if available).

看起来像这样:

formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')

这篇关于如何在Python中记录源文件名和行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆