Logging Custom Levels?

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Mar 31 13:37:13 EDT 2015


----- Original Message -----
> From: "Didymus" <lynto28 at gmail.com>
> To: python-list at python.org
> Sent: Tuesday, 31 March, 2015 5:20:52 PM
> Subject: Logging Custom Levels?
> 
> Hi,
> 
> I've create a Python file called "log.py" and placed in the custom
> levels:
> 
> # Performance Debug...
> logging.addLevelName(PDEBUG_NUM, "PDEBUG")
> 
> def pdebug(self, message, *args, **kws):
>     """ Performance Debug Message Level """
>     self.log(PDEBUG_NUM, message, *args, **kws)
>         
> logging.Logger.pdebug = pdebug
> 
> 
> This works except that the %(module) and %(lineno) does not print
> properly, it instead prints out as the "log.py" and the line that
> this is on. I think I figured out a way to get the module and line
> from the calling custom level:
> 
> import inspect
> frame = inspect.currentframe()
> filename =
> os.path.splitext(os.path.basename(frame.f_back.f_code.co_filename))[0]
> linenumber = frame.f_back.f_lineno
> 
> 
> My question is how do I pass this into the "self.log" call properly?
> I've tried a few different things without any luck. Any ideas how I
> can pass this into the custom logging level and get it to work?
> 
> Thanks in Advance for any help!
>     Tom

A solution is pretty simple, do not use an intermediate log function pdebug.

import logging
PDEBUG_NUM=20
logging.addLevelName(PDEBUG_NUM, "PDEBUG")
 
logger = logging.getLogger('foo')
logging.basicConfig(level=logging.DEBUG, format='%(message)s %(lineno)d')

logger.log(PDEBUG_NUM, 'This will work :')


If you *really* want to go for the hackish way, forget about the inspect module, the following pdebug function should do the trick:

def pdebug(self, message, *args, **kws):
    if self.isEnabledFor(PDEBUG_NUM):
        self._log(PDEBUG_NUM, message, args, **kws)

Cheers,

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list