Package: fastapi-and-logging
fastapi-and-loggingFastAPI-and-Logging simplifies log handling, allowing for effective organization, tracking, and analysis of logs in FastAPI applications, aiding in debugging and issue resolution.Support for:Incoming LoggerException LoggerAPICall Logger (HTTPX, AIOHttp, requests (coming soon...))Kafka (coming soon...)Installpip install fastapi-and-loggingIncomiong LoggerThisFastAPIIncomingLogclass is designed to log incoming system requests using FastAPI.Parameters:app: It is used to set route_class.request_id_builder: A function to build a request identifier, if specified(It uses uuid4 by default).log_builder: A function used to construct logs.get_request_data: A function used to retrieve request information.get_response_data: A function used to retrieve response information.response_max_len: The maximum length of a response stored in the log (default is 5000).log_path (optional): Log file path.log_type: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).How to Use:To use this class, you can create an instance of it and set it as theroute_classfor your relevant Router in your FastAPI application.fromfastapiimportFastAPIfromfastapi_and_loggingimportFastAPIIncomingLogapp=FastAPI()FastAPIIncomingLog(app)Customizing and Using Default FunctionsThe provided default functions (get_request_data,get_response_data, andlog_builder) serve as customizable components for theFastAPIIncomingLogclass. Here's how you can customize and use them:get_request_dataThis function is responsible for extracting and formatting request data.fromfastapi_and_loggingimportRequestfromfastapi_and_logging.fastapiimportget_request_dataasyncdefcustomize_get_request_data(request:Request):# You can also use the output of the default functiondata=awaitget_request_data(request)returndataget_response_dataThis function handles the processing of response data.fromfastapiimportResponsefromfastapi_and_logging.fastapiimportget_response_datadefcustomize_get_response_data(response:Response)->dict|str:# You can also use the output of the default functiondata=get_response_data(response)returndatalog_builderThe log_builder function constructs the log data based on various parameters.fromfastapiimportRequest,Responsefromuser_agents.parsersimportUserAgentfromfastapi_and_logging.fastapiimportlog_builderdefcustomize_log_builder(request:Request,response:Response,request_data:dict|str,response_data:dict|str,user_agent:UserAgent,start_time:int,end_time:int,duration:int,):# You can also use the output of the default functiondata=log_builder(**)returndataException LoggerTo log all exceptions, simply use the ExceptionLogger class.Parameters:app: It is used to add exception handlers.log_path (optional): Log file path.log_type: The type of logging, which can be one of various types (default is LogTypeEnum.FILE).set_default_handlers: Whether to set default exception handlers (default: True).How to Use:fromfastapiimportFastAPIfromfastapi_and_loggingimportExceptionLoggerapp=FastAPI()ExceptionLogger(app)You can also add your own exception handlers as follows:fromfastapiimportFastAPI,Requestfromfastapi_and_loggingimportExceptionLoggerapp=FastAPI(debug=False)exception_logger=ExceptionLogger(app=app)asyncdeftest_exception_handler(request:Request,exc:Exception):returnJSONResponse(content={"message":"Internal Server Error"},)exception_logger.add_exception_handler(Exception,test_exception_handler)APICall LoggerNote: Currently it only supports httpx and aiohttp.HTTPXLoggerYou can easily log all apicalls using httpx by adding the HTTPXLogger class.Parameters:request_hook (optional): A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..response_hook (optional): A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.sync_client (optional): A boolean value indicating whether the logging functionality should be applied to synchronous HTTP clients. If True, the hooks and configuration will be set for synchronous clients. Defaults to True.async_client (optional): A boolean value indicating whether the logging functionality should be applied to asynchronous HTTP clients. If True, the hooks and configuration will be set for asynchronous clients. Defaults to True.request_max_len (optional): An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .response_max_len (optional): An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.log_path (optional): Log file path.log_type (optional): Specifies the type of logging, currently it takes two values: console and file.How to Use:importhttpxfromfastapiimportFastAPIfromfastapi_and_logging.http_clientsimportHTTPXLoggerapp=FastAPI()HTTPXLogger()@app.get("/")defindex():withhttpx.Client()asclient:response=client.get("http://localhost:8000/path")AioHttpLoggerYou can easily log all apicalls using httpx by adding the AioHttpLogger class.Parameters:request_hook (optional): A callable object that serves as a hook for capturing and logging HTTP requests. It takes a single parameter, the request object, and does not return any value. Defaults to None..response_hook (optional): A callable object that acts as a hook to capture and log HTTP responses. Any value returned will be logged.request_max_len (optional): An integer specifying the maximum length of the request body to be logged. If the request body exceeds this length, it will be truncated. Defaults to 5000 .response_max_len (optional): An integer specifying the maximum length of the response body to be logged. If the response body exceeds this length, it will be truncated. Defaults to 5000.log_path (optional): Log file path.log_type (optional): Specifies the type of logging, currently it takes two values: console and file.How to Use:importaiohttpfromfastapiimportFastAPIfromfastapi_and_logging.http_clientsimportAioHttpLoggerapp=FastAPI()AioHttpLogger()@app.get("/")asyncdefindex():asyncwithaiohttp.ClientSession()assession:asyncwithsession.get("http://localhost:8000/path",)asresponse:...To be able to have the request data or request ID associated with the incoming log in the apicall log, you need to follow the following steps. Additionally, you can send your desired parameters to log in the trace_request_ctx as well.importaiohttpfromfastapiimportRequest@app.get("/")asyncdefindex(request:Request):payload={"name":"FastAPI And Logging"}asyncwithaiohttp.ClientSession()assession:asyncwithsession.post("http://localhost:8000/path",json=payload,trace_request_ctx={"request_id":request.state.request_id,"request_data":payload,})asresponse:...