1- import os
2- import socket
3- import platform
4- import logging
5- from datetime import datetime , timezone , timedelta
6- from flask import Flask , jsonify , request
7-
8- # Configuration
9- HOST = os .getenv ('HOST' , '0.0.0.0' )
10- PORT = int (os .getenv ('PORT' , '5000' ))
11- DEBUG = os .getenv ('DEBUG' , 'False' ).lower () == 'true'
12-
13- # Application Setup
14- app = Flask (__name__ )
15- app_start_time = datetime .now (timezone .utc )
16-
17- # Logging Configuration
18- logging .basicConfig (
19- level = logging .DEBUG if DEBUG else logging .INFO ,
20- format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
21- )
22- logger = logging .getLogger (__name__ )
23-
24- # Helper Functions
25- def get_system_info ():
26- """Collect comprehensive system information."""
27- return {
28- 'hostname' : socket .gethostname (),
29- 'platform' : platform .system (),
30- 'platform_version' : platform .version (),
31- 'architecture' : platform .machine (),
32- 'cpu_count' : os .cpu_count () or 0 ,
33- 'python_version' : platform .python_version ()
34- }
35-
36- def get_uptime ():
37- """Calculate application uptime in seconds and human-readable format."""
38- delta = datetime .now (timezone .utc ) - app_start_time
39- seconds = int (delta .total_seconds ())
40-
41- # Calculate human-readable format
42- days , remainder = divmod (seconds , 86400 )
43- hours , remainder = divmod (remainder , 3600 )
44- minutes , seconds = divmod (remainder , 60 )
45-
46- human_parts = []
47- if days > 0 :
48- human_parts .append (f"{ days } day{ 's' if days != 1 else '' } " )
49- if hours > 0 :
50- human_parts .append (f"{ hours } hour{ 's' if hours != 1 else '' } " )
51- if minutes > 0 :
52- human_parts .append (f"{ minutes } minute{ 's' if minutes != 1 else '' } " )
53- if seconds > 0 or not human_parts :
54- human_parts .append (f"{ seconds } second{ 's' if seconds != 1 else '' } " )
55-
56- return {
57- 'seconds' : seconds ,
58- 'human' : ', ' .join (human_parts )
59- }
60-
611# Application Endpoints
622@app .route ('/' )
633def main_endpoint ():
644 """Main endpoint returning service and system information."""
65- logger .info (f"Main endpoint accessed by { request .remote_addr } " )
66-
5+ logger .info ('Main endpoint accessed' )
676 return jsonify ({
687 'service' : {
698 'name' : 'devops-info-service' ,
@@ -93,8 +32,7 @@ def main_endpoint():
9332@app .route ('/health' )
9433def health_check ():
9534 """Health check endpoint for monitoring and probes."""
96- logger .debug (f"Health check from { request .remote_addr } " )
97-
35+ logger .debug ('Health check performed' )
9836 return jsonify ({
9937 'status' : 'healthy' ,
10038 'timestamp' : datetime .now (timezone .utc ).isoformat (),
@@ -104,7 +42,10 @@ def health_check():
10442# Error Handlers
10543@app .errorhandler (404 )
10644def not_found (error ):
107- logger .warning (f"404 error: { request .path } " )
45+ logger .warning ('404 Not Found' , extra = {
46+ 'path' : request .path ,
47+ 'method' : request .method
48+ })
10849 return jsonify ({
10950 'error' : 'Not Found' ,
11051 'message' : 'The requested endpoint does not exist' ,
@@ -113,14 +54,20 @@ def not_found(error):
11354
11455@app .errorhandler (500 )
11556def internal_error (error ):
116- logger .error (f"500 error: { str (error )} " )
57+ logger .error ('500 Internal Server Error' , exc_info = True , extra = {
58+ 'path' : request .path ,
59+ 'method' : request .method
60+ })
11761 return jsonify ({
11862 'error' : 'Internal Server Error' ,
11963 'message' : 'An unexpected error occurred'
12064 }), 500
12165
12266# Application Entry Point
123- if __name__ == '__main__' :
124- logger .info (f"Starting DevOps Info Service on { HOST } :{ PORT } " )
125- logger .info (f"Debug mode: { DEBUG } " )
126- app .run (host = HOST , port = PORT , debug = DEBUG )
67+ if name == 'main' :
68+ logger .info ('Application starting' , extra = {
69+ 'host' : HOST ,
70+ 'port' : PORT ,
71+ 'debug' : DEBUG
72+ })
73+ app .run (host = HOST , port = PORT , debug = DEBUG )
0 commit comments