Logging: Formatter: name of the function

Sylvain Defresne sylvain.defresne at free.fr
Fri Dec 23 16:34:42 EST 2005


Le vendredi 23 décembre 2005 à 16:23 +0100, Gregor Horvath a écrit :
> Hi,
> 
> Is there a possibility to format a log message to give the function name 
> where the log appears?
> 
> Example
> 
> import logging
> 
> def aTestFunction():
>    logger.debug("This is a message")
> 
> The log should read:
> 
> aTestFunction  This is a message.

You can use the currentframe of the inspect module. For example :
        
        >>> import inspect
        >>> def debug(string):
        ...     frame = inspect.currentframe(1)
        ...     print frame.f_code.co_name, string
        >>> def a_test_function():
        ...     debug("This is a message")
        >>> a_test_function()
        a_test_function This is a message

But please take note that this is not recommended. As stated in the
documentation of inspect.currentframe : "[t]his function should be used
for internal and specialized purposes only."
-- 
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?




More information about the Python-list mailing list