TL;DR
Audit logs record who did what, when, and to which resources in your application. They are essential for security incident investigation, debugging, and meeting compliance requirements like SOC 2, HIPAA, and PCI-DSS. Log user actions, authentication events, and data changes. Store logs securely where they cannot be modified.
The Simple Explanation
Every time something important happens in your app, you write it down. User logged in? Log it. User deleted a record? Log it. Admin changed permissions? Log it. When something goes wrong or you need to prove compliance, you can look back and see exactly what happened.
What to Log
- Authentication: Logins, logouts, failed attempts
- Authorization: Permission changes, access denials
- Data changes: Create, update, delete operations
- Admin actions: Configuration changes, user management
- Security events: Password resets, 2FA changes
- API access: External integrations, API key usage
Log Entry Structure
{ "timestamp": "2026-01-15T14:32:00Z", "event": "user.role.updated", "actor": { "userId": "user_abc123", "email": "admin@example.com", "ip": "192.0.2.1" }, "target": { "userId": "user_xyz789", "type": "user" }, "changes": { "role": { "from": "member", "to": "admin" } }, "outcome": "success" }
What Not to Log
- Passwords or password hashes
- Full credit card numbers
- API keys or secrets
- Personal data beyond what is needed
Log security matters. If attackers compromise your logs, they can cover their tracks or extract sensitive data. Protect logs with proper access controls and consider using a separate logging service.
What should I include in audit logs?
Log who (user ID, IP address), what (action taken), when (timestamp), where (resource affected), and outcome (success/failure). For sensitive operations, log before and after values. Include enough context to reconstruct what happened without logging sensitive data like passwords.
How long should I keep audit logs?
Retention depends on compliance requirements. PCI-DSS requires one year with three months immediately available. HIPAA requires six years. SOC 2 typically expects one year. Check your specific compliance needs and set retention policies accordingly.
How do I protect audit logs from tampering?
Store logs in append-only storage or a separate system. Use write-once storage or log aggregation services. Implement access controls so only specific roles can read logs and no one can modify them. Consider cryptographic signing for critical logs.