Reputation: 8419
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
Upvotes: 9
Views: 7910
Reputation: 438
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}")
Upvotes: 5
Reputation: 91017
You cannot only set the level of a handler, but also of a logger:
import logging
class NullHandler(logging.Handler):
def emit(self,record):
pass
logging.getLogger().addHandler(NullHandler())
logging.getLogger('console').addHandler(logging.StreamHandler())
logging.getLogger('console').info("foo")
logging.getLogger('console').setLevel(1000)
logging.getLogger('console').info("foo")
logging.getLogger('console').setLevel(1)
logging.getLogger('console').info("foo")
Note that the handler's log level is independent of this one and a handler only logs if both levels are reached.
Upvotes: 0