Thursday, 24 December 2015

Python: logging: Logging Exceptions


Logger.exception() method is used to log exceptions. It logs a message with level ERROR on this logger and dumps a stack trace along with it. This method should only be called from an exception handler.
import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

def processData():
    try:
        logger.info("Processing data")
        10/0
    except ZeroDivisionError as inst:
        logger.exception(inst)

processData()


Run above program, you will get following output.
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/harikrishna_gurram/PycharmProjects/python_tutorial/loggingEx/__init__.py
2015-10-23 00:04:43,992 __main__     INFO     Processing data
2015-10-23 00:04:43,992 __main__     ERROR    division by zero
Traceback (most recent call last):
  File "/Users/harikrishna_gurram/PycharmProjects/python_tutorial/loggingEx/__init__.py", line 9, in processData
    10/0
ZeroDivisionError: division by zero

Process finished with exit code 0




Previous                                                 Next                                                 Home

No comments:

Post a Comment