logging magic

Vinay Sajip vinay_sajip at yahoo.co.uk
Wed Jun 14 04:42:28 EDT 2006


nicholas.farrell at gmail.com wrote:

> Hi everyone.
>
> I've just been trying to add a bit more granularity to my logging code,
> as the jump from INFO (level 20) to DEBUG (level 10) is a bit too big.
> I was thinking of borrowing a few levels from java: fine (18), finer
> (16) and finest(14).
>
> This is what I've tried:
>
> log = logging.getLogger(appName)
>
> logging.FINE = 18
> logging.FINER = 16
> logging.FINEST = 14
>
> log.fine = lambda msg, self=log, level=logging.FINE: self.log(level,
> msg)
> log.finer = lambda msg, self=log, level=logging.FINER: self.log(level,
> msg)
> log.finest = lambda msg, self=log, level=logging.FINEST:
> self.log(level, msg)
>
> I could expand this to support kwargs, etc, but that's the least of my
> problems.
>
> The real issue is that by adding this extra method into the stack, the
> logging module incorrectly reports the module name/line number. I
> assume it's because logging.log(...) accesses the stack to find out
> where it was being invoked from.
>
> Does anyone know I can add such methods to my log object and still have
> it correctly report the context of the log message?
>
> Thanks to all in advance.

Try using addLevelName (this will ensure that your level names are
correctly formatted in the log), and also try creating your own Logger
subclass which has the custom methods you want.

The logging system does walk up the stack, looking for a stack frame
whose corresponding source file is not the logging package itself. What
is the module name/file number which gets printed?

Regards,

Vinay Sajip




More information about the Python-list mailing list