
6. API Audit Logging Best Practices
Essential Elements for API Audit Logs
Request Identification
- Request ID (unique identifier)
- Correlation ID (for distributed tracing)
- Session ID
Authentication/Authorization
- User ID or service account
- Authentication method (JWT, OAuth, API key)
- Scopes/permissions used
Request Details
- HTTP method (GET, POST, PUT, DELETE)
- Endpoint/route
- Request parameters
- Request body (sanitized of sensitive data)
Response Details
- Status code
- Response time
- Error messages (if applicable)
Context
- IP address
- User agent
- Geolocation
- Timestamp (with timezone)
API Audit Log Schema
CREATE TABLE api_audit_logs (
id BIGSERIAL PRIMARY KEY,
-- Request identification
request_id UUID NOT NULL UNIQUE,
correlation_id UUID,
session_id VARCHAR(100),
-- Authentication
user_id VARCHAR(100),
service_account VARCHAR(100),
auth_method VARCHAR(50),
-- Request details
http_method VARCHAR(10) NOT NULL,
endpoint TEXT NOT NULL,
route_pattern VARCHAR(200), -- e.g., "/api/v1/orders/:id"
query_params JSONB,
request_body JSONB,
request_headers JSONB,
-- Response details
status_code INT NOT NULL,
response_time_ms INT,
response_body JSONB,
error_message TEXT,
-- Context
ip_address INET,
user_agent TEXT,
geo_location JSONB,
-- Timing
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Additional metadata
metadata JSONB
);
-- Indexes for common query patterns
CREATE INDEX idx_api_audit_user ON api_audit_logs(user_id, created_at DESC);
CREATE INDEX idx_api_audit_endpoint ON api_audit_logs(route_pattern, created_at DESC);
CREATE INDEX idx_api_audit_status ON api_audit_logs(status_code, created_at DESC);
CREATE INDEX idx_api_audit_created ON api_audit_logs(created_at DESC);
CREATE INDEX idx_api_audit_correlation ON api_audit_logs(correlation_id);
-- GIN index for JSONB queries
CREATE INDEX idx_api_audit_metadata ON api_audit_logs USING GIN(metadata);API Audit Logging Best Practices
Log Asynchronously
- Don't block API responses
- Use queues (RabbitMQ, Kafka)
- Buffer and batch writes
Sanitize Sensitive Data
- Never log passwords, tokens, credit cards
- Mask or redact PII
- Use allowlist for safe fields
Structured Logging
- Use JSON format
- Consistent field names
- Enable easy parsing/analysis
Implement Log Rotation
- Archive old logs
- Partition tables by date
- Set retention policies
Monitor and Alert
- Set up alerts for anomalies
- Track error rates
- Monitor unusual access patterns
Compliance Considerations
- GDPR: Support right to erasure
- HIPAA: Encrypt at rest and in transit
- SOC 2: Tamper-proof logs
What the API Audit Table Captures
The current API writes audit entries for content operations and selected media operations. Its audit model stores actor, action, target, and the base timestamps. A content operation uses values such as edit or approve for the action and the content entry ID for the target.
This table is an administrative change history, not a record of every HTTP request. It does not store request bodies, route patterns, response codes, session IDs, or client IP addresses. Keeping those concerns separate helps avoid treating a state-change audit trail as a general traffic log. If request-level security monitoring is required, define that contract separately and decide which fields can be retained safely.
For request-scoped database work, GORM supports passing a Go context through WithContext; callbacks can read the context from tx.Statement.Context. The current audit writer receives actor, action, and target explicitly, so adding request metadata would be a separate design change.
References: GORM context, Go cancellation for database operations.
Expanded from the supplied audit-log article
Append-only does not mean "keep everything forever"
The usual rule is simple: an audit event must not be silently edited after it has been recorded. If an earlier event was wrong, add a correction event that explains the mistake rather than rewriting history.
But there is an important difference between these ideas:
- Append-only: Normal application operations insert new records and do not update old ones.
- Tamper-resistant: Permissions and other controls make unauthorized alteration harder or detectable.
- Permanent retention: Data is kept forever, which is often neither necessary nor appropriate.
An audit_logs table is not magically immutable because we call it append-only. A database administrator with sufficient privileges may still change or delete records. Serious audit systems need restricted database roles, monitoring, backups, and sometimes an independent immutable archive or integrity checks.
Retention also matters. Personal information in audit logs may be subject to deletion or retention obligations. Define a retention period based on actual business and legal requirements. Document how records are archived and safely deleted at the end of that period.
Make audit records useful for investigation
Audit logging is not complete when data is inserted. Someone must be able to find the right records and understand the sequence.
For example, to inspect all changes to article 17:
SELECT
occurred_at,
actor_id,
action,
target_type,
target_id,
request_id
FROM audit_logs
WHERE target_type = 'content_entry'
AND target_id = '17'
ORDER BY occurred_at DESC, id DESC
LIMIT 100;The extra id in the sort makes the order stable when multiple events share the same timestamp. Use pagination for long histories and restrict who can query the audit table.

A usable audit system combines data design with controls and operational procedures.
A practical protection checklist includes:
- Grant normal application roles
INSERTaccess to audit rows only where needed. KeepUPDATEandDELETEout of regular request paths. - Restrict audit reads, because actor IDs and request context may be sensitive.
- Monitor failures and alert when critical audit writes unexpectedly stop.
- Back up audit data and test restoration.
- Consider independent archiving or integrity verification if the threat model includes privileged tampering.
- Document retention, access review, and deletion procedures.
These controls support trustworthy records, but they do not make every event impossible to falsify. The correct assurance level depends on the system's threat model.
Further reading
Originally published on DEV Community.


