Structured logging to TSV files with JSON context: grep-able, compressible and searchable.

0 downloads

dbbasic-logs/examples/flask_app.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-logs.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-logs.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-logs.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add PyPI badges and links to README cea7e20 1 year, 1 month ago History
flask_app.py · 3.3 KB · 123 lines
1#!/usr/bin/env python3
2"""
3Example Flask application using dbbasic-logs
4"""
5
6from flask import Flask, request, jsonify
7from dbbasic_logs import log
8import time
9
10app = Flask(__name__)
11
12
13# Request logging middleware
14@app.before_request
15def log_request_start():
16 request.start_time = time.time()
17
18
19@app.after_request
20def log_request_end(response):
21 duration = time.time() - request.start_time
22
23 log.access(
24 method=request.method,
25 path=request.path,
26 status=response.status_code,
27 duration=duration,
28 ip=request.remote_addr,
29 user_agent=request.user_agent.string
30 )
31
32 return response
33
34
35# Routes
36@app.route('/')
37def index():
38 log.info("Homepage visited", ip=request.remote_addr)
39 return jsonify({"message": "Welcome to DBBasic Logs example"})
40
41
42@app.route('/api/users/<int:user_id>')
43def get_user(user_id):
44 log.info("Fetching user", user_id=user_id, ip=request.remote_addr)
45
46 # Simulate user lookup
47 if user_id == 42:
48 return jsonify({"id": 42, "name": "John Doe"})
49 else:
50 log.warning("User not found", user_id=user_id)
51 return jsonify({"error": "User not found"}), 404
52
53
54@app.route('/api/process', methods=['POST'])
55def process_data():
56 try:
57 data = request.get_json()
58
59 if not data:
60 log.warning("Invalid request - no JSON data", ip=request.remote_addr)
61 return jsonify({"error": "No data provided"}), 400
62
63 log.info("Processing data", data_keys=list(data.keys()))
64
65 # Simulate processing that might fail
66 if data.get('fail'):
67 raise ValueError("Simulated processing error")
68
69 result = {"status": "processed", "count": len(data)}
70 log.info("Processing complete", result=result)
71
72 return jsonify(result)
73
74 except Exception as e:
75 log.exception("Processing failed", error=str(e), data=data)
76 return jsonify({"error": "Processing failed"}), 500
77
78
79@app.route('/admin/logs')
80def view_logs():
81 """Simple log viewer endpoint"""
82 log_type = request.args.get('type', 'app')
83 lines = int(request.args.get('lines', 100))
84
85 try:
86 recent_logs = log.tail(log_type, lines=lines)
87 return jsonify({
88 "log_type": log_type,
89 "count": len(recent_logs),
90 "logs": recent_logs
91 })
92 except Exception as e:
93 log.exception("Failed to retrieve logs", log_type=log_type)
94 return jsonify({"error": str(e)}), 500
95
96
97@app.route('/admin/search')
98def search_logs():
99 """Simple log search endpoint"""
100 pattern = request.args.get('pattern')
101 log_type = request.args.get('type', 'app')
102 days = int(request.args.get('days', 7))
103
104 if not pattern:
105 return jsonify({"error": "pattern parameter required"}), 400
106
107 try:
108 results = log.search(pattern, log_type=log_type, days=days)
109 return jsonify({
110 "pattern": pattern,
111 "log_type": log_type,
112 "days": days,
113 "count": len(results),
114 "results": results[:100] # Limit to 100 results
115 })
116 except Exception as e:
117 log.exception("Search failed", pattern=pattern)
118 return jsonify({"error": str(e)}), 500
119
120
121if __name__ == '__main__':
122 log.info("Starting Flask application", port=5000)
123 app.run(debug=True, port=5000)