Reputation: 324
I have to create a one single log file for entire application and if there is any exception raised by any of module in the application , exception should go into except block and error should be written to log file . This log file should not be overridden instead if there are exceptions raised by multiple modules , all exceptions should be logged into one single log file .
I have tried logger with below code , but it is not creating log file :
import logging
with open("D:\logfile\log.txt", "w") as log:
logging.basicConfig(filename=log, level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)
try:
1/0
except ZeroDivisionError as err
logger.error(err)
also using with clause needs indentation and I do not want to use all modules under one with clause , instead I want to simply create one log file at the beginning of program and as program executes and modules raise an exceptions those exceptions should be written into one log file .
Upvotes: 0
Views: 1867
Reputation: 51
I don't know the logging module, but some googling suggests that the logging module supports writing the traceback into the logfile. Also your code didn't seem to work on my machine (Python v3.8.5), so i edited it so it works.
logging.exception('text')
logs the traceback to the logfile, and you can specify a message which will displayed beforehand.
The code:
import logging
#with open("log.txt", "w") as log:
logging.basicConfig(filename='log.txt', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)
try:
1/0
except ZeroDivisionError:
logging.exception('Oh no! Error. Here is the traceback info:')
The logfile:
2020-08-20 08:31:02,310 ERROR root Oh no! Error. Here is the traceback info:
Traceback (most recent call last):
File "logger.py", line 7, in <module>
1/0
ZeroDivisionError: division by zero
This has the advantage that the whole traceback is logged, which usually more helpful.
Upvotes: 3