Skip to content

Instantly share code, notes, and snippets.

@thedavecarroll
Last active March 30, 2022 15:24
Show Gist options
  • Save thedavecarroll/29b7ed7968fe0813e196423fdf781a57 to your computer and use it in GitHub Desktop.
Save thedavecarroll/29b7ed7968fe0813e196423fdf781a57 to your computer and use it in GitHub Desktop.
Python Exception Logger and Boto3 Client
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()
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