Metadata-Version: 2.1
Name: longsight
Version: 1.0.2
Summary: This library implements a range of common logging functions.
Home-page: https://gitlab.com/crossref/labs/distrunner
Author: Martin Paul Eve
Author-email: meve@crossref.org
Maintainer-email: Martin Paul Eve <meve@crossref.org>
License: Copyright &copy; 2023 Crossref
        
        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Project-URL: homepage, https://labs.crossref.org
Project-URL: documentation, https://labs.crossref.org
Project-URL: repository, https://gitlab.com/crossref/labs/longsight
Project-URL: changelog, https://gitlab.com/crossref/labs/longsight/-/blob/main/CHANGELOG.md
Keywords: distributed computing
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: aws-lambda-powertools[all] (==2.11.0)
Requires-Dist: uvicorn (==0.21.1)
Requires-Dist: fastapi (~=0.95.0)
Requires-Dist: httpx (==0.23.3)
Requires-Dist: starlette (==0.26.1)
Requires-Dist: claws (==0.0.7)
Requires-Dist: watchtower (==3.0.1)

# Longsight: Best Practice Logging Library
A range of common logging functions for the observability of Python AWS cloud applications


![license](https://img.shields.io/gitlab/license/crossref/labs/longsight) ![activity](https://img.shields.io/gitlab/last-commit/crossref/labs/longsight)

![AWS](https://img.shields.io/badge/AWS-%23FF9900.svg?style=for-the-badge&logo=amazon-aws&logoColor=white) ![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) ![Python](https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54)

This library implements a range of best-practice logging techniques for Python AWS cloud applications. This includes [FastAPI Lambda contexts](https://www.eliasbrange.dev/posts/observability-with-fastapi-aws-lambda-powertools/). 

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):
        instrumentation.logger.info("Hello, World!")
        return {"message": "Hello, World!"}

Alternatively, you can also log to CloudWatch instead of locally (note also that the decorator works on both async and synchronous functions):

    from longsight.instrumentation import instrument

    @instrument(cloudwatch_push=True)
    def a_function(instrumentation):
        instrumentation.logger.info("Hello, World!")
        return

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

## 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, Metrics, Logger
    
    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")
            instrumentation.metrics.put_metric("RequestCount", 1)
            return {"message": "Hello, World!"}

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

# Credits
* [.gitignore](https://github.com/github/gitignore) from Github.
* [AWS Lambda Powertools](https://awslabs.github.io/aws-lambda-powertools-python/2.10.0/) by Amazon.

&copy; Crossref 2023
