I am trying to log all kinds of errors into the log file. (unhandled exceptions is NOT being logged into the log file.)
For example inside my function i have:
i = "hello"
x = i /3
gives TypeError: unsupported operand type(s) for /: 'str' and 'int'
I want to put this error into the log file without having to add a pre-defined line of logger.error
in my functions as I won't be aware what errors I might get during runtime. Hope I'm making sense.
I tried searching a lot but can't find any answers to this issue
I tried
print = logger.info
but turns out its useless as it doesn't help in errors and I understand that its a terrible way to write code
My code so far:
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
c_format = logging.Formatter('%(name)s:%(funcName)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - [%(levelname)s] -[%(name)s:%(funcName)s:%(lineno)d]- %(message)s', datefmt='%d-%b-%y %H:%M:%S')
LOG_FILENAME = 'check.log'
LOG_FILENAME = os.path.join(get_datadir_path(), LOG_FILENAME)
f_handler = logging.FileHandler(LOG_FILENAME)
f_handler.setFormatter(f_format)
f_handler.setLevel(logging.DEBUG)
c_handler = logging.StreamHandler(sys.stdout)
c_handler.setFormatter(c_format)
c_handler.setLevel(logging.DEBUG)
logger.addHandler(c_handler)
logger.addHandler(f_handler)
Thanks for the help in advance
Use try
, except
and logger.exception
:
try:
i = "hello"
x = i / 3
except Exception as e:
logger.exception('Exception!')
raise # you can also raise the exception to stop running after logging
except Exception
will catch all non-exit exceptions (but it is a too broad exception clause). Or use except BaseException
to catch all kinds of exceptions, like KeyboardInterrupt
.
Then the exception is logged into your logfile:
01-Jan-23 22:33:48 - [ERROR] -[root:<module>:29]- Exception!
Traceback (most recent call last):
File "/data/xxx.py", line 27, in <module>
x = i / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'