Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print current logging configuration used by the python logging module?

Tags:

python

logging

I'm using the python logging module.

I update the logging config using logging.dictConfig().

I would like a way to read the current configuration (e.g. level) used by each logger and print it.

How can I get and print this information?

like image 272
morfys Avatar asked Jul 23 '15 23:07

morfys


People also ask

How do I print logging info in Python?

Python - Print Logs in a File. If you want to print python logs in a file rather than on the console then we can do so using the basicConfig() method by providing filename and filemode as parameter. The format of the message can be specified by using format parameter in basicConfig() method.

What is logging config in Python?

The logging configuration functionality tries to offer convenience, and in part this is done by offering the ability to convert text in configuration files into Python objects used in logging configuration - for example, as described in User-defined objects.

What is logging logger in Python?

Logger : This is the class whose objects will be used in the application code directly to call the functions. LogRecord : Loggers automatically create LogRecord objects that have all the information related to the event being logged, like the name of the logger, the function, the line number, the message, and more.

What is logging module in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.


2 Answers

From Simeon's comment, the logging_tree package lets you print out the details of the current logging configuration.

>>> import logging >>> logging.getLogger('a') >>> logging.getLogger('a.b').setLevel(logging.DEBUG) >>> logging.getLogger('x.c') >>> from logging_tree import printout >>> printout() <--""    Level WARNING    |    o<--"a"    |   Level NOTSET so inherits level WARNING    |   |    |   o<--"a.b"    |       Level DEBUG    |    o<--[x]        |        o<--"x.c"            Level NOTSET so inherits level WARNING >>> # Get the same display as a string: >>> from logging_tree.format import build_description >>> print(build_description()[:50]) <--""    Level WARNING    |    o<--"a"    |   Leve 
like image 125
Don Kirkby Avatar answered Sep 22 '22 23:09

Don Kirkby


Logging configuration are stored in logging.root.manager.

From there you can access every logging parameters, example : logging.root.manager.root.level to get the logging level of your root logger.

Any other loggers can be accessed through logging.root.manager.loggerDict['logger_name'].

Here is an example on how to get the formatter used by a custom logger:

>>> import logging >>> import logging.config >>> config = {"version": 1, ...     "formatters": { ...         "detailed": { ...             "class": "logging.Formatter", ...             "format": "%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s"}}, ...     "handlers": { ...         "console": { ...             "class": "logging.StreamHandler", ...             "level": "WARNING"}, ...         "file": { ...             "class": "logging.FileHandler", ...             "filename": "mplog.log", ...             "mode": "a", ...             "formatter": "detailed"}, ...         "foofile": { ...             "class": "logging.handlers.RotatingFileHandler", ...             "filename": "mplog-foo.log", ...             "mode": "a", ...             "formatter": "detailed", ...             "maxBytes": 20000, ...             "backupCount": 20}}, ...     "loggers": { ...         "foo": { ...             "handlers": ["foofile"]}}, ...     "root": { ...         "level": "DEBUG", ...         "handlers": ["console", "file"]}} >>> logging.config.dictConfig(config) >>> logging.root.manager.loggerDict['foo'].handlers[0].formatter._fmt '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s' 

Handlers parameters can also be found in logging._handlers.data.

>>> logging._handlers.data['file']().__dict__  {'baseFilename': '/File/Path/mplog.log',   'mode': 'a',   'encoding': None,   'delay': False,   'filters': [],   '_name': 'file',   'level': 0,   'formatter': <logging.Formatter object at 0x7ff13a3d6df0>,   'lock': <unlocked _thread.RLock object owner=0 count=0 at 0x7ff13a5b7510>,   'stream': <_io.TextIOWrapper name='/File/Path/mplog.log' mode='a' encoding='UTF-8'>} 
like image 42
Turlututu Avatar answered Sep 24 '22 23:09

Turlututu