0

I want to send an email and send the error to Amazon Cloudwatch with every exception. Right now I am doing like this:

import watchtower
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(watchtower.CloudWatchLogHandler(
    log_group_name="example",
    log_stream_name="example")
)

def send_email(exception):
    blabla

try:
    something
except Exception as e:
    logger.exception(f"ERROR {e}")
    send_email(e)
    raise

I was wondering if somehow I can tell python to use my custom logger by default and also send the email function in every exception, so that I don't have to code a lot of try except with the same structure.

Javier Lopez Tomas
  • 2,072
  • 3
  • 19
  • 41

1 Answers1

1

You could make a decorator, for example:

def log_uncaught(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, *kwargs)
        except Exception as e:
            logger.exception(f"ERROR {e}")
            send_email(e)
            raise
    return wrapper


@log_uncaught
def do_something(args1, args2):
    pass
Tzane
  • 2,752
  • 1
  • 10
  • 21