Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging to different destination using a configuration file

I want to use a configuration file to create two loggers which will log in two distinct files. My configuration file looks like:

[loggers]
keys=root,main,zipper

[handlers]
keys=main,zip

[formatters]
keys=fmt

[logger_root]
level=DEBUG
handlers=main

[logger_main]
level=DEBUG
handlers=main
qualname=MAIN

[logger_zipper]
level=DEBUG
qualname=UPLOAD
handlers=zip

[handler_zip]
class=FileHandler
level=DEBUG
formatter=fmt
args=('zipper.log','a+')

[handler_main]
class=FileHandler
level=DEBUG
formatter=fmt
args=('main.log','a+')

[formatter_fmt]
format=%(asctime)s - %(levelname)s - %(name)s - %(message)s

I try to use this configuration file like this:

import logging
import logging.config

logging.config.fileConfig("logging.conf")

# Logs to the first file
log = logging.getLogger("")
log.debug("unspec - debug")
log.error("unspec - error")

# Logs to the first file
log_r = logging.getLogger("main")
log_r.debug("main - debug")
log_r.error("main - error")

# Also logs to the first file :(
log_z = logging.getLogger("zipper")
log_z.debug("zipper - debug")
log_z.error("zipper - error")

For some reason I don't understand, all logging messages go to the first file, when I expect the last two to be written to 'zipper.log'. What am I missing ?

like image 858
Unknown Avatar asked Oct 30 '25 20:10

Unknown


1 Answers

The problem is that the qualified name used in the configuration file:

[logger_zipper]
level=DEBUG
qualname=UPLOAD
handlers=zip

doesn't match the one used in the code:

log_z = logging.getLogger("zipper")

Use any of these combinations:

  • qualname=zipper and logging.getLogger("zipper")
  • qualname=UPLOAD and logging.getLogger("UPLOAD")
like image 136
jcollado Avatar answered Nov 01 '25 10:11

jcollado



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!