🔭 Want to centralize and monitor your python logs?
Go to Logtail and start your log management in 5 minutes.
For this, you can use the sys.excepthook
that allows us to attach a handler
for any unhandled exception:
#Creating a logger
logger = logging.getLogger(__name__)
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
#Creating a handler
def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
#Will call default excepthook
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
#Create a critical level log message with info from the except hook.
logger.critical("Unhandled exception", exc_info=(exc_type, exc_value, exc_traceback))
#Assign the excepthook to the handler
sys.excepthook = handle_unhandled_exception
First, you will create a logger that will take care of your exceptions.
Then create a handler handle_unhandled_exception
that you will later attach to
the hook. Then call the __excepthook__
provided by the sys
module. This
method is invoked every time the exception is uncaught.
Use the info from the hook to create a log message and assign this handler to
the sys.excepthook
.
You can learn more info about sys.excepthook
in
the offical documentation. .
If you are new to logging in Python, please feel free read our Introduction to Python logging and learn more.
Go to Logtail and start your log management in 5 minutes.
If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to color python logging output: 🔭 Want to cent...
If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to log all requests from the python request li...
If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to write logs to a file in Python: Using Basic...
If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to log to Stdout with Python: Using Basic Conf...
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usWrite a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github