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

查看:44
本文介绍了如何在 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).

%(filename)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天全站免登陆