Python SDK logging with file redirection

Hi, I’m using the following snippet to set up logging for CLI Python scripts (run overnight on a server via cron jobs).

if in_server:
    now_str = pendulum.now("UTC").isoformat()[:16]

    logging_to_file(f'/path/app_{now_str}_err.log')

    with open(f'/path/app_{now_str}.log', 'a', buffering=1) as f:
        with redirect_stdout(f), redirect_stderr(f):
            main()
else:  # just display everything on the screen in local development
    main()

where logging_to_file is defined as:

def logging_to_file(filename):
    logging.shutdown()
    reload(logging)

    logging.basicConfig(
        format='\n-------------------\n%(asctime)s\n%(levelname)-8s\n%(message)s\n\n',
        level=logging.WARNING,
        filename=filename,
        datefmt='%Y-%m-%dT%H:%M:%S',
    )

    sys.excepthook = handle_exception

How would you integrate this with sentry_sdk.init()? I’d like to make sure it’s both logging to file as it does it currently, as well capturing exceptions via the Sentry SDK.

Would it work if I simply put the init command between the logging_to_file and with open commands?

It doesn’t matter, you can init anywhere. The only thing I can think of is that you should make sure your excepthook does not completely replace the SDK’s one.