implementing-database-audit-logging
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".
- License 许可
- MIT
- 最近更新
- 2025-12-18
- Stars
- ★ 29
- Forks
- 9
01 前言 Front Matter
- name
- implementing-database-audit-logging
- license
- MIT
- version
- 1.0.0
- description
- 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".
- allowed-tools
- [ "Read", "Write", "Edit", "Grep", "Glob", "Bash(psql:*, mysql:*)" ]
02 资源文件 6
- 资产文件assets/README.md361 B
- 参考文档references/README.md751 B
- 脚本scripts/audit_log_analyzer.py4.7 KB
- 脚本scripts/audit_log_generator.py4.7 KB
- 脚本scripts/audit_table_creator.sh4.8 KB
- 脚本scripts/README.md477 B
03 SKILL.md 正文
Prerequisites
Before using this skill, ensure:
- Database credentials with CREATE TABLE and CREATE TRIGGER permissions
- Understanding of compliance requirements (GDPR, HIPAA, SOX, PCI-DSS)
- Sufficient storage for audit logs (estimate 10-30% of data size)
- Decision on audit log retention period
- Access to database documentation for table schemas
- Monitoring tools configured for audit log analysis
Instructions
Step 1: Define Audit Requirements
- Identify tables requiring audit logging based on compliance needs
- Determine events to audit (INSERT, UPDATE, DELETE, SELECT for sensitive data)
- Define which columns contain sensitive data requiring audit
- Document retention requirements for audit logs
- Identify users/roles whose actions need auditing
Step 2: Choose Audit Strategy
- Trigger-Based Auditing: Best for comprehensive row-level tracking
- Pros: Automatic, no application changes, captures all changes
- Cons: Performance overhead, complex trigger maintenance
- Application-Level Auditing: Best for selective auditing
- Pros: Flexible, lower database overhead, easier debugging
- Cons: Requires application changes, can miss direct database changes
- Change Data Capture (CDC): Best for real-time streaming
- Pros: Minimal performance impact, real-time analysis, external processing
- Cons: Complex setup, requires CDC infrastructure
- Native Database Logs: Best for general monitoring
- Pros: No setup, captures everything, built-in
- Cons: High volume, limited retention, difficult to query
Step 3: Design Audit Table Schema
- Create audit log table with these core columns:
- audit_id (primary key), table_name, action (INSERT/UPDATE/DELETE)
- record_id (reference to audited record), old_values (JSON), new_values (JSON)
- changed_by (user), changed_at (timestamp), client_ip, application_context
- Add indexes on table_name, changed_at, changed_by for query performance
- Partition audit table by date for efficient archival
- Configure tablespace for audit logs separate from primary data
Step 4: Implement Audit Mechanism
- For trigger-based: Create AFTER INSERT/UPDATE/DELETE triggers on each table
- Capture old and new row values as JSON in trigger body
- Record user context (CURRENT_USER, application user, IP address)
- Handle trigger failures gracefully (log but don't block operations)
- Test triggers with sample data modifications
Step 5: Configure Audit Log Management
- Set up automated archival of old audit logs to cold storage
- Implement audit log analysis queries for common compliance reports
- Create alerts for suspicious activities (bulk deletes, off-hours changes)
- Document audit log query procedures for compliance auditors
- Schedule periodic audit log reviews with security team
Step 6: Validate Audit Implementation
- Perform test operations on audited tables
- Verify audit log entries are created with complete data
- Test audit log queries for performance
- Confirm audit logs cannot be modified by regular users
- Document audit implementation for compliance documentation
Output
This skill produces:
Audit Table Schema: SQL DDL for audit log table with proper indexes and partitioning
Audit Triggers: Database triggers for automatic audit log population on data changes
Audit Log Queries: Pre-built SQL queries for compliance reports and change tracking
Implementation Documentation: Configuration details, trigger logic, and maintenance procedures
Compliance Report Templates: SQL queries for GDPR access logs, SOX change reports, etc.
Error Handling
Trigger Performance Issues:
- Audit only critical tables, not all tables
- Use asynchronous audit logging with queue systems
- Batch audit log inserts instead of individual inserts
- Monitor trigger execution time and optimize trigger logic
Audit Table Growth:
- Implement automated archival of audit logs older than retention period
- Partition audit table by month or quarter
- Compress old audit log partitions
- Move historical audit logs to cheaper storage tiers
Missing Audit Context:
- Set application context in database session before operations
- Use database session variables to pass user identity
- Implement connection pooling with session initialization
- Log application user separately from database user
Permission Issues:
- Ensure audit log table is writable by trigger execution context
- Grant INSERT on audit table to all database users
- Protect audit table from modifications (no UPDATE/DELETE grants)
- Use separate schema for audit tables with restricted access
Resources
Audit Table Templates:
- PostgreSQL audit trigger:
{baseDir}/templates/postgresql-audit-trigger.sql - MySQL audit trigger:
{baseDir}/templates/mysql-audit-trigger.sql - Audit table schema:
{baseDir}/templates/audit-table-schema.sql
Compliance Report Queries: {baseDir}/queries/compliance-reports/
- GDPR data access report
- SOX change audit report
- User activity summary
- Suspicious activity detection
Audit Strategy Guide: {baseDir}/docs/audit-strategy-selection.md
Performance Tuning: {baseDir}/docs/audit-performance-optimization.md
Archival Procedures: {baseDir}/scripts/audit-archival.sh
04 同仓库更多 Skills
testing-visual-regression
Detect visual changes in UI components using screenshot comparison. Use when detecting unintended UI changes or pixel differences. Trigger with phrases like "test visual changes", "compare screenshots", or "detect UI regressions".
generating-unit-tests
Automatically generate comprehensive unit tests from source code covering happy paths, edge cases, and error conditions. Use when creating test coverage for functions, classes, or modules. Trigger with phrases like "generate unit tests", "create tests for", or "add test coverage".
generating-test-reports
Generate comprehensive test reports with metrics, coverage, and visualizations. Use when performing specialized testing. Trigger with phrases like "generate test report", "create test documentation", or "show test metrics".
orchestrating-test-execution
Coordinate parallel test execution across multiple environments and frameworks. Use when performing specialized testing. Trigger with phrases like "orchestrate tests", "run parallel tests", or "coordinate test execution".
managing-test-environments
Provision and manage isolated test environments with configuration and data. Use when performing specialized testing. Trigger with phrases like "manage test environment", "provision test env", or "setup test infrastructure".
generating-test-doubles
Generate mocks, stubs, spies, and fakes for dependency isolation. Use when creating mocks, stubs, or test isolation fixtures. Trigger with phrases like "generate mocks", "create test doubles", or "setup stubs".