Last active
March 30, 2022 15:24
-
-
Save thedavecarroll/29b7ed7968fe0813e196423fdf781a57 to your computer and use it in GitHub Desktop.
Python Exception Logger and Boto3 Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from mylogger import logger,log_exception | |
def create_session(profile_name='default'): | |
logger.info(f'Creating new boto3 session with profile {profile_name}') | |
try: | |
return boto3.session.Session(profile_name=profile_name) | |
except: | |
raise Exception( log_exception() ) | |
def create_client(session, service): | |
logger.info(f'Creating boto3 {service} client with profile {session.profile_name}') | |
try: | |
return session.client(service) | |
except: | |
raise Exception( log_exception() ) | |
def how_to_use(): | |
session = create_session() | |
s3_client = create_client(session, 's3') | |
s3_client.list_buckets() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging, sys, json, traceback | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
# uncomment the following to have the logger write to standard out | |
# logger.addHandler(logging.StreamHandler()) | |
def log_exception(): | |
exception_type, exception_value, exception_traceback = sys.exc_info() | |
traceback_string = traceback.format_exception( | |
exception_type, exception_value, exception_traceback) | |
err_msg = json.dumps({ | |
'errorType': exception_type.__name__, | |
'errorMessage': str(exception_value), | |
'stackTrace': traceback_string | |
}) | |
logger.error(err_msg) | |
return traceback_string[-1] | |
def how_to_use(): | |
try: | |
# some code that could throw exception | |
return | |
except: | |
raise Exception( log_exception() ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment