Skip to main content

This library implements a range of common logging functions.

Project description

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

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

longsight-1.0.10.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

longsight-1.0.10-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file longsight-1.0.10.tar.gz.

File metadata

  • Download URL: longsight-1.0.10.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.6

File hashes

Hashes for longsight-1.0.10.tar.gz
Algorithm Hash digest
SHA256 a2f4e9cdb271a573d69c3f8ce3195d6dae6748604777babf8f0011e098110df4
MD5 8b9b922f271ba724ba81f9f3fe2a2ff6
BLAKE2b-256 843b6c925c6d128700a104994a46642c193ff2c7221ac630aef14d5536976432

See more details on using hashes here.

File details

Details for the file longsight-1.0.10-py3-none-any.whl.

File metadata

  • Download URL: longsight-1.0.10-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.6

File hashes

Hashes for longsight-1.0.10-py3-none-any.whl
Algorithm Hash digest
SHA256 2abea9832f68e864c566887c10b6bd7bc0b7d13c65b1410b756f1cec86db64fb
MD5 ea72dffd39b09a1494b238f2a22138c2
BLAKE2b-256 1169ee3f3cf5c7f41072ba93e8ba45d0d0138026d15e7b09bd342f86b87f7351

See more details on using hashes here.

Supported by

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