简体   繁体   中英

Changing formatter when using logging module with yaml in python

When using logging module in python, we can initialize general setting for each logger using yaml file. My test code looks like

[main.py]

import yaml
import logging, logging.config
def setup_logging(default_level=logging.DEBUG):
    with open("./logging.yaml", 'rt') as f:
        configdata = yaml.safe_load(f.read())
    logging.config.dictConfig(configdata)
setup_logging()

dbg = logging.getLogger(__name__)
dbg.info("Test")

[logging.yaml]

version: 1
disable_existing_loggers: False
formatters:
    detail:
        format: "%(asctime)s - %(name)s - %(message)s"
    onlymessage:
        format: "%(message)s"

handlers:
    file_handler:
        class: logging.FileHandler
        level: DEBUG 
        formatter: detail
        filename: ./log
        mode: w

loggers:
    __main__:
        level: DEBUG
        handlers: [file_handler]
        propagate: No

So for "file_handler", the default formatter is "detail". Then how do I change the formatter of this logger to another one, in this case "onlymessage"?

I know that if we were given formatter object, we can use Handler.setFormatter() to change the formatter of a logger, like

dbg.handlers[0].setFormatter(FORMATTER NAME)

But since I specified all information about formatter in yaml file and used logging.config when initizliaing logger, I have no formatter object. I think if I can retrieve formatter object written in that yaml file, problem can be solved. Or is there any other way to do this?

Yes, "unused" formatters will be lost in the process if you don't bind them to any handler. You can check the source of what happens, here is the interesting bit.

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