Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging to file through ini creates empty log file

I have what I think is a very basic example of logging in Python (v2.7.10), but I cannot get logging to a file to work. Logging to stderr is not a problem, but when I try to ask it to write to a file all I get is an empty log file.

Here is my configuration log_config.ini file:

[loggers]
keys=root

[handlers]
keys=file_handler,stream_handler

[formatters]
keys=formatter

[logger_root]
level=DEBUG
handlers=stream_handler

[handler_stream_handler]
class=StreamHandler
level=WARNING
formatter=formatter
args=(sys.stderr,)

[handler_file_handler]
class=FileHandler
level=DEBUG
formatter=formatter
args=('empty.log',)

[formatter_formatter]
format=%(asctime)-s %(name)s %(module)s %(funcName)s %(levelname)-8s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

And here is a basic test python script to uses this ini file:

import logging
from logging import config

log_config_ini = "log_config.ini"
logging.config.fileConfig(log_config_ini)

logger = logging.getLogger()

logger.critical('This outputs just to the screen')
logger.debug("This does not write to either screen (expected) nor file (unexpected)")

Note that I can change things like the level for the handler_stream_handler block and everything works as expected, so the configuration file is being read properly.

I've also tried things like logging.config.fileConfig(log_config_ini, disable_existing_loggers = False), levels, but nothing seems to make a difference, I just get an empty 'empty.log' file.

I'm sure there's just something very basic and silly that will help, but I think I've exhausted google and the Python docs at this point. Any help would be appreciated, thank you in advance!

like image 982
wolfpigeon Avatar asked Feb 15 '26 10:02

wolfpigeon


1 Answers

You need to add the file_handler to the root logger handlers in your config file :

[logger_root]
level=DEBUG
handlers=stream_handler, file_handler
like image 170
PRMoureu Avatar answered Feb 17 '26 22:02

PRMoureu



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!