Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where does python logging module write log by default?

I have a python script run by jenkins. logging module is used.

logging.basicConfig(filename="/tmp/test.log",
                    format="%(asctime)s %(levelname)s %(message)s",
                    filemode="a",
                    level=logging.INFO)

If the above config removed, I cannot find the log generated by the following statement:

logging.info("xxxxxxx")

I did not find it in syslog of the jenkins machine. I did not find it in the jenkins console output.

Any hints? Thanks

like image 416
BAE Avatar asked Jun 07 '18 21:06

BAE


2 Answers

The help for the logging module says:

The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger.

As pointed out in the (now deleted) comment, this description is for basicConfig() which indeed is not called immediately. What really happens is that the root logger is initialized in a functionally equivalent way and that's what is used as the default logger. It is actually initialized in two phases: at module load time, the root logger is initialized like this:

root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)

but no handler is attached:

>>> logging.root.__dict__
{'name': 'root', 'parent': None, 'handlers': [], 'level': 30, 'disabled': 0, 'propagate': 1, 'filters': []}

When a logging.warning() (or error() or info() or ...) is called, basicConfig() is called which adds the StreamHandler to sys.stderr:

def warning(msg, *args, **kwargs):
"""
Log a message with severity 'WARNING' on the root logger.
"""
if len(root.handlers) == 0:
    basicConfig()
root.warning(msg, *args, **kwargs)

This is python2.7. I assume python3 works the same way but I have not checked.

like image 28
NickD Avatar answered Oct 22 '22 09:10

NickD


By default, logging writes to stderr. The reason you're not seeing the statement printed is because the default log level is warning.

>>> import logging
>>> logging.error('a message!')
ERROR:root:a message!
>>> logging.warning('a message!')
WARNING:root:a message!
>>> logging.info('a message!')
>>>
like image 147
munk Avatar answered Oct 22 '22 07:10

munk