Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logging: dictConfig

I am trying to use a config file for configure Python Logging, but also adding handlers after the dict config has been loaded. SO my config file is like

version: 1
formatters:
  default_formatter:
    format: '%(asctime)s : %(levelname)s : %(message)s'
    datefmt: '%d-%b-%Y %H:%M:%S'
  plain_formatter:
    format: '%(message)s'
handlers:  
  console_default_handler:
    class: logging.StreamHandler
    level: INFO
    formatter: default_formatter
    stream: ext://sys.stdout  
root:
  level: INFO
  handlers: [console_default_handler]

Then in the code - I do

log_config_dict=yaml.load(open(log_config_file, 'r'))
logging.config.dictConfig(log_config_dict)

And I want to add loggers in this way -

fhandler1=logging.FileHandler(log_file_name,mode="w")
fhandler1.setFormatter(log_config_dict['formatters']['plain_formatter'])
fhandler1.setLevel(logging.DEBUG)

This is not working. Is there any way I catch fetch values defined in the dictConfig for using them in my manual log configuration please?

like image 254
Nupur Avatar asked Feb 17 '26 13:02

Nupur


1 Answers

Ohh I figure it out. What I need to do is

formatter =logging.Formatter(log_config_dict['formatters']['plain_formatter']['format'])             
fhandler1.setFormatter(formatter)

So, I need to create a Formatter object.

like image 96
Nupur Avatar answered Feb 20 '26 01:02

Nupur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!