K G
K G

Reputation: 1815

Python logging not working

I'm loading my logging configuration from a file. The log file is given below:

[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter
args=(sys.stderr,)

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('../output.log','w')

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

And I create a logger using:

_logger = logging.getLogger(__name__)
logging.config.fileConfig('../logging.conf')

However, I do not see any logging output when I run my program. If I add a separate logger for my main module, then logging works as expected. But set up like this it doesn't work. What am I doing wrong?

Upvotes: 2

Views: 3420

Answers (2)

DX2003
DX2003

Reputation: 138

You need to place the logger creation after configuration. The logging.fileConfig call will disable the pre-existing loggers which is why your logger isn't working.

Upvotes: 1

HennyH
HennyH

Reputation: 7944

By creating the log file like so:

_logger = logging.getLogger(__name__)

It will look for a file with the name with the value of __main__, which your main module will have equal to "__main__". However the other modules you import will have __name__ equal to the module name of the module.

Upvotes: 1

Related Questions