DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Audit Logging Best Practices

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Audit Logging Best Practices

Introduction

Audit logs are the authoritative record of who did what, when, and where in a system. They are essential for incident investigation, compliance reporting, and operational troubleshooting. A robust audit logging architecture ensures logs are complete, tamper-evident, and readily accessible when needed — often months or years after the event.

Immutable Logs

Log immutability prevents attackers or insiders from covering their tracks by modifying or deleting log entries.

Write-Once, Read-Many (WORM) Storage

import hashlib

import hmac

import json

from datetime import datetime

class ImmutableAuditLogger:

def init(self, storage_backend, hmac_key):

self.storage = storage_backend

self.hmac_key = hmac_key.encode()

def write_log(self, event):

"""Write a tamper-evident log entry."""

Create log entry with metadata

entry = {

'timestamp': datetime.utcnow().isoformat(),

'event': event,

'sequence': self._next_sequence(),

}

Add hash of previous entry (blockchain-style chain)

prev_entry = self.storage.get_last()

if prev_entry:

entry['prev_hash'] = prev_entry['hash']

else:

entry['prev_hash'] = '0' * 64

Calculate hash of this entry

entry_json = json.dumps(entry, sort_keys=True)

entry_hash = hashlib.sha256(entry_json.encode()).hexdigest()

entry['hash'] = entry_hash

HMAC sign the hash

entry['signature'] = hmac.new(

self.hmac_key,

entry_hash.encode(),

hashlib.sha256

).hexdigest()

Write to WORM storage

log_id = f"{entry['timestamp']}_{entry['sequence']}"

self.storage.write(log_id, entry)

return entry


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)