Monitoring and logging are important for keeping systems, applications, and services running smoothly. Think of monitoring as checking the vital signs of a system, like a doctor checking a patient’s health. Logging is like keeping a diary of everything that happens in the system.
Monitoring is important because:
Logging is also important because:
Without monitoring and logging, you might face:
Here is a simple example of how to monitor and log in a Python program using the psutil
library to monitor system performance and the logging
module to log events:
import psutil
import time
import logging
# Configure logging
logging.basicConfig(filename='system_monitor.log', level=logging.INFO, format='%(asctime)s - %(message)s')
def monitor_system():
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
logging.info(f"CPU Usage: {cpu_usage}%")
logging.info(f"Memory Usage: {memory_info.percent}%")
time.sleep(5)
if __name__ == "__main__":
monitor_system()
For a web application, you might use a monitoring tool like Prometheus along with Grafana for visualization, and the logging
module for logging. Here is a basic example using Flask, Prometheus, and logging:
from flask import Flask
from prometheus_client import start_http_server, Summary
import logging
# Configure logging
logging.basicConfig(filename='webapp.log', level=logging.INFO, format='%(asctime)s - %(message)s')
app = Flask(__name__)
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
@app.route('/')
@REQUEST_TIME.time()
def hello():
logging.info("Hello endpoint was called")
return "Hello, World!"
if __name__ == "__main__":
start_http_server(8000)
app.run(port=5000)
In this example, Prometheus collects metrics on the request processing time, which can then be visualized using Grafana, while logging records each request to the “Hello” endpoint.
Monitoring and logging are essential practices that help keep systems reliable, performing well, and secure. By implementing good monitoring and logging strategies, you can manage and maintain your systems effectively.