cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Python callback functions fail to trigger

lozik
New Contributor II

How can I get sys.exceptionhook and atexit module to trigger a callback function on exit of a python notebook? These fail to work when an unhandled exception is encountered (exceptionhook), or the program exits (atexit). 

1 REPLY 1

lozik
New Contributor II

Hi @Retired_mod - `sys.excepthook` fails to trigger on an unhandled exception. Here's some example code using the logging module. This will write all logging messages to the logfile, except the the ones in `handleException`

 

import logging
import sys
import datetime
import os
logger = logging.getLogger("log_test")
def handleException(excType, excValue, traceback, logger=logger):
    logger.info("message from exception handler")
    logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
sys.excepthook = handleException

log_filepath = f'/dbfs/mnt/logs/log_test_{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.txt'
logging.basicConfig(
    format=f'%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(lineno)d - %(message)s',
    level=logging.INFO,
    handlers=[
        logging.FileHandler(log_filepath),
        logging.StreamHandler(stream=sys.stdout)
    ]
)
logger.debug("this is an debug message")
logger.info("this is an info message")
logger.warning("this is an warning message")
logger.critical("this is an critical message")

raise RuntimeError("Test unhandled")

 

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you wonโ€™t want to miss the chance to attend and share knowledge.

If there isnโ€™t a group near you, start one and help create a community that brings people together.

Request a New Group