'Python. Catching error without try... except
So I build a small logger class that logs everything but there is a small issue with it.
Then some kind of exception/error happens outside of try... except block I don't have a way to log it into a file.
So the question is, how to catch errors out side of try... except block.
Also if there someone saying "Put whole program in try except.", well here is the problem that it completely ignores errors happening in threads and subprocesses.
Example:
from datetime import datetime
import logging
class Msg:
def __init__(self, logger_name, path, conn=None, info_format="utf-8", file_name=None):
self.path = path
self.logger = logging.getLogger(logger_name)
self.logger.setLevel(logging.DEBUG)
self.now = datetime.now()
self.now = self.now.strftime("%d_%m_%Y-%H_%M_%S")
self.file_formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(message)s")
if file_name is not None:
self.now = file_name
self.file_handler = logging.FileHandler(f"{self.path}/{self.now}.log")
self.file_handler.setLevel(logging.DEBUG)
self.file_handler.setFormatter(self.file_formatter)
self.stream_formatter = logging.Formatter("%(levelname)s:%(message)s")
self.stream_handler = logging.StreamHandler()
self.stream_handler.setFormatter(self.stream_formatter)
self.logger.addHandler(self.stream_handler)
self.logger.addHandler(self.file_handler)
def debug(self, message):
self.logger.debug(message)
def info(self, message):
self.logger.info(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message): # Somehow any exception outside try except have to trigger this to be logged or any other function.
self.logger.error(message, exc_info=True)
def critical(self, message):
self.logger.critical(message, exc_info=True)
if __name__ == "__main__":
log = Msg("Example_Logger_Name", ".")|
a = 1/0 # an example error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
