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 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?
Thanks in advance.
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 likef_lineno
andf_code.co_filename
.http://docs.python.org/library/sys.html#sys._getframe
It is possible to generate a log wrapper if you are willing to re-implent a little bit of the standard logging module. The trick is to write your own findCaller() method that knows how to ignore your logging-wrapper source-file when interpreting back-traces.
in logwrapper.py:
And an example of using it:
Here's yet another stab at rewriting
findCaller
. This lets you customize the extra stack frame depth on a per-function basis.Based on @Will Ware's answer. Another option is to overwrite
findCaller
method and use custom class as default logger: