implementing-database-audit-logging
БесплатноЗапускает вложенные скриптыНе проверенProcess use when you need to track database changes for compliance and security monitoring. This skill implements audit logging using triggers…
от jeremylongshore★ 2 961 звезда на GitHubОб этом скилле
Database Audit Logger
Overview
Implement database audit logging to track all data modifications (INSERT, UPDATE, DELETE) with full before/after values, user identity, timestamps, and application context. This skill supports trigger-based auditing for PostgreSQL and MySQL, change data capture (CDC) patterns, and application-level audit logging.
Prerequisites
- Database credentials with CREATE TABLE, CREATE FUNCTION, and CREATE TRIGGER permissions
psqlormysqlCLI for executing audit setup DDL- Understanding of applicable compliance requirements (which tables, which operations, retention period)
- Estimated storage for audit logs: plan for 10-30% of the audited table's data volume per year
- Separate tablespace or storage volume for audit data to prevent audit growth from affecting application performance
Instructions
Identify tables requiring audit logging based on compliance and business needs:
- Tables containing PII (users, contacts, addresses) -- GDPR/HIPAA requirement
- Tables containing financial data (transactions, payments, invoices) -- SOX/PCI-DSS requirement
- Tables containing access control data (roles, permissions, API keys) -- security requirement
- Determine which operations to audit per table: INSERT, UPDATE, DELETE, or all three
Create the audit log table with comprehensive metadata:
CREATE TABLE audit_log ( id BIGSERIAL PRIMARY KEY, table_name VARCHAR(100) NOT NULL, record_id TEXT NOT NULL, action VARCHAR(10) NOT NULL CHECK (action IN ('INSERT', 'UPDATE', 'DELETE')), old_values JSONB, new_values JSONB, changed_columns TEXT[], changed_by VARCHAR(100), changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), client_ip INET, application_name VARCHAR(100), transaction_id BIGINT );Add indexes for common audit queries:
CREATE INDEX idx_audit_table_record ON audit_log (table_name, record_id)CREATE INDEX idx_audit_changed_at ON audit_log (changed_at)CREATE INDEX idx_audit_changed_by ON audit_log (changed_by)CREATE INDEX idx_audit_action ON audit_log (table_name, action)
Create the PostgreSQL audit trigger function:
CREATE OR REPLACE FUNCTION audit_trigger_func() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'INSERT' THEN INSERT INTO audit_log (table_name, record_id, action, new_values, changed_by, client_ip, application_name, transaction_id) VALUES (TG_TABLE_NAME, NEW.id::text, 'INSERT', to_jsonb(NEW), current_setting('app.user', true), inet_client_addr(), current_setting('application_name'), txid_current()); ELSIF TG_OP = 'UPDATE' THEN INSERT INTO audit_log (table_name, record_id, action, old_values, new_values, changed_by, client_ip, application_name, transaction_id) VALUES (TG_TABLE_NAME, NEW.id::text, 'UPDATE', to_jsonb(OLD), to_jsonb(NEW), current_setting('app.user', true), inet_client_addr(), current_setting('application_name'), txid_current()); ELSIF TG_OP = 'DELETE' THEN INSERT INTO audit_log (table_name, record_id, action, old_values, changed_by, client_ip, application_name, transaction_id) VALUES (TG_TABLE_NAME, OLD.id::text, 'DELETE', to_jsonb(OLD), current_setting('app.user', true), inet_client_addr(), current_setting('application_name'), txid_current()); END IF; RETURN COALESCE(NEW, OLD); END; $$ LANGUAGE plpgsql;Attach triggers to each audited table:
CREATE TRIGGER audit_users AFTER INSERT OR UPDATE OR DELETE ON users FOR EACH ROW EXECUTE FUNCTION audit_trigger_func()- Repeat for each table requiring audit logging
Pass application-level user context to the database session so audit logs capture the actual application user (not just the database role):
- At the start of each request:
SET LOCAL app.user = '[email protected]' - For connection pools, set in the connection checkout hook
- This value is captured by
current_setting('app.user', true)in the trigger
- At the start of each request:
Partition the audit_log table by month for efficient querying and archival:
CREATE TABLE audit_log (...) PARTITION BY RANGE (changed_at)- Create monthly partitions:
CREATE TABLE audit_log_2024_01 PARTITION OF audit_log FOR VALUES FROM ('2024-01-01') TO ('2024-02-01') - Automate partition creation for future months
Protect audit log integrity:
- Revoke UPDATE and DELETE permissions on audit_log from all application users
- Grant only INSERT permission to the trigger execution context
- Consider using
pg_auditextension for additional tamper protection - Ship audit logs to an external system (SIEM, S3) for independent retention
Create compliance report queries:
- Change history for a record:
SELECT * FROM audit_log WHERE table_name = 'users' AND record_id = '12345' ORDER BY changed_at - All changes by a user:
SELECT * FROM audit_log WHERE changed_by = '[email protected]' ORDER BY changed_at DESC
- Change history for a record:
Установить implementing-database-audit-logging в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditGrepGlobBash(psql:*)Bash(mysql:*)Вложенные файлы
FAQ
Что делает скилл implementing-database-audit-logging?
Process use when you need to track database changes for compliance and security monitoring. This skill implements audit logging using triggers, application-level logging, CDC, or native logs. Trigger with phrases like "implement database audit logging", "add audit trails", "track database changes", or "monitor database activity for compliance".
Как установить скилл implementing-database-audit-logging?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл implementing-database-audit-logging запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
ci-review
The scan that the plugin's GitHub Action runs.
от Anthropicazure-static-web-apps
Helps create, configure, and deploy Azure Static Web Apps using the SWA CLI. Use when deploying static sites to Azure, setting up SWA local development…
от GitHubai-ready
Make any repo AI-ready — analyzes your codebase and generates AGENTS.md, copilot-instructions.md, CI workflows, issue templates, and more. Mines your PR…
от GitHubaws-cdk-python-setup
Setup and initialization guide for developing AWS CDK (Cloud Development Kit) applications in Python. This skill enables users to configure environment…
от GitHub