Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the level of the logging record in a custom logging.Handler in Python?

Tags:

python

logging

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?

like image 713
koleto Avatar asked Dec 18 '22 00:12

koleto


1 Answers

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).

like image 161
Alex Martelli Avatar answered Mar 30 '23 00:03

Alex Martelli