Exceptions information#
By adding the exc_info=True
argument to the logging method, you can include information about the exception in the log.
import os
import logging
Basic example#
Here I create loggin system which will write any error to logging_files/basic.log
log_filename = "exception_information_files/basic.log"
fun_lines = [
lambda: "no_bug", # no_bug function
lambda: 7/0, # ZeroDivisionError
lambda: "hello" + 5784 # TypeError
]
basic_logger = logging.getLogger("basic loger")
basic_logger.level = logging.INFO
handler = logging.FileHandler(log_filename, mode='w')
handler.setFormatter(
logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')
)
basic_logger.addHandler(handler)
for fun in fun_lines:
try:
fun()
except:
basic_logger.error("===Any error===", exc_info=True)
with open(log_filename) as file:
print(file.read())
os.remove(log_filename)
2024-04-18 21:04:50,089|ERROR|===Any error===
Traceback (most recent call last):
File "/tmp/ipykernel_8410/697886762.py", line 18, in <module>
fun()
File "/tmp/ipykernel_8410/697886762.py", line 4, in <lambda>
lambda: 7/0, # ZeroDivisionError
ZeroDivisionError: division by zero
2024-04-18 21:04:50,089|ERROR|===Any error===
Traceback (most recent call last):
File "/tmp/ipykernel_8410/697886762.py", line 18, in <module>
fun()
File "/tmp/ipykernel_8410/697886762.py", line 5, in <lambda>
lambda: "hello" + 5784 # TypeError
TypeError: can only concatenate str (not "int") to str
Exception in exception#
I wanted to learn how looging
module will process the situation when there is one exception is handled within the framework of the other. In the following example there are functions:
inside_exception
calls the division by zero exception;outside_exception
will executeinside_exception
and in addition will lead to type exception;as a result we see only
TypeError
in log.
log_filename = "exception_information_files/excep_in_excep.log"
logging.basicConfig(
level=logging.INFO,
filename=log_filename,
filemode="w",
format="%(asctime)s %(levelname)s %(message)s"
)
def inside_exception():
try:
7/0
except:
pass
def outside_exception():
try:
inside_exception()
"hello" + 7
except:
logging.error("Any error", exc_info=True)
outside_exception()
with open(log_filename) as f:
print(f.read())
2024-04-18 21:04:51,494 ERROR Any error
Traceback (most recent call last):
File "/tmp/ipykernel_8410/1712082539.py", line 18, in outside_exception
"hello" + 7
TypeError: can only concatenate str (not "int") to str