-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_python.py.template
93 lines (70 loc) · 2.5 KB
/
base_python.py.template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Template for lambda and base python scripts
# Has logging and some built in features.
from __future__ import print_function
import os
import sys
import logging
import traceback
import boto3
LOG_LEVELS = {'CRITICAL': 50, 'ERROR': 40, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10}
AWS_REGION = ''
def init_logging():
# Setup loggin because debugging with print can get ugly.
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.getLogger("boto3").setLevel(logging.WARNING)
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('nose').setLevel(logging.WARNING)
return logger
def setup_local_logging(logger, log_level = 'INFO'):
# Set the Logger so if running locally, it will print out to the main screen.
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
if log_level in LOG_LEVELS:
logger.setLevel(LOG_LEVELS[log_level])
else:
logger.setLevel(LOG_LEVELS['INFO'])
return logger
def set_log_level(logger, log_level = 'INFO'):
# There is some stuff that needs to go here.
if log_level in LOG_LEVELS:
logger.setLevel(LOG_LEVELS[log_level])
else:
logger.setLevel(LOG_LEVELS['INFO'])
return logger
def process_global_vars():
logger.info("Processing variables from environment.")
try:
global AWS_REGION
AWS_REGION = os.environ.get('AWS_REGION', AWS_REGION)
except SystemExit:
sys.exit(1)
except:
logger.error("Unexpected error!\n Stack Trace:", traceback.format_exc())
def lambda_handler(event, context):
try:
global logger
logger = init_logging()
logger = set_log_level(logger, os.environ.get('log_level', 'INFO'))
logger.debug("Running function lambda_handler")
process_global_vars()
except SystemExit:
logger.error("Exiting")
sys.exit(1)
except ValueError:
exit(1)
except:
print ("Unexpected error!\n Stack Trace:", traceback.format_exc())
exit(0)
if __name__ == "__main__":
logger = init_logging()
os.environ['log_level'] = os.environ.get('log_level', "INFO")
logger = setup_local_logging(logger, os.environ['log_level'])
event = {'log_level': 'INFO'}
os.environ['AWS_REGION'] = os.environ.get('AWS_REGION', "us-east-2")
# Add default level of debug for local execution
lambda_handler(event, 0)