tags:

views:

112

answers:

2

Hi, I'd like to have loglevel TRACE (5) for my application as I don't think that debug() is enought. Additionally log(5, msg) isn't what I want.

The question is, how can I add a custom log level to a Python logger?

Actually I've a mylogger.py with the following content:

import logging

@property
def log(obj):
    myLogger = logging.getLogger(obj.__class__.__name__)
    return myLogger

In my code I use it in the following way:

class ExampleClass(object):
    from mylogger import log

    def __init__(self):
        '''The constructor with the logger'''
        self.log.debug("Init runs")

Now I'd like to call self.log.trace("foo bar")

Thanks in advance for your help.

+2  A: 

I think you'll have to subclass the Logger class and add a method called trace which basically calls Logger.log with a level lower than DEBUG. I haven't tried this but this is what the docs indicate.

Noufal Ibrahim
And you'll probably want to replace `logging.getLogger` to return your subclass instead of the built-in class.
S.Lott
ok, do you have any other best practices for `logging`?
tuergeist
+3  A: 

I find it easier to create a new attribute for the logger object that passes the log() function. I think the logger module provides the addLevelName() and the log() for this very reason. Thus no subclasses or new method needed.

import logging

@property
def log(obj):
    logging.addLevelName(5, 'TRACE')
    myLogger = logging.getLogger(obj.__class__.__name__)
    setattr(myLogger, 'trace', lambda *args: myLogger.log(5, *args))
    return myLogger

now

mylogger.trace('This is a trace message')

should work as expected.

LtPinback