3

How can I set the python logging module to write an exception to a file handler? In the console I naturally see the system exception, but how can I configure logging to send it also to a file handler when I not explicitly surround it with a try block?

import logging
import logging.config

logging.config.fileConfig('logging.conf')
log = logging.getLogger('my_file_logger')

log.info('writes to logfile')
print('prints to console')
not_a_command  # force exception

And logging.conf

[loggers]
keys=root,console,my_file_logger

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=simpleFormatter

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

[handler_consoleHandler]
class=StreamHandler
formatter=simpleFormatter
level=DEBUG
args=(sys.stdout,)
stream=sys.stdout

[handler_fileHandler]
class=FileHandler
formatter=simpleFormatter
level=DEBUG
args=('logfile_'+time.strftime('%%Y%%m%%d', time.localtime())+'.log', 'a')

[logger_root]
level=ERROR
handlers=consoleHandler

[logger_console]
level=DEBUG
propagate=0
qualname=console
handlers=consoleHandler

[logger_my_file_logger]
level=DEBUG
propagate=0
qualname=my_file_logger
handlers=consoleHandler,fileHandler

Thanks!

Jim B
  • 641
  • 5
  • 18

0 Answers0