本文介绍了自定义Logger类和日志中正确的行号/功能名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Python记录器包装在一个自定义类中,以嵌入一些特定于应用程序的功能,并向开发人员隐藏设置详细信息(设置文件输出,日志记录级别等).为此,我使用以下API创建了一个类:

I'd like to wrap Python logger in a custom class to embed some application-specific functionality and hide setup details from developers (setting file output, logging level, etc). To do this, I created a class with the following API:

__init__(log_level, filename)
debug(msg)
info(msg)
warning(msg)
error(msg)

Logger.debug/info/warning/etc调用通常在日志中写入进行日志调用的函数和行号.但是,使用我的自定义类,写入日志文件的函数和行号始终是相同的(对应于自定义类中的debug()/info()/warning()/error()函数).我希望它保存记录味精的应用程序代码行.有可能吗?

Logger.debug/info/warning/etc calls usually write in the log the function and line number where the log call was made. However, using my custom class, the function and line numbers written to the log file are always the same (correspondent to the debug()/info()/warning()/error() functions inside the custom class). I want it to save the line of application code that logged the msg. Is that possible?

谢谢.

推荐答案

是:sys._getframe(NUM)其中NUM表示您要查找的当前函数之外还有多少个函数.返回的框架对象具有f_linenof_code.co_filename之类的属性.

Yes: sys._getframe(NUM) where NUM says how how many functions outside the current one you are looking for. The returned frame object has attributes like f_lineno and f_code.co_filename.

http://docs.python.org/library/sys.html# sys._getframe

这篇关于自定义Logger类和日志中正确的行号/功能名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:31