litewave-logger 0.1.0__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import logging
2
- import uuid
2
+ import json
3
3
  from contextvars import ContextVar
4
4
 
5
5
  # Context variable to hold the request ID
@@ -8,6 +8,9 @@ from contextvars import ContextVar
8
8
  # Magically, this is maintained across multiple requests without it getting mixed up.
9
9
  request_id_var = ContextVar("request_id", default=None)
10
10
 
11
+ # List of endpoints that should not be logged
12
+ _excluded_endpoints = []
13
+
11
14
 
12
15
  class RequestIdFilter(logging.Filter):
13
16
  """
@@ -17,21 +20,45 @@ class RequestIdFilter(logging.Filter):
17
20
  record.request_id = request_id_var.get()
18
21
  return True
19
22
 
23
+ class JsonLogFormatter(logging.Formatter):
24
+ """
25
+ Formatter that outputs logs as JSON with required fields.
26
+ """
27
+ def format(self, record):
28
+ # Collect fields with fallback to None for path, method, and status_code
29
+ log_object = {
30
+ "timestamp": self.formatTime(record, self.datefmt),
31
+ "level": record.levelname,
32
+ "request_id": getattr(record, "request_id", None),
33
+ "path": getattr(record, "path", None),
34
+ "method": getattr(record, "method", None),
35
+ "message": record.getMessage(),
36
+ "status_code": getattr(record, "status_code", None),
37
+ "error": getattr(record, "error", None),
38
+ }
39
+ return json.dumps(log_object)
20
40
 
21
- def setup_logging():
41
+ def setup_logging(excluded_endpoints=[]):
22
42
  """
23
43
  Configures the logging for the application.
24
- It sets up a handler, a formatter, and adds the RequestIdFilter.
44
+ Uses a JSON formatter and adds the RequestIdFilter.
45
+
46
+ Args:
47
+ excluded_endpoints: List of endpoint paths that should not be logged.
48
+ For example: ['/health', '/metrics']
49
+ Defaults to None (empty list).
25
50
  """
51
+ global _excluded_endpoints
52
+
53
+ _excluded_endpoints = excluded_endpoints
54
+
26
55
  logger = logging.getLogger()
27
56
  logger.setLevel(logging.INFO)
28
57
 
29
58
  # Prevent adding duplicate handlers
30
59
  if not logger.handlers:
31
60
  handler = logging.StreamHandler()
32
- formatter = logging.Formatter(
33
- "%(asctime)s - %(name)s - %(levelname)s - [%(request_id)s] - %(message)s"
34
- )
61
+ formatter = JsonLogFormatter()
35
62
  handler.setFormatter(formatter)
36
63
  logger.addHandler(handler)
37
64
 
@@ -42,4 +69,10 @@ def setup_logging():
42
69
 
43
70
  return logger
44
71
 
45
- __all__ = ["setup_logging", "request_id_var", "RequestIdFilter"]
72
+ def get_excluded_endpoints():
73
+ """
74
+ Returns the list of excluded endpoints.
75
+ """
76
+ return _excluded_endpoints
77
+
78
+ __all__ = ["setup_logging", "request_id_var", "RequestIdFilter", "get_excluded_endpoints"]
@@ -1,31 +1,64 @@
1
1
  import uuid
2
+ import time
3
+ import logging
4
+ from datetime import datetime
2
5
  from starlette.middleware.base import BaseHTTPMiddleware
3
6
  from starlette.requests import Request
4
7
 
5
- from . import request_id_var
8
+ from . import request_id_var, get_excluded_endpoints
6
9
 
7
- # This middleware is used to handle the request ID.
10
+ logger = logging.getLogger(__name__)
11
+ RequestIdHeader = "X-Request-ID"
12
+ # This middleware is used to handle the request ID and provide comprehensive debugging.
8
13
  # It checks for a 'X-Request-ID' header in the incoming request.
9
14
  # If the header is present, its value is used as the request ID.
10
15
  # If not, a new UUID is generated.
11
16
  # The request ID is then stored in a context variable.
12
17
  class RequestIdMiddleware(BaseHTTPMiddleware):
13
18
  """
14
- FastAPI middleware to handle the request ID.
19
+ FastAPI middleware to handle the request ID and provide comprehensive debugging.
15
20
  It checks for a 'X-Request-ID' header in the incoming request.
16
21
  If the header is present, its value is used as the request ID.
17
22
  If not, a new UUID is generated.
18
23
  The request ID is then stored in a context variable.
24
+ Provides detailed logging for incoming requests and outgoing responses.
19
25
  """
20
26
  async def dispatch(self, request: Request, call_next):
21
- request_id = request.headers.get("X-Request-ID")
27
+ # Extract request information
28
+ method = request.method
29
+ path = request.url.path
30
+ # Get or generate request ID
31
+ request_id = request.headers.get(RequestIdHeader)
22
32
  if not request_id:
23
33
  request_id = str(uuid.uuid4())
24
-
34
+
35
+ # Set request ID in context
25
36
  request_id_var.set(request_id)
26
-
27
- response = await call_next(request)
28
- response.headers["X-Request-ID"] = request_id_var.get()
29
- return response
37
+
38
+ # Check if this endpoint should be excluded from logging
39
+ excluded_endpoints = get_excluded_endpoints()
40
+ should_log = path not in excluded_endpoints
41
+
42
+ if should_log:
43
+ logger.info("request received", extra={"method": method, "path": path})
44
+
45
+ try:
46
+ # Process the request
47
+ response = await call_next(request)
48
+
49
+ # Add request ID to response headers
50
+ response.headers[RequestIdHeader] = request_id
51
+
52
+ # Log response details only if endpoint is not excluded
53
+ if should_log:
54
+ logger.info("response sent", extra={"status_code": response.status_code})
55
+
56
+ return response
57
+
58
+ except Exception as e:
59
+ logger.error("request failed", extra={"method": method, "path": path, "error": str(e)})
60
+
61
+ # Re-raise the exception
62
+ raise
30
63
 
31
64
  __all__ = ["RequestIdMiddleware"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: litewave_logger
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: A lightweight logging library with context carry forward
5
5
  Author: Litewave
6
6
  Author-email: Sonu Sudhakaran <sonu@litewave.ai>
@@ -18,10 +18,12 @@ This module provides a centralized and consistent logging solution for Litewave
18
18
  ## Features
19
19
 
20
20
  - **Centralized Logging**: A single module to configure and manage logging across all services.
21
+ - **JSON Logging**: All logs are formatted as JSON for easy parsing and integration with log aggregation systems.
21
22
  - **Request ID Propagation**: Automatically injects a `request-id` into all log messages.
22
- - **FastAPI Integration**: Middleware for FastAPI to handle `request-id` for incoming HTTP requests.
23
- - **Celery Integration**: Signal handlers to propagate the `request-id` to Celery tasks.
23
+ - **FastAPI Integration**: Middleware for FastAPI to handle `request-id` for incoming HTTP requests and adds it to response headers.
24
+ - **Celery Integration**: Signal handlers to propagate the `request-id` to Celery tasks automatically.
24
25
  - **Requests Library Patching**: Automatically injects the `request-id` into outgoing HTTP requests made with the `requests` library.
26
+ - **Endpoint Exclusion**: Configure endpoints that should not be logged (e.g., health checks, metrics).
25
27
 
26
28
  ## Installation
27
29
 
@@ -37,7 +39,8 @@ To use the `litewave_logger` in your service, follow these steps:
37
39
  ```python
38
40
  from litewave_logger import setup_logging
39
41
 
40
- setup_logging()
42
+ # Optionally exclude endpoints from logging (e.g., health checks, metrics)
43
+ setup_logging(excluded_endpoints=['/health', '/metrics'])
41
44
  ```
42
45
 
43
46
  2. **Add the FastAPI middleware**: If your service is a FastAPI application, add the `RequestIdMiddleware` to your FastAPI app.
@@ -58,10 +61,11 @@ To use the `litewave_logger` in your service, follow these steps:
58
61
  patch_requests()
59
62
  ```
60
63
 
61
- 4. **Connect Celery signals**: If your service uses Celery, you need to import the Celery signal handlers to ensure they are registered. You don't need to call them directly.
64
+ 4. **Connect Celery signals**: If your service uses Celery, you need to import the Celery module to ensure the signal handlers are registered. The signal handlers are automatically connected via decorators, so you don't need to call them directly.
62
65
 
63
66
  ```python
64
- from litewave_logger.celery import propagate_request_id_to_celery, clear_request_id_after_celery
67
+ # Just import the module - signal handlers are automatically registered
68
+ import litewave_logger.celery
65
69
  ```
66
70
 
67
71
  ### Example
@@ -74,11 +78,11 @@ from litewave_logger import setup_logging
74
78
  from litewave_logger.middleware import RequestIdMiddleware
75
79
  from litewave_logger.requests import patch_requests
76
80
 
77
- # These imports are needed to register the signal handlers
78
- from litewave_logger.celery import propagate_request_id_to_celery, clear_request_id_after_celery
81
+ # Import Celery module to register signal handlers (if using Celery)
82
+ import litewave_logger.celery
79
83
 
80
- # 1. Initialize logging
81
- setup_logging()
84
+ # 1. Initialize logging (optionally exclude endpoints)
85
+ setup_logging(excluded_endpoints=['/health', '/metrics'])
82
86
 
83
87
  # 2. Patch requests library
84
88
  patch_requests()
@@ -90,3 +94,31 @@ app.add_middleware(RequestIdMiddleware)
90
94
 
91
95
  # Your application code here...
92
96
  ```
97
+
98
+ ## How It Works
99
+
100
+ ### Request ID Flow
101
+
102
+ 1. **Incoming HTTP Request**: The `RequestIdMiddleware` checks for an `X-Request-ID` header. If present, it uses that value; otherwise, it generates a new UUID.
103
+ 2. **Context Variable**: The request ID is stored in a context variable (`request_id_var`) that is automatically maintained across async operations.
104
+ 3. **Logging**: All log messages automatically include the request ID via the `RequestIdFilter`.
105
+ 4. **Outgoing Requests**: When using the `requests` library, the request ID is automatically injected as the `X-Request-ID` header.
106
+ 5. **Response Headers**: The request ID is added to the response headers as `X-Request-ID`.
107
+ 6. **Celery Tasks**: When a Celery task is published, the request ID is automatically included in the task headers and propagated to the worker process.
108
+
109
+ ### Log Format
110
+
111
+ All logs are formatted as JSON with the following structure:
112
+
113
+ ```json
114
+ {
115
+ "timestamp": "2024-01-01 12:00:00",
116
+ "level": "INFO",
117
+ "request_id": "550e8400-e29b-41d4-a716-446655440000",
118
+ "path": "/api/users",
119
+ "method": "GET",
120
+ "message": "request received",
121
+ "status_code": 200,
122
+ "error": null
123
+ }
124
+ ```
@@ -0,0 +1,8 @@
1
+ litewave_logger/__init__.py,sha256=gow3U-Op3f4xNTQ3ppBUD8mEAA0d_3hVa_u88mKLigg,2599
2
+ litewave_logger/celery.py,sha256=KkeuXNTQm7P_TFj_POdt7WTHL-mcP_Jv60g06Fkw_M4,3358
3
+ litewave_logger/middleware.py,sha256=P3Mjv0RZ7Bh7cxmJ4pH537wsORSXP-Dgn1PE9EKUcgQ,2375
4
+ litewave_logger/requests.py,sha256=tagJVwWWSVnrYHYRJ24HXu7YNBs9WxIHql0E1fRkbGA,1236
5
+ litewave_logger-0.3.0.dist-info/METADATA,sha256=3aIHcutM1eocQhI50SVjKpB3U1rCglvbwbL9CW5v7OQ,4839
6
+ litewave_logger-0.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ litewave_logger-0.3.0.dist-info/top_level.txt,sha256=omvs1vFc7ccmip7_gMDjF_3F8omnR-Gdfm2UudrqWuo,16
8
+ litewave_logger-0.3.0.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- litewave_logger/__init__.py,sha256=NgRQIlAbGXrlVoL5hcWHs3jbeNZPJ3j9zLuPfpf6vPc,1443
2
- litewave_logger/celery.py,sha256=KkeuXNTQm7P_TFj_POdt7WTHL-mcP_Jv60g06Fkw_M4,3358
3
- litewave_logger/middleware.py,sha256=oiWsRO9i8W7hlQrg0wJvOmAxqTkjkvASKa2psaA9Tbk,1161
4
- litewave_logger/requests.py,sha256=tagJVwWWSVnrYHYRJ24HXu7YNBs9WxIHql0E1fRkbGA,1236
5
- litewave_logger-0.1.0.dist-info/METADATA,sha256=0TSMGW8hGWb42X7Ls7Hfe7LN7gIqv3eyPBDD0C7StwA,3211
6
- litewave_logger-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
- litewave_logger-0.1.0.dist-info/top_level.txt,sha256=omvs1vFc7ccmip7_gMDjF_3F8omnR-Gdfm2UudrqWuo,16
8
- litewave_logger-0.1.0.dist-info/RECORD,,