Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python's logging module to log all exceptions and errors

I want to check for errors in a particular background file, but the standard error stream is being controlled by the program in the foreground and the errors in the file in the question are not being displayed. I can use the logging module and write output to a file, though. I was wondering how I can use this to log all exceptions, errors and their tracebacks.

like image 842
abc def foo bar Avatar asked Nov 08 '11 13:11

abc def foo bar


People also ask

How do I log exceptions in Python logging?

To log an exception in Python we can use logging module and through that we can log the error. Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger.

What is the use of logging module in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.

Does logging error raise exception Python?

It depends on the situation, but logging and then raising an exception is generally considered an antipattern. It's redundant and clutters logs. Unless you're expecting something to catch that exception and suppress the message, don't log. Pythonic is not really a look as it is the formatting of code.


1 Answers

It's probably a bad idea to log any exception thrown within the program, since Python uses exceptions also for normal control flow.

Therefore you should only log uncaught exceptions. You can easily do this using a logger's exception() method, once you have an exception object.

To handle all uncaught exceptions, you can either wrap your script's entry point in a try...except block, or by installing a custom exception handler by re-assigning sys.excepthook():

import logging import sys  logger = logging.getLogger('mylogger') # Configure logger to write to a file...  def my_handler(type, value, tb):     logger.exception("Uncaught exception: {0}".format(str(value)))  # Install exception handler sys.excepthook = my_handler  # Run your main script here: if __name__ == '__main__':     main() 
like image 141
Ferdinand Beyer Avatar answered Sep 21 '22 23:09

Ferdinand Beyer