简体   繁体   中英

Python logging: can dictConfig be read from a file?

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.

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.

No, there is no parser in the standard library that'll take a file and spit out a dictConfig compatible dictionary.

You'll have to create your own file format to populate your dictionary. This is what usually happens; application specific configuration translated to a dictConfig setup, where your configuration file offers a subset of the full dictConfig spectrum.

dictConfig takes a dict as its parameter and does not care, how you got it. You can read the dict from file, compute it, decode it, or create any other way you want, as long, as it has proper structure.

So yes, you can, but you have to extract the dict from file yourself (probabelly using some library)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM