1

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?

juggernaut
  • 748
  • 1
  • 10
  • 19
  • Are you looking for [print-exception-with-stack-trace-to-file](https://stackoverflow.com/questions/31636884/print-exception-with-stack-trace-to-file)? – Msvstl Jul 27 '22 at 09:13
  • 1
    No, as catching & logging err has 3 downsides: 1. you've to write some extra wrapping catching code. especially taking into account console handler which does everything for free as it doesn't require extra-code; 2. even if you wrap some entry point (e.g. `main` func) with try-except it doesn't guaranteed to have uncaught crashes logged when happen outside of it (e.g. import, syntax errors) 3. if exception gonna be re-raised the console handler is also affected by this change and duplicates the traceback twice which is weird (first from `logger.exception` and second from stderr) – juggernaut Jul 27 '22 at 17:24
  • This answer https://stackoverflow.com/a/6234491/2532408 might be of some help. – Marcel Wilson Aug 11 '22 at 22:54

2 Answers2

1

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:

Msvstl
  • 1,116
  • 5
  • 21
  • I'm aware about possibility to catch exception and log it. And this was the first solution I came to and actually want to avoid as it is nice to write uncaught exceptions to the log file, isn't it? – juggernaut Jul 27 '22 at 08:03
  • 1
    btw, `logger.error` won't work too, only `logger.exception` is going to write traceback to file. – juggernaut Jul 27 '22 at 08:05
0

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

shaioz
  • 340
  • 3
  • 12