juggernaut
juggernaut

Reputation: 988

logging.FileHandler doesn't write tracebacks

I've 2 handlers to write to the console and the file:

import logging, sys

logger = logging.getLogger(__name__)

stdout_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stdout_handler)

file_handler = logging.FileHandler(filename="out.log")
logger.addHandler(file_handler)

if __name__ == '__main__':
    raise ZeroDivisionError

When exceptions happen StreamHandler made for stdout is able to log the traceback which came to the stderr. Meanwhile, FileHandler doesn't write a traceback to the file.

Am I missing something in the FileHandler setup? Is FileHandler able to log stderr (e.g. uncaught exceptions) at all?

Upvotes: 1

Views: 364

Answers (2)

shaioz
shaioz

Reputation: 450

Late to the party but, please see logger-tt, an awesome module that implements this requirement.

Upvotes: 1

Msv
Msv

Reputation: 1371

Logging module doesn't do everything on it's own. You have to specify what to capture as shown below.

import logging, sys

logger = logging.getLogger(__name__)

stdout_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stdout_handler)

file_handler = logging.FileHandler(filename="out.log")
logger.addHandler(file_handler)

if __name__ == '__main__':
    try:
        1/0
    except ZeroDivisionError as err:
        logger.error(err)

Refer to these for more details:

Upvotes: 1

Related Questions