Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #88397

Re: Logging Custom Levels?

Date 2015-03-31 19:37 +0200
From Jean-Michel Pichavant <jeanmichel@sequans.com>
Subject Re: Logging Custom Levels?
Newsgroups comp.lang.python
Message-ID <mailman.384.1427823434.10327.python-list@python.org> (permalink)

Show all headers | View raw


----- Original Message -----
> From: "Didymus" <lynto28@gmail.com>
> To: python-list@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.

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: Logging Custom Levels? Jean-Michel Pichavant <jeanmichel@sequans.com> - 2015-03-31 19:37 +0200
  Re: Logging Custom Levels? Didymus <lynto28@gmail.com> - 2015-04-01 04:51 -0700

csiph-web