Security and hardening · Intermediate · 28 min
Log security events an analyst can use
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · FastAPI 0.165 · Uvicorn 0.54 · pytest 9.2
You will add structured JSON security events to a FastAPI app, with a fixed event vocabulary, request IDs, UTC timestamps, the real client address behind a proxy, redaction of secrets, protection against log injection and a retention policy, all checked by pytest.
On this page
When something goes wrong, the first question an analyst asks is "what happened, to whom, from where, and when?". Most application logs cannot answer it. They hold free-text lines such as Login failed for ada, written in local time, with no way to tie a line to the request that caused it, and sometimes with the password that was typed. Security logging is a different job from debug logging: the reader is a person or a detection rule looking for patterns across thousands of events, and the log itself is a store of personal data that needs protecting.
In this tutorial you add a small security event module to a FastAPI app. Every event is one JSON object on one line, with a name from a fixed list, a UTC timestamp, a user ID, a request ID and the client's real address, even behind a reverse proxy. You decide what to record (sign-in success and failure, MFA changes, permission denials, admin actions, data exports) and what never to record (passwords, tokens, full card numbers, and more personal data than the purpose needs). pytest proves the events are emitted and that secrets and forged lines cannot get in. Then you run the app, answer analyst questions with jq, and set a retention period with logrotate.
The app is a deliberately small API with users kept in memory. If you are new to Python's logging module, read log properly in Python with the logging module first: this tutorial builds on handlers and formatters without re-explaining them.
Step 1 · Decide what to log and what never to log
Before any code, write the list down. It becomes your event vocabulary, and an analyst can only search for names that never change. This tutorial follows the names in the OWASP Logging Vocabulary where one exists, and adds two for MFA:
authn_login_success: correct password (INFO)authn_login_fail: wrong password or unknown user (WARNING)authn_mfa_enabledandauthn_mfa_disabled: a user turns MFA on (INFO) or off (WARNING)authz_fail: a signed-in user is refused (WARNING)authz_change: an admin changes someone's role (INFO)sensitive_read: a bulk data export (INFO)
Every event carries the same fields, so one query works across all of them: ts (UTC, ISO 8601, ending in Z), app, event, outcome, level, user_id, request_id, client_ip, method, path, user_agent and a details object for anything event-specific.
Never log:
- passwords, including wrong ones, which are often a typo away from the right one
- session tokens, API keys,
AuthorizationandCookieheaders, one-time codes - full card numbers or security codes; at most the last four digits
- names, email addresses and phone numbers when an internal user ID will do
Both the EU's GDPR and Nigeria's Data Protection Act 2023 ask you to keep personal data to the minimum the purpose needs and for no longer than necessary. An IP address next to a user ID is personal data. Security monitoring is a recognised reason to keep it, which is why the log holds user_id and client_ip but not the user's name or email, and why the last step sets a deletion date.
Check it worked
Write your own app's list in the same shape: one line per event, a name in area_action_result form, and a level. If two people on your team would name the same event differently, settle it now. Check your list against the "never log" items: no field in it should ever hold one.
Step 2 · Create the project
Make a throwaway project folder and add FastAPI and Uvicorn, with pytest and httpx2 for the tests. The ranges allow patch releases only:
mkdir -p ~/security-log-demo
cd ~/security-log-demo
uv init --no-package
rm main.py
uv add "fastapi>=0.165,<0.166" "uvicorn>=0.54,<0.55"
uv add --dev "pytest>=9.2,<9.3" "httpx2>=2.16,<2.17"uv init creates a placeholder main.py, which you remove because the app lives in app.py. FastAPI's test client uses httpx2 when it is installed.
Check it worked
uv run python -c "import fastapi, uvicorn; print(fastapi.__version__, uvicorn.__version__)"The output is 0.165.0 0.54.0, or later patch releases of each.
Step 3 · Write the security event module
Put everything about security logging in one module, seclog.py, so routes never format a log line themselves:
cat > seclog.py <<'PY'
import ipaddress
import json
import logging
import logging.handlers
import os
import re
import unicodedata
from datetime import datetime, timezone
from enum import StrEnum
APP_ID = "notes-api"
class Event(StrEnum):
LOGIN_SUCCESS = "authn_login_success"
LOGIN_FAIL = "authn_login_fail"
MFA_ENABLED = "authn_mfa_enabled"
MFA_DISABLED = "authn_mfa_disabled"
AUTHZ_FAIL = "authz_fail"
AUTHZ_CHANGE = "authz_change"
DATA_EXPORT = "sensitive_read"
SECRET_KEY_PARTS = ("password", "secret", "token", "authorization", "cookie",
"api_key", "apikey", "card", "cvv", "otp")
CARD_RE = re.compile(r"\b(?:\d[ -]?){12,18}\d\b")
BEARER_RE = re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._~+/=-]+")
BIDI = set("\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069")
MAX_LEN = 200
def clean(text: str) -> str:
"""Make one untrusted string safe to put in a log line."""
out = []
for ch in str(text)[:MAX_LEN]:
if ch in BIDI or unicodedata.category(ch) in ("Cc", "Zl", "Zp"):
out.append("\ufffd")
else:
out.append(ch)
text = "".join(out)
text = BEARER_RE.sub("Bearer [REDACTED]", text)
return CARD_RE.sub(lambda m: "[CARD ****" + re.sub(r"\D", "", m.group())[-4:] + "]", text)
def redact(value, key=""):
if any(part in key.lower() for part in SECRET_KEY_PARTS):
return "[REDACTED]"
if isinstance(value, dict):
return {clean(k): redact(v, k) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [redact(v, key) for v in value]
if isinstance(value, str):
return clean(value)
return value
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def client_ip(peer: str, forwarded_for: str | None, trusted: set[str]) -> str:
"""Return the client address, trusting X-Forwarded-For only from our own proxies."""
if peer not in trusted or not forwarded_for:
return peer
hops = [h.strip() for h in forwarded_for.split(",")]
for hop in reversed(hops):
try:
ipaddress.ip_address(hop)
except ValueError:
return peer
if hop not in trusted:
return hop
return peer
class JsonFormatter(logging.Formatter):
def format(self, record):
return json.dumps(record.security, ensure_ascii=False, separators=(",", ":"))
logger = logging.getLogger("security")
logger.setLevel(logging.INFO)
logger.propagate = False
def configure(path: str) -> None:
os.makedirs(os.path.dirname(path) or ".", mode=0o750, exist_ok=True)
os.close(os.open(path, os.O_CREAT | os.O_APPEND | os.O_WRONLY, 0o640))
handler = logging.handlers.WatchedFileHandler(path, encoding="utf-8")
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
def security_event(event: Event, *, outcome: str, request, user_id=None, level="INFO", **details):
record = {
"ts": utc_now(),
"app": APP_ID,
"event": event.value,
"outcome": outcome,
"level": level,
"user_id": user_id,
"request_id": request.state.request_id,
"client_ip": request.state.client_ip,
"method": request.method,
"path": clean(request.url.path),
"user_agent": clean(request.headers.get("user-agent", "")),
"details": redact(details),
}
logger.log(getattr(logging, level), event.value, extra={"security": record})
PYWhat each part does:
Eventis the vocabulary. A route passesEvent.LOGIN_FAIL, never a string, so a misspelt member raises anAttributeErrorthe first time that code runs, and the tests catch it, instead of silently creating a new event name.cleanhandles any untrusted string: the user agent, the path, values indetails. It cuts it to 200 characters and replaces control characters (Cc), Unicode line and paragraph separators, and the bidirectional overrides that can make text display in a different order from how it is stored. It leaves letters, accents and combining marks alone, so names in Yorùbá, Hausa, Amharic or Persian stay readable. It also masks card-number-like digit runs andBearertokens that turn up inside free text.redactwalksdetailsand replaces the value of any key whose name containspassword,token,secret,cookie,card,otpand similar. It errs on the side of hiding too much: a key calleddiscard_reasonis hidden too.client_ipdecides who the client is.X-Forwarded-Foris a header anyone can send, so it is believed only when the connection comes from one of your own proxies, and then only the rightmost address your proxies did not add.JsonFormatterwrites one JSON object per line.json.dumpsalways escapes newlines and other control characters, which is the main defence against forged lines;cleanadds defence for characters JSON leaves as they are whenensure_ascii=False.configurecreates the log folder and file private to your user before the first write, and usesWatchedFileHandler, which notices when logrotate moves the file and opens a new one.
Check it worked
uv run python -c "from seclog import clean, client_ip; print(clean('ada' + chr(10) + 'forged')); print(client_ip('10.0.0.2', '203.0.113.7', {'10.0.0.2'}))"The output is ada�forged on one line, then 203.0.113.7. The newline has become the replacement character, and the forwarded address was believed because 10.0.0.2 is in the trusted set.
Step 4 · Emit events from the app
Now write app.py. A middleware gives every request an ID and works out the client address once; each route then calls security_event at the moment something security-relevant happens:
cat > app.py <<'PY'
import hashlib
import os
import re
import secrets
import uuid
from fastapi import Depends, FastAPI, HTTPException, Request
from pydantic import BaseModel
from seclog import Event, client_ip, configure, security_event
configure(os.environ.get("SECURITY_LOG_FILE", "logs/security.log"))
TRUSTED_PROXIES = {p for p in os.environ.get("TRUSTED_PROXIES", "").split(",") if p}
REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9-]{8,64}$")
app = FastAPI()
USERS: dict[str, dict] = {}
SESSIONS: dict[str, str] = {}
def hash_password(password: str, salt: bytes) -> bytes:
return hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1)
def add_user(user_id: str, username: str, password: str, role: str) -> None:
salt = secrets.token_bytes(16)
USERS[username] = {"id": user_id, "salt": salt, "hash": hash_password(password, salt),
"role": role, "mfa": True}
if os.environ.get("DEMO_PASSWORD"):
add_user("u_1001", "ada", os.environ["DEMO_PASSWORD"], "admin")
add_user("u_1002", "tunde", os.environ["DEMO_PASSWORD"], "member")
@app.middleware("http")
async def request_context(request: Request, call_next):
incoming = request.headers.get("x-request-id", "")
request.state.request_id = incoming if REQUEST_ID_RE.match(incoming) else str(uuid.uuid4())
peer = request.client.host if request.client else "unknown"
request.state.client_ip = client_ip(peer, request.headers.get("x-forwarded-for"), TRUSTED_PROXIES)
response = await call_next(request)
response.headers["X-Request-ID"] = request.state.request_id
return response
class Login(BaseModel):
username: str
password: str
def user_by_id(user_id: str) -> dict:
return next(u for u in USERS.values() if u["id"] == user_id)
def current_user(request: Request) -> dict:
token = request.headers.get("authorization", "").removeprefix("Bearer ")
if token not in SESSIONS:
raise HTTPException(401, "sign in first")
return user_by_id(SESSIONS[token])
@app.get("/health")
def health():
return {"ok": True}
@app.post("/login")
def login(body: Login, request: Request):
user = USERS.get(body.username)
if user and secrets.compare_digest(hash_password(body.password, user["salt"]), user["hash"]):
token = secrets.token_urlsafe(32)
SESSIONS[token] = user["id"]
security_event(Event.LOGIN_SUCCESS, outcome="success", request=request, user_id=user["id"])
return {"token": token}
security_event(Event.LOGIN_FAIL, outcome="failure", request=request, level="WARNING",
user_id=user["id"] if user else None, username_known=user is not None)
raise HTTPException(401, "wrong username or password")
class Mfa(BaseModel):
enabled: bool
@app.post("/account/mfa")
def set_mfa(body: Mfa, request: Request, user: dict = Depends(current_user)):
user["mfa"] = body.enabled
event = Event.MFA_ENABLED if body.enabled else Event.MFA_DISABLED
security_event(event, outcome="success", request=request, user_id=user["id"],
level="INFO" if body.enabled else "WARNING")
return {"mfa": body.enabled}
class Role(BaseModel):
role: str
@app.post("/admin/users/{target_id}/role")
def change_role(target_id: str, body: Role, request: Request, user: dict = Depends(current_user)):
if user["role"] != "admin":
security_event(Event.AUTHZ_FAIL, outcome="denied", request=request, level="WARNING",
user_id=user["id"], resource=f"user:{target_id}:role")
raise HTTPException(403, "admins only")
target = next((u for u in USERS.values() if u["id"] == target_id), None)
if target is None:
raise HTTPException(404, "no such user")
old, target["role"] = target["role"], body.role
security_event(Event.AUTHZ_CHANGE, outcome="success", request=request, user_id=user["id"],
target_user_id=target_id, from_role=old, to_role=body.role)
return {"user_id": target_id, "role": body.role}
@app.get("/export")
def export(request: Request, user: dict = Depends(current_user)):
rows = [{"id": u["id"], "role": u["role"]} for u in USERS.values()]
security_event(Event.DATA_EXPORT, outcome="success", request=request, user_id=user["id"],
resource="users", record_count=len(rows), format="json")
return rows
PYPoints worth noticing:
- The request ID comes from an
X-Request-IDheader if your proxy or load balancer already set one and it looks like an ID, otherwise fromuuid4. It goes back in the response, so a support ticket that quotes it leads straight to the log line. - A failed sign-in for a real account records the account's
user_id. A failed sign-in for a name that does not exist recordsusername_known: falseand nothing else, because people often paste a password into the username box. Failures per address are still visible to the analyst. - Turning MFA off is a
WARNING: it is a common step after an account takeover. - The refused role change is logged before the
403is raised, with what was asked for inresource. TRUSTED_PROXIESandDEMO_PASSWORDcome from environment variables. No secret is written in the code. Passwords are stored as scrypt hashes; for a real app use Argon2id as in hash passwords with Argon2id.
Check it worked
uv run python -c "from app import app; print(sorted(r.path for r in app.routes if not r.path.startswith(('/docs', '/openapi', '/redoc'))))"
ls -l logsThe first line lists /account/mfa, /admin/users/{target_id}/role, /export, /health and /login. ls shows security.log, empty, with permissions -rw-r-----: only you and your group can read it.
Step 5 · Test that every event is emitted
Tests are how you keep the vocabulary stable: if someone renames an event or drops a field, an analyst's saved search breaks silently, but a test fails loudly. Start with a conftest.py in the project folder. It points the log file at a temporary folder, creates the two demo users with a random password per test, and captures exactly what the JSON formatter writes:
cat > conftest.py <<'PY'
import io
import json
import logging
import os
import secrets
import tempfile
os.environ["SECURITY_LOG_FILE"] = os.path.join(tempfile.mkdtemp(), "security.log")
import pytest
from fastapi.testclient import TestClient
import app as app_module
from seclog import JsonFormatter
@pytest.fixture
def password():
return secrets.token_urlsafe(16)
@pytest.fixture
def client(password, monkeypatch):
monkeypatch.setattr(app_module, "TRUSTED_PROXIES", {"10.0.0.2"})
app_module.USERS.clear()
app_module.SESSIONS.clear()
app_module.add_user("u_1001", "ada", password, "admin")
app_module.add_user("u_1002", "tunde", password, "member")
return TestClient(app_module.app, client=("10.0.0.2", 50000))
@pytest.fixture
def log():
"""Capture what the security logger writes, exactly as it would reach the file."""
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(JsonFormatter())
logger = logging.getLogger("security")
logger.addHandler(handler)
class Captured:
def raw(self):
return stream.getvalue()
def events(self):
return [json.loads(line) for line in stream.getvalue().splitlines()]
yield Captured()
logger.removeHandler(handler)
@pytest.fixture
def sign_in(client, password):
def _sign_in(username):
response = client.post("/login", json={"username": username, "password": password})
assert response.status_code == 200
return {"Authorization": f"Bearer {response.json()['token']}"}
return _sign_in
PYThe test client connects from 10.0.0.2, which the fixture marks as a trusted proxy, so tests can send X-Forwarded-For the way Nginx would. Now the event tests:
mkdir -p tests
cat > tests/test_events.py <<'PY'
from datetime import datetime
PROXY = {"X-Forwarded-For": "203.0.113.7"}
def test_failed_login_is_logged_without_the_password(client, log):
response = client.post("/login", headers=PROXY,
json={"username": "ada", "password": "Wrong-Guess-123"})
assert response.status_code == 401
[event] = log.events()
assert event["event"] == "authn_login_fail"
assert event["outcome"] == "failure"
assert event["level"] == "WARNING"
assert event["user_id"] == "u_1001"
assert event["client_ip"] == "203.0.113.7"
assert event["request_id"] == response.headers["x-request-id"]
assert event["ts"].endswith("Z")
assert datetime.fromisoformat(event["ts"]).utcoffset().total_seconds() == 0
assert "Wrong-Guess-123" not in log.raw()
def test_unknown_username_is_not_written_down(client, log):
client.post("/login", json={"username": "my-real-password!", "password": "x"})
[event] = log.events()
assert event["user_id"] is None
assert event["details"] == {"username_known": False}
assert "my-real-password" not in log.raw()
def test_success_mfa_change_and_export(client, log, password, sign_in):
headers = sign_in("tunde")
assert client.post("/account/mfa", json={"enabled": False}, headers=headers).status_code == 200
assert client.get("/export", headers=headers).status_code == 200
names = [e["event"] for e in log.events()]
assert names == ["authn_login_success", "authn_mfa_disabled", "sensitive_read"]
export = log.events()[-1]
assert export["details"] == {"resource": "users", "record_count": 2, "format": "json"}
token = headers["Authorization"].removeprefix("Bearer ")
assert token not in log.raw()
assert password not in log.raw()
def test_permission_denied_and_admin_action(client, log, sign_in):
member = sign_in("tunde")
denied = client.post("/admin/users/u_1002/role", json={"role": "admin"}, headers=member)
assert denied.status_code == 403
admin = sign_in("ada")
changed = client.post("/admin/users/u_1002/role", json={"role": "auditor"}, headers=admin)
assert changed.status_code == 200
by_name = {e["event"]: e for e in log.events()}
assert by_name["authz_fail"]["user_id"] == "u_1002"
assert by_name["authz_fail"]["details"]["resource"] == "user:u_1002:role"
assert by_name["authz_change"]["details"] == {
"target_user_id": "u_1002", "from_role": "member", "to_role": "auditor"}
def test_request_id_is_kept_only_when_well_formed(client, log):
good = client.get("/health", headers={"X-Request-ID": "edge-7f3a9c21"})
assert good.headers["x-request-id"] == "edge-7f3a9c21"
bad = client.post("/login", headers={"X-Request-ID": "x\nforged"},
json={"username": "ada", "password": "nope"})
assert bad.headers["x-request-id"] != "x\nforged"
assert log.events()[0]["request_id"] == bad.headers["x-request-id"]
PY
uv run pytest -q tests/test_events.pyEach test asserts on the parsed JSON: event names in order, user IDs, the forwarded address, that the request ID in the log equals the one in the response, that the timestamp is UTC, and that neither the password nor the session token appears anywhere in the raw text.
Check it worked
The last line reads 5 passed. To see the tests catch a leak, add typed=body.password to the end of the LOGIN_FAIL call in app.py and run them again. typed is not on the redaction list, so two tests fail: one finds the typed password in the raw log text, the other sees an unexpected field in details. Remove it again before you continue.
Step 6 · Test redaction, injection and the proxy rules
The second test file checks seclog.py directly, with the inputs an attacker would choose:
cat > tests/test_hygiene.py <<'PY'
import pytest
from seclog import clean, client_ip, redact
def test_secrets_are_redacted_at_any_depth():
out = redact({"password": "hunter2", "nested": {"api_token": "abc"},
"headers": {"Authorization": "Bearer eyJabc.def"}, "count": 3})
assert out == {"password": "[REDACTED]", "nested": {"api_token": "[REDACTED]"},
"headers": {"Authorization": "[REDACTED]"}, "count": 3}
def test_card_numbers_and_bearer_tokens_in_text_are_masked():
text = clean("paid with 4111 1111 1111 1111 using Bearer eyJhbGciOi.x.y")
assert text == "paid with [CARD ****1111] using Bearer [REDACTED]"
def test_control_characters_cannot_forge_a_line():
forged = 'ada\n{"event":"authn_login_success","user_id":"u_1001"}'
assert "\n" not in clean(forged)
for nasty in ("\r", "\x1b[31m", "\u2028", "\u2029", "\u202e", "\x85"):
assert nasty not in clean(f"name{nasty}x")
def test_multilingual_text_survives():
for name in ("Adébáyọ̀", "Ngozi Okonkwo-Èzè", "ሰላም", "ƙasa", "می\u200cخواهم"):
assert clean(name) == name
def test_long_values_are_cut():
assert len(clean("A" * 5000)) == 200
@pytest.mark.parametrize("peer, header, expected", [
("198.51.100.20", None, "198.51.100.20"),
("198.51.100.20", "203.0.113.7", "198.51.100.20"),
("10.0.0.2", "203.0.113.7", "203.0.113.7"),
("10.0.0.2", "1.2.3.4, 203.0.113.7", "203.0.113.7"),
("10.0.0.2", "203.0.113.7, 10.0.0.3", "203.0.113.7"),
("10.0.0.2", "not-an-ip", "10.0.0.2"),
], ids=["no-proxy", "spoofed-header", "one-hop", "client-prepended-fake", "two-proxies", "garbage"])
def test_client_ip_behind_a_proxy(peer, header, expected):
assert client_ip(peer, header, {"10.0.0.2", "10.0.0.3"}) == expected
PY
uv run pytest -qThe injection test tries to smuggle a second, fake authn_login_success event in a username, and then tries carriage return, a terminal colour escape, the Unicode line and paragraph separators, a right-to-left override and the C1 "next line" character. The proxy cases cover the attacks that matter: a client that sends X-Forwarded-For directly (ignored, because it did not come through your proxy) and a client that puts a fake address at the front of the header (ignored, because the rightmost untrusted address is the one your proxy saw).
Check it worked
The last line reads 16 passed. In -v mode you can see the six proxy cases by name: no-proxy, spoofed-header, one-hop, client-prepended-fake, two-proxies and garbage.
Step 7 · Run the app and answer an analyst's questions
Install jq, the command-line JSON processor most analysts reach for:
sudo apt update
sudo apt install -y jqIn your second terminal, start the app. The read line asks for a password for the two demo users without echoing it or saving it in your shell history. TRUSTED_PROXIES=127.0.0.1 stands in for an Nginx on the same machine:
cd ~/security-log-demo
read -rsp "Demo password: " DEMO_PASSWORD; echo; export DEMO_PASSWORD
TRUSTED_PROXIES=127.0.0.1 uv run uvicorn app:app --host 127.0.0.1 --port 8000 --no-proxy-headers--no-proxy-headers matters. Uvicorn rewrites the client address from X-Forwarded-For by default when the connection comes from 127.0.0.1. Do that in one place only: either let Uvicorn do it with --forwarded-allow-ips, or turn it off and let the app's client_ip do it, as here.
Back in the first terminal, play an attacker guessing Ada's password five times from 203.0.113.7, as Nginx would report it:
cd ~/security-log-demo
for i in 1 2 3 4 5; do
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://127.0.0.1:8000/login \
-H "Content-Type: application/json" -H "X-Forwarded-For: 203.0.113.7" \
-d '{"username": "ada", "password": "wrong-guess"}'
done
tail -n 1 logs/security.logEach request prints 401. The last log line is one JSON object, something like {"ts":"2026-11-18T09:14:03.512Z","app":"notes-api","event":"authn_login_fail","outcome":"failure","level":"WARNING","user_id":"u_1001",...,"client_ip":"203.0.113.7",...,"details":{"username_known":true}}. wrong-guess appears nowhere in the file.
Now ask the questions an analyst asks. Which addresses are failing to sign in, and how often? Which warnings happened, in short form? Which addresses crossed a threshold of five failures?
jq -r 'select(.event == "authn_login_fail") | .client_ip' logs/security.log | sort | uniq -c | sort -rn
jq -c 'select(.level == "WARNING") | {ts, event, user_id, client_ip}' logs/security.log | tail -n 2
jq -s 'map(select(.event == "authn_login_fail")) | group_by(.client_ip) | map({ip: .[0].client_ip, fails: length}) | map(select(.fails >= 5))' logs/security.logCheck it worked
The first command prints 5 203.0.113.7. The second prints two short objects with authn_login_fail and u_1001. The third prints a list with one entry, {"ip": "203.0.113.7", "fails": 5}. That last query is the shape of a real detection rule; detect suspicious logins in the auth log builds more of them.
On slow or prepaid connections, a central log service that receives every line as it happens can cost real money in data. One JSON line per event is compact, and you can ship only WARNING and above in real time and batch the rest.
Step 8 · Set a retention period with logrotate
Security logs need to be kept long enough to investigate an incident found weeks later, and deleted when that purpose is done. Ninety days is a common starting point; write down your own reason for the number you choose, because a data protection review will ask. Logrotate, installed on Ubuntu by default, renames the file daily, compresses old copies and deletes anything past the limit.
The heredoc below fills in your home folder, user and group as it writes the file:
sudo tee /etc/logrotate.d/security-log-demo > /dev/null <<EOF
$HOME/security-log-demo/logs/security.log {
su $(id -un) $(id -gn)
daily
rotate 90
maxage 90
dateext
compress
delaycompress
missingok
notifempty
create 0640 $(id -un) $(id -gn)
}
EOF
sudo logrotate --debug /etc/logrotate.d/security-log-demo--debug only reports what logrotate would do. su makes it act as you, since the folder is yours. create 0640 keeps the new file as private as the first one. There is no copytruncate: the app's WatchedFileHandler notices the move and opens a fresh file.
Force one rotation now to prove the app keeps logging into the new file, then make one more failed sign-in:
sudo logrotate --force /etc/logrotate.d/security-log-demo
curl -s -o /dev/null -X POST http://127.0.0.1:8000/login \
-H "Content-Type: application/json" -d '{"username": "tunde", "password": "nope"}'
ls -l logs
wc -l logs/security.log logs/security.log-*Check it worked
The --debug run prints something like rotating pattern: ... after 1 days (90 rotations) and log does not need rotating. After the forced rotation, logs holds security.log and a dated copy such as security.log-20261118. wc shows 1 line in the new security.log (Tunde's failure) and 5 in the dated copy. Logrotate runs daily from Ubuntu's logrotate.timer, so from now on old copies are compressed the next day and deleted after 90 days.
A log file on the same server as the app is the first thing an intruder edits. In production, also send these lines somewhere the app server cannot change, such as the systemd journal forwarded to a central host, which search the systemd journal with journalctl covers, and keep the server's clock synchronised so UTC timestamps from different machines line up.
Step 9 · Clean up
Stop the app with Ctrl+C in the second terminal. Then remove the logrotate rule and the demo project:
sudo rm /etc/logrotate.d/security-log-demo
cd ~
rm -rf ~/security-log-demoCheck it worked
ls /etc/logrotate.d/security-log-demo ~/security-log-demo reports No such file or directory for both.
Next steps
- Turn these events into alerts: detect suspicious logins in the auth log.
- Make the events the app logs harder to trigger in the first place: defend sign-in against credential stuffing.
- Keep the rest of your app logging tidy: log properly in Python with the logging module.
- Test the rest of a FastAPI app the same way: test a FastAPI app with pytest and dependency overrides.
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials