Skip to content

Instantly share code, notes, and snippets.

@vvalorous
Forked from bh1428/lambda_template.py
Created March 27, 2018 06:42
Show Gist options
  • Save vvalorous/71d0dbfb81183e093d9bad0e356da4f7 to your computer and use it in GitHub Desktop.
Save vvalorous/71d0dbfb81183e093d9bad0e356da4f7 to your computer and use it in GitHub Desktop.
AWS Lambda function template
#!/usr/bin/env python
"""Describe the function
The following environment variables can be used to steer behavior:
- LOGLEVEL: set the loglevel (INFO when not defined / missing), this
is based on the Python `logging` module
"""
import logging
import os
# setup logging, the environment variabel LOGLEVEL
# can be used for a (non-default) loglevel
DEFINED_LOGLEVELS = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'DEFAULT': logging.INFO
}
LOGGER = logging.getLogger()
LOGLEVEL = os.getenv('LOGLEVEL', 'DEFAULT')
if LOGLEVEL.upper() in DEFINED_LOGLEVELS:
LOGGER.setLevel(DEFINED_LOGLEVELS[LOGLEVEL])
else:
LOGGER.setLevel(DEFINED_LOGLEVELS['DEFAULT'])
def lambda_handler(event, context):
"""Lambda handler doing the work.
For the Python programming model, see:
http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model.html
:type event: dict
:param event: AWS Lambda uses this parameter to pass in event data to the
handler. This parameter is usually of the Python `dict` type. It can
also be `list`, `str`, `int`, `float`, or `NoneType` type.
:type event: LambdaContext
:param event: AWS Lambda uses this parameter to provide runtime
information to your handler.
See: http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
:rtype: dict
:return: Optional return of the handler. What happens to the returned value
depends on the invocation type you use when invoking the Lambda function.
See: http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html
"""
# do the work
return {'result': 'some message or data'}
if __name__ == '__main__':
os.environ[LOGLEVEL] = 'DEBUG'
loglevel = logging.DEBUG
LOGGER.setLevel(loglevel)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
console_handler.setLevel(loglevel)
LOGGER.addHandler(console_handler)
lambda_handler(None, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment