Skip to main content

Longsight: Best Practice Logging Library

A range of common logging functions for the observability of Python AWS cloud applications

license activity

AWS Linux Python

This library implements a range of best-practice logging techniques for Python AWS cloud applications. This includes FastAPI Lambda contexts.

This is a prototype Crossref Labs system. It is not guaranteed to be stable and the metadata schema and behaviour may be subject to change at any time.

longsight.instrumentation

The longsight.instrumentation module provides functionality for instrumenting a FastAPI application with AWS CloudWatch Metrics and Logs. It includes middleware to handle correlation IDs, filters for attaching correlation IDs to logs, and context managers for instrumenting routes with metrics and logging.

Installation

To install the longsight.instrumentation module, run the following command:

pip install longsight

Usage

To use the longsight.instrumentation module, import the necessary components and add them to your FastAPI application.

Decorators

Using the longsight decorators are the easiest way to start logging locally (or in Lambda contexts) quickly.

from longsight.instrumentation import instrument

router = APIRouter()

@router.get("/path")
@instrument()
async def a_route(request: Request, instrumentation=None):
    instrumentation.logger.info("Hello, World!")
    return {"message": "Hello, World!"}

Note that, in FastAPI contexts, you must specify "instrumentation=None" to avoid FastAPI thinking this is an unfilled parameter.

Alternatively, you can also log to CloudWatch instead of locally from any function (note also that the decorator works on both async and synchronous functions and is not limited to FastAPI functions):

from longsight.instrumentation import instrument

@instrumentation.instrument(
cloudwatch_push=True,
log_stream_name="martin-test-stream-name",
log_group_name="martin-test-group-name",
namespace="martin-test-namespace",
)
def a_function(instrumentation):
    instrumentation.logger.info("Hello, World!")
    instrumentation.logger.info("A second log line")
    instrumentation.add_metric_point(
        metric_name="test_metric",
        dimensions=[{"Name": "Environment", "Value": "Production"}],
        metric_value=1,
        unit="Count",
        time_stamp=datetime.now(),
    )

Longsight can also create AWS objects for you to reuse throughout your project, centralizing AWS code:

from longsight.instrumentation import instrument

@instrument(create_aws=True, bucket="my-bucket")
def a_function(instrumentation):
    instrumentation.logger.info("Hello, World!")
    s3_client = instrumentation.aws_connector.s3_client
    return

By default, the AWS interaction is anonymous. To write to S3 buckets or access protected buckets, pass sign_aws_requests=True.

Easy counters

The instrumentation class also provides a simple counter function to increment a counter in CloudWatch:

from longsight.instrumentation import instrument

@instrumentation.instrument(
cloudwatch_push=True,
log_stream_name="martin-test-stream-name",
log_group_name="martin-test-group-name",
namespace="martin-test-namespace",
)
def a_function(instrumentation):
    instrumentation.add_counter(
        metric_name="test_counter", status_code=200, member_id=None, 
        additional_dimensions=[{"Name": "Environment", "Value": "Production"}]
    )

Correlation ID Middleware

The AWSCorrelationIdMiddleware middleware automatically generates or loads a correlation ID for each incoming request, and attaches it to the request headers and logs. To use the middleware, create an instance of the AWSCorrelationIdMiddleware class and add it to your FastAPI application:

from fastapi import FastAPI
from longsight.instrumentation import AWSCorrelationIdMiddleware

app = FastAPI()
app.add_middleware(AWSCorrelationIdMiddleware)

By default, the middleware looks for the X-Request-ID header in the incoming request headers, or in the mangum handlers aws.context, and generates a new UUID if the header is not present.

Using Mangum and logging default Lambda stats

To configure Mangum to handle requests in an AWS Lambda context and to inject instrumentation, use:

from mangum import Mangum
handler = Mangum(app, lifespan="off")
handler = instrumentation.logger.inject_lambda_context(
    lambda_handler=handler, clear_state=True
)
handler = instrumentation.metrics.log_metrics(
    handler, capture_cold_start_metric=True
)

Logging Filters

The CorrelationIdFilter filter attaches the correlation ID to log records. To use the filter, create an instance of the CorrelationIdFilter class and add it to your logger:

import logging
from longsight.instrumentation import CorrelationIdFilter

logger = logging.getLogger(__name__)
logger.addFilter(CorrelationIdFilter())

This setup is done automatically if you use the decorators.

Context Managers

The Instrumentation context manager provides functionality for instrumenting routes with metrics and logging. To use the context manager, create an instance of the Instrumentation class and use it as a context manager:

from fastapi import FastAPI
from longsight.instrumentation import Instrumentation

app = FastAPI()

@app.get("/")
async def root(request: Request):
    with Instrumentation(
                    aws_connector=aws_connector,
                    fastapi_app=fastapi_app,
                    request=request) as instrumentation:
        instrumentation.logger.info("Handling request")
        return {"message": "Hello, World!"}

The Instrumentation context manager automatically logs the start and end of the request, and provides an instance of the Logger classes for logging and metrics. The Logger classes are provided by the aws_lambda_powertools package.

Credits

© Crossref 2023

Metadata

Release files for longsight 1.0.16

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for longsight 1.0.16
File Size Uploaded
longsight-1.0.16.tar.gz 12.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for longsight 1.0.16
File Interpreter ABI Platform
longsight-1.0.16-py3-none-any.whl Python 3 none any Details

Total release size: 21.9 kB

Release files / longsight-1.0.16.tar.gz

Download URL longsight-1.0.16.tar.gz
Size 12.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c00e089bb9d003e51304150fd0a17fed9eb6cbdc0998084f1f6435087f05ef9b
BLAKE2b-256 checksum
How to use checksums
5e5e6a63a35d96c3355f4ad74c9a6c3d56f51f8ffc06010c3d027904c6db0048
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release files / longsight-1.0.16-py3-none-any.whl

Download URL longsight-1.0.16-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
04b1376563bb9bb5069580620e90af25702c85e9208b13ed3c9745259aa1cf9e
BLAKE2b-256 checksum
How to use checksums
0bde9160603a4c58e06d45de623ca7d83204fd4ab2b10a6a95630b65a0b88e01
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release history Release notifications | RSS feed

This release

1.0.16 This release

2 release files

1.0.15

2 release files

1.0.14

2 release files

1.0.13

2 release files

1.0.12

2 release files

1.0.11

2 release files

1.0.10

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page