Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging retrieve specific handler

Tags:

python

logging

We work on a python program/library for which we would like to set a logging system. Basically we would like to log either on a terminal either on a file. To do so, we will use the excellent logging package embedded in the standard distribution.

The logging level should be customizable by the user via its Preferences. My problem is how to retrieve one of the handler connected to the logger ? I was thinking about something a bit like this:

import logging

class NullHandler(logging.Handler):
    def emit(self,record):
        pass

HANDLERS = {}
HANDLERS['console'] = logging.StreamHandler()
HANDLERS['logfile'] = logging.FileHandler('test.log','w')

logging.getLogger().addHandler(NullHandler())
logging.getLogger('console').addHandler(HANDLERS['console'])
logging.getLogger('logfile').addHandler(HANDLERS['logfile'])

def set_log_level(handler, level):
    if hanlder not in HANDLERS:
        return

    HANDLERS[handler].setLevel(level)

def log(message, level, logger=None):

    if logger is None:
        logger= HANDLERS.keys()

    for l in logger:
        logging.getLogger(l).log(level, message)

As you can see, my implementation implies the use of the HANDLERS global dictionary to store the instances of the handlers I created. I could not find a better way to do so. In that design, it could be said that as I just plugged one handler per logger, the handlers attribute of my loggers objects should be OK, but I am looking for something more general (i.e. how to do if one day one several handlers are plugged to one of my logger ?)

What do you think about this ?

thank you very much

Eric

like image 207
Eurydice Avatar asked May 28 '26 14:05

Eurydice


1 Answers

A little late but here's a way to do it:

When you create a handler you can set the name, so something like following:

import logging

stream_handler = logging.StreamHandler()
# Set name for handler
stream_handler.name = "stream_handler"

logging.getLogger().addHandler(stream_handler)

# Use name to find specific handler from list of all handlers for the logger
for handler in logging.getLogger().handlers:
    if handler.name == "stream_handler":
        print(f"Found stream_handler={stream_handler}")
like image 142
Saravanan Setty Avatar answered May 31 '26 04:05

Saravanan Setty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!