Azure Monitor Setup Guide
Task
- Create a VM
Assign the Following Roles
- Log Analytics Contributor
- Monitoring Contributor
Enable AMA
Create a Table and DCR
PART 1 — Generate Sample Logs
Follow the steps below to generate sample logs.
Step 1.1 — Install Flask
Open your terminal or command prompt and run:
Linux:
sudo apt-get install python3 -y
sudo apt install python3-pip -y
pip install flask
Windows:
choco install python3 -y
python get-pip.py
Step 1.2 — Create the Application File
Create a folder called mywebapp and inside it, create a file called app.py:
# app.py — Sample Flask Web App with Logging
import logging
import random
import time
from flask import Flask, request, jsonify
from datetime import datetime
app = Flask(__name__)
# ─── Configure File Logger ───────────────────────────────────────────────────
logging.basicConfig(
filename="C:/logs/webapp.log", # Windows path
# filename="/var/log/webapp/webapp.log", # Linux path (uncomment for Linux)
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S"
)
logger = logging.getLogger(__name__)
# ─── Routes ──────────────────────────────────────────────────────────────────
@app.route("/")
def home():
logger.info("Home page visited from IP: %s", request.remote_addr)
return "Welcome to the Sample Web App!"
@app.route("/order")
def order():
order_id = random.randint(1000, 9999)
logger.info("New order created. OrderID=%s", order_id)
return jsonify({"status": "success", "order_id": order_id})
@app.route("/error")
def trigger_error():
logger.error("Simulated ERROR: Payment gateway timeout at %s", datetime.now().isoformat())
return jsonify({"status": "error", "message": "Payment failed"}), 500
@app.route("/warning")
def trigger_warning():
logger.warning("Simulated WARNING: High memory usage detected — 87%%")
return jsonify({"status": "warning"})
# ─── Run ─────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
logger.info("Application starting up...")
app.run(debug=False, port=5000)
Step 1.3 — Create the Log Folder
On Windows (run as Administrator):
mkdir C:\logs
On Linux:
sudo mkdir -p /var/log/webapp
sudo chmod 777 /var/log/webapp
Step 1.4 — Run the App
cd mywebapp
python app.py
Visit these URLs in your browser to generate logs:
| URL | Log Type Generated |
|---|---|
| http://localhost:5000/ | INFO |
| http://localhost:5000/order | INFO |
| http://localhost:5000/warning | WARNING |
| http://localhost:5000/error | ERROR |
PART 2 — Add Dummy Logs (Optional — No App Needed)
💡 Use this method if you just want to test Azure Monitor without running an app.
Step 2.1 — Create a Dummy Log Generator Script
Create a file called generate_dummy_logs.py:
# generate_dummy_logs.py — Writes fake logs every few seconds
import random
import time
from datetime import datetime
# LOG_FILE = "C:/logs/webapp.log" # Windows
LOG_FILE = "/var/log/webapp/webapp.log" # Linux
LEVELS = ["INFO", "WARNING", "ERROR", "DEBUG"]
MESSAGES = [
"User login successful. UserID={}",
"Order placed. OrderID={}",
"Payment failed. TransactionID={}",
"High CPU usage: {}%",
"Database connection timeout. RetryAttempt={}",
"Cache miss for key: session_{}",
"Email sent to user_{}@example.com",
"API response time: {}ms",
]
print(f"Writing dummy logs to: {LOG_FILE}")
print("Press Ctrl+C to stop.\n")
while True:
timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
level = random.choice(LEVELS)
message = random.choice(MESSAGES).format(random.randint(100, 9999))
log_line = f"{timestamp} {level} {message}\n"
with open(LOG_FILE, "a") as f:
f.write(log_line)
print(log_line.strip())
time.sleep(2) # writes a new log every 2 seconds
Run it:
python generate_dummy_logs.py
Your C:\logs\webapp.log (or /var/log/webapp/webapp.log) will now be populated with a new log entry every 2 seconds.
