This module defines functions and classes which implement a flexible event logging system for applications and libraries.
The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.
As of Python 2.7, you can use a dictionary with configuration details. PEP 391 contains a list of the mandatory and optional elements in the configuration dictionary.
If you want to log exceptions you can and should make use of the logging.exception(msg) method:
Do not pass the exception as argument:
As logging.exception(msg) expects a msg arg, it is a common pitfall to pass the exception into the logging call like this:
While it might look as if this is the right thing to do at first, it is actually problematic due to the reason how exceptions and various encoding work together in the logging module:
Trying to log an exception that contains unicode chars, this way will fail miserably. It will hide the stacktrace of the original exception by overriding it with a new one that is raised during formatting of your logging.exception(e) call.
Obviously, in your own code, you might be aware of the encoding in exceptions. However, 3rd party libs might handle this in a different way.
If instead of the exception you just pass a message and let python do its magic, it will work:
As you can see we don't actually use e in that case, the call to logging.exception(...) magically formats the most recent exception.
Logging exceptions with non ERROR log levels
If you want to log an exception with another log level than ERROR, you can use the the exc_info argument of the default loggers:
Accessing the exception's message
Be aware that libraries out there might throw exceptions with messages as any of unicode or (utf-8 if you're lucky) byte-strings. If you really need to access an exception's text, the only reliable way, that will always work, is to use repr(e) or the %r string formatting:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0