Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging: can dictConfig be read from a file?

Tags:

python

logging

The examples of seen of using dictConfig to set up logging in Python show the dictionary be created in the Python script. I'd like to use a configuration file, but the documentation says fileConfig is older and less capable than dictConfig. Can a dictConfig be set up from a configuration file?

Thank you very much.

like image 304
ROBERT RICHARDSON Avatar asked Dec 21 '15 17:12

ROBERT RICHARDSON


People also ask

How to configure logging in Python?

You can configure logging as shown above using the module and class functions or by creating a config file or a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want to change your logging configuration in a running application.

What is the name of the log file in Python?

The name of the logger corresponding to the __name__ variable is logged as __main__, which is the name Python assigns to the module where execution starts. If this file is imported by some other module, then the __name__ variable would correspond to its name logging_example.

What is the use of saving logs in Python?

Saving logs to a file allows for unlimited length (as far as our disk allows it) and enables the usage of tools, such as grep, to search through them. The FileHandler class, located in the core logging package, sends logging output to a disk file. It inherits the output functionality from StreamHandler.

What is a Python log message?

A log message can store information like the current status of a program or where the program is running. If an error occurs, developers can quickly find the line of code that causes the issue and act upon that. Python provides a quite powerful and flexible built-in logging module with many advanced features.


1 Answers

Since dictConfig just takes a dictionary, you can construct the dictionary in any way you like. One example for reading from a file is to have the configuration in JSON format. You can then just do something like

import json
import logging

with open('myconfig.json') as f:
    config_dict = json.load(f)
    logging.config.dictConfig(config_dict)

as long as the JSON file has the appropriate schema.

You can also use other file formats, such as YAML, though you would then need to install a 3rd-party library to parse the file.

like image 186
Vinay Sajip Avatar answered Oct 29 '22 11:10

Vinay Sajip