Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging: Set handlers for all loggers of used modules

Tags:

python

logging

I have my main script that interprets cli commands with argparse and then starts the application by calling the according stuff form an other module (made by myself).

My question now is how I can attach a handler to the logger from that module. The logger is retrieved with

logger = logging.getLogger(__name__)

I hence put following in my main script:

consoleHandler = logging.StreamHandler()
logger = logging.getLogger('MyModule')
logger.addHandler(consoleHandler)

However there is 0 logging output from 'MyModule'. Log levels are correct, eg there should be an output.

In MyModule I have the following:

logging.getLogger(__name__).addHandler(logging.NullHandler())

However removing that makes no difference.

So how can I correctly attach a handler to the logger of MyModule?

like image 983
beginner_ Avatar asked Dec 05 '13 05:12

beginner_


People also ask

What is Handler in logging Python?

Python Logging Handler The log handler is the component that effectively writes/displays a log: Display it in the console (via StreamHandler), in a file (via FileHandler), or even by sending you an email via SMTPHandler, etc. Each log handler has 2 important fields: A formatter which adds context information to a log.

How do I create a multiple logging level in Python?

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO.


1 Answers

The best example of adding handler to logger is the one from Docs, See below.

Did you added consoleHandler with setLevel() and the Formatter() ?

As for this line: logging.getLogger(__name__).addHandler(logging.NullHandler())

Why are you using it this way? I would recommend to follow the next code for adding an handler the right way.

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
like image 199
Kobi K Avatar answered Nov 03 '22 01:11

Kobi K