- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
What is the best way to log a Python exception?
We import the logging module and then use the logging.exception method to create a log of the python exception.
import logging try: print 'toy' + 6 except Exception as e: logging.exception("This is an exception log")
We get the following output
ERROR:root:This is an exception log Traceback (most recent call last): File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/loggingerror1.py", line 3, in <module> print 'toy' + 6 TypeError: cannot concatenate 'str' and 'int' objects
It is noted that in Python 3 we must call the logging.exception method just inside the except part. If we call this method in any other place we may get a weird exception as per alert by python docs.
- Related Articles
- What is the best way to handle list empty exception in Python?
- What is the best way to learn Python and Django?
- What is the best way to get stock data using Python?
- What is the Best Way to Develop Desktop Applications Using Python?
- What is the best way to remove an item from a Python dictionary?
- What is the best way to run all Python files in a directory?
- What is the Best Way to Install Python on a Windows 10 Computer?
- What is the correct way to pass an object with a custom exception in Python?
- What is best way to check if a list is empty in Python?
- What is the best way to stop Brain Drain?
- What is the best way to earn money online?
- What are the best practices for exception handling in Python?
- What is the best way to iterate over a Dictionary in C#?