-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_initial.py
More file actions
170 lines (135 loc) · 4.48 KB
/
app_initial.py
File metadata and controls
170 lines (135 loc) · 4.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
from flask import Flask, request, jsonify, g, has_request_context
import logging
from pythonjsonlogger import jsonlogger
import uuid
import time
import sys
from datetime import datetime, timezone
app = Flask(__name__)
SERVICE_NAME = "service-a"
class RequestContextFilter(logging.Filter):
def filter(self, record):
record.timestamp = datetime.now(timezone.utc).isoformat()
record.level = record.levelname
if not hasattr(record, "service"):
record.service = SERVICE_NAME
if not hasattr(record, "correlation_id"):
if has_request_context():
record.correlation_id = getattr(g, "correlation_id", "no-correlation-id")
else:
record.correlation_id = "no-request-context"
return True
def setup_logging():
"""
Configure structured logging with JSON format.
Should include: timestamp, level, correlation_id, message, and extra fields
"""
log_handler = logging.StreamHandler(sys.stdout)
formatter = jsonlogger.JsonFormatter(
"%(timestamp)s %(level)s %(name)s %(service)s %(correlation_id)s %(message)s"
)
log_handler.setFormatter(formatter)
log_handler.addFilter(RequestContextFilter())
logger = logging.getLogger(SERVICE_NAME)
logger.handlers.clear()
logger.addHandler(log_handler)
logger.setLevel(logging.INFO)
logger.propagate = False
return logger
logger = setup_logging()
@app.before_request
def before_request():
"""
Extract correlation ID from headers or generate new one.
Store in Flask's g object for request context.
"""
g.correlation_id = request.headers.get("X-Correlation-ID", str(uuid.uuid4()))
g.request_start_time = time.time()
@app.after_request
def after_request(response):
response.headers["X-Correlation-ID"] = getattr(g, "correlation_id", "")
return response
def log_with_context(level, message, **kwargs):
"""
Log message with correlation ID and additional context.
Args:
level: Log level (info, warning, error)
message: Log message
**kwargs: Additional fields to include in log
"""
extra = {
"correlation_id": getattr(g, "correlation_id", "no-correlation-id"),
"timestamp": datetime.now(timezone.utc).isoformat(),
"service": SERVICE_NAME
}
extra.update(kwargs)
log_method = getattr(logger, level.lower(), logger.info)
log_method(message, extra=extra)
@app.route('/api/users', methods=['GET'])
def get_users():
"""Endpoint to retrieve users with structured logging"""
log_with_context(
"info",
"Incoming request for users",
method=request.method,
path=request.path,
remote_addr=request.remote_addr
)
# Simulate processing
time.sleep(0.1)
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
duration_ms = round((time.time() - g.request_start_time) * 1000, 2)
log_with_context(
"info",
"Users retrieved successfully",
status_code=200,
user_count=len(users),
duration_ms=duration_ms
)
return jsonify(users)
@app.route('/api/orders', methods=['POST'])
def create_order():
"""Endpoint to create order with error handling and logging"""
data = request.get_json(silent=True) or {}
log_with_context(
"info",
"Incoming order creation request",
method=request.method,
path=request.path,
payload_keys=list(data.keys())
)
required_fields = ["user_id", "amount"]
missing_fields = [field for field in required_fields if field not in data]
if missing_fields:
log_with_context(
"warning",
"Order validation failed",
status_code=400,
missing_fields=missing_fields
)
return jsonify({
"error": "Validation failed",
"missing_fields": missing_fields
}), 400
# Simulate order creation
order = {
"order_id": str(uuid.uuid4()),
"user_id": data.get('user_id'),
"amount": data.get('amount')
}
duration_ms = round((time.time() - g.request_start_time) * 1000, 2)
log_with_context(
"info",
"Order created successfully",
status_code=201,
order_id=order["order_id"],
user_id=order["user_id"],
amount=order["amount"],
duration_ms=duration_ms
)
return jsonify(order), 201
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False)