Skip to main content

Moesif Middleware to automatically log API calls from AWS Lambda functions

Project description

Moesif AWS Lambda Middleware

Built For Software License Source Code

Middleware (Python) to automatically log API calls from AWS Lambda functions and sends to Moesif for API analytics and log analysis.

Designed for APIs that are hosted on AWS Lambda using Amazon API Gateway as a trigger.

This middleware expects the Lambda proxy integration type. If you're using AWS Lambda with API Gateway, you are most likely using the proxy integration type.

How to install

pip install moesif_aws_lambda

How to use

The following shows how import the module and use:

1. Import the module:

from moesif_aws_lambda.middleware import MoesifLogger
import os

# Moesif Application Id
os.environ["MOESIF_APPLICATION_ID"] = "Your Moesif Application Id"

def identify_user(event, context):
    return 'my_user_id'

def identify_company(event, context):
    return 'my_company_id'

def get_api_version(event, context):
    return '1.0.0'

def get_session_token(event, context):
    return '23jdf0owekfmcn4u3qypxg09w4d8ayrcdx8nu2ng]s98y18cx98q3yhwmnhcfx43f'

def get_metadata(event, context):
    return { 'foo' : 'aws lambda', 'bar' : 'aws lambda metadata', }

def mask_event(eventmodel):
    return eventmodel

def should_skip(event, context):
    return "/" in event['path']

moesif_options = {
    'GET_METADATA': get_metadata,
    'IDENTIFY_USER': identify_user,
    'IDENTIFY_COMPANY': identify_company,
    'GET_SESSION_TOKEN': get_session_token,
    'GET_API_VERSION': get_api_version,
    'MASK_EVENT_MODEL': mask_event,
    'SKIP': should_skip,
    'LOG_BODY': True,
    'DEBUG': True
}

@MoesifLogger(moesif_options)
def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'isBase64Encoded': False,
        'body': {
            'msg': 'Hello from Lambda!'
        },
        'headers': {
            'Content-Type': 'application/json'
        }
    }

2. Enter Moesif Application Id

Your Moesif Application Id can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the top right menu, and then clicking Installation.

Repo file structure

  • moesif_aws_lambda/middleware.py the middleware library
  • lambda_function.py sample AWS Lambda function using the middleware

Configuration options

IDENTIFY_USER

Type: (event, context) => String

IDENTIFY_USER is a function that takes AWS lambda event and context objects as arguments and returns a user_id. This enables Moesif to attribute API requests to individual unique users so you can understand who calling your API. This can be used simultaneously with IDENTIFY_COMPANY to track both individual customers and the companies their a part of.

def identify_user(event, context):
  # your code here, must return a string
  return event["requestContext"]["identity"]["cognitoIdentityId"]

IDENTIFY_COMPANY

Type: (event, context) => String

IDENTIFY_COMPANY is a function that takes AWS lambda event and context objects as arguments and returns a company_id. If your business is B2B, this enables Moesif to attribute API requests to specific companies or organizations so you can understand which accounts are calling your API. This can be used simultaneously with IDENTIFY_USER to track both individual customers and the companies their a part of.

def identify_company(event, context):
  # your code here, must return a string
  return 'my_company_id'
}

GET_SESSION_TOKEN

Type: (event, context) => String

GET_SESSION_TOKEN a function that takes AWS lambda event and context objects as arguments and returns a session token (i.e. such as an API key).

def get_session_token(event, context):
    # your code here, must return a string.
    return '23jdf0owekfmcn4u3qypxg09w4d8ayrcdx8nu2ng]s98y18cx98q3yhwmnhcfx43f'

GET_API_VERSION

Type: (event, context) => String

GET_API_VERSION is a function that takes AWS lambda event and context objects as arguments and returns a string to tag requests with a specific version of your API.

def get_api_version(event, context):
  # your code here. must return a string.
  return '1.0.0'

GET_METADATA

Type: (event, context) => String

GET_METADATA is a function that AWS lambda event and context objects as arguments and returns an object that allows you to add custom metadata that will be associated with the request. The metadata must be a simple python object that can be converted to JSON. For example, you may want to save a function_name, a trace_id, or request_context with the request.

def get_metadata(event, context):
  # your code here:
  return {
        'trace_id': context.aws_request_id,
        'function_name': context.function_name,
        'request_context': event['requestContext']
    }

SKIP

Type: (event, context) => Boolean

SKIP is a function that takes AWS lambda event and context objects as arguments and returns true if the event should be skipped (i.e. not logged)
The default is shown below and skips requests to the root path "/".

def should_skip(event, context):
    # your code here. must return a boolean.
    return "/" in event['path']

MASK_EVENT_MODEL

Type: MoesifEventModel => MoesifEventModel

MASK_EVENT_MODEL is a function that takes the final Moesif event model (rather than the AWS lambda event/context objects) as an argument before being sent to Moesif. With maskContent, you can make modifications to headers or body such as removing certain header or body fields.

def mask_event(eventmodel):
  # remove any field that you don't want to be sent to Moesif.
  return eventmodel

DEBUG

Type: Boolean

Set to true to print debug logs if you're having integegration issues.

LOG_BODY

Type: Boolean

LOG_BODY is default to true, set to false to remove logging request and response body to Moesif.

Examples

Other integrations

To view more documentation on integration options, please visit the Integration Options Documentation.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

moesif_aws_lambda-1.0.1.tar.gz (10.4 kB view details)

Uploaded Source

Built Distribution

moesif_aws_lambda-1.0.1-py2.py3-none-any.whl (12.8 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file moesif_aws_lambda-1.0.1.tar.gz.

File metadata

  • Download URL: moesif_aws_lambda-1.0.1.tar.gz
  • Upload date:
  • Size: 10.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.5

File hashes

Hashes for moesif_aws_lambda-1.0.1.tar.gz
Algorithm Hash digest
SHA256 5bddc2f449d6c5d41e0d79e76fad46f4ce523d8137b2249de63307f715a81bbf
MD5 f9eebc0219abc7f9024d7c6c337f3497
BLAKE2b-256 f694055116cb303fa4130c742f6393d5564bb7ac7bbbad09205b979012170a58

See more details on using hashes here.

File details

Details for the file moesif_aws_lambda-1.0.1-py2.py3-none-any.whl.

File metadata

  • Download URL: moesif_aws_lambda-1.0.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 12.8 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.5

File hashes

Hashes for moesif_aws_lambda-1.0.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 2d08b083509b36d6f5a152c5e887ddcea8f518692175b65467174e0b929e17a3
MD5 edc761a23ef2129ce3d4bead9d4a06e0
BLAKE2b-256 0cd68fa3c74b1b09bd9d18b4304857ac6b0729660faee29da7c373134e48e10b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page