tags:

views:

47

answers:

1

I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets.

For example:

log = logging.getLogger('application')

log.progress('time remaining %d sec' % i)
    custom method for logging to:
            - database status filed
            - console custom handler showing changes in a single console line

log.data(kindOfObject)
    custom method for logging to:
            - database
            - special data format

log.info
log.debug
log.error
log.critical
    all standard logging methods:
        - database status/error/debug filed
        - console: append text line
        - logfile

If I use a custom LoggerHandler by overriding the emit method, I can not distinguishe the level of the logging record. Is there any other posibility to get in runtime information of the record level?

class ApplicationLoggerHandler(logging.Handler):

  def emit(self, record):
    # at this place I need to know the level of the record (info, error, debug, critical)?

Any suggestions?

+2  A: 

record is an instance of LogRecord:

>>> import logging
>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)

and your method can just access the attributes of interest (I'm splitting dir's result for ease of reading):

>>> dir(rec)
['__doc__', '__init__', '__module__', '__str__', 'args', 'created',
 'exc_info', 'exc_text', 'filename', 'funcName', 'getMessage', 'levelname',
 'levelno', 'lineno', 'module', 'msecs', 'msg', 'name', 'pathname', 'process',
 'processName', 'relativeCreated', 'thread', 'threadName']
>>> rec.levelno
1
>>> rec.levelname
'Level 1'

and so on. (rec.getMessage() is the one method you use on rec -- it formats the message into a string, interpolating the arguments).

Alex Martelli
Thank you very much!
koleto
@koleto, you're welcome!
Alex Martelli