Audit Logging
Skill Profile
(Select at least one profile to enable specific modules)
Overview
Audit logging is a critical security and compliance practice that records system events, user actions, and data access patterns. This skill provides comprehensive patterns for implementing audit logging systems that meet various compliance frameworks including GDPR, HIPAA, PCI DSS, SOX, and ISO 27001.
Why This Matters
Audit logging is essential for:
- Compliance: Meeting regulatory requirements for data protection and security
- Security: Detecting and investigating security incidents
- Accountability: Tracking who did what, when, and how
- Forensics: Providing evidence for investigations
- Risk Management: Identifying patterns of suspicious activity
Core Concepts & Rules
1. Core Principles
- Follow established patterns and conventions
- Maintain consistency across codebase
- Document decisions and trade-offs
2. Implementation Guidelines
- Start with the simplest viable solution
- Iterate based on feedback and requirements
- Test thoroughly before deployment
Inputs / Outputs / Contracts
- Inputs:
- <e.g., env vars, request payload, file paths, schema>
- Entry Conditions:
- <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
- Outputs:
- <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
- Artifacts Required (Deliverables):
- <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
- Acceptance Evidence:
- <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
- Success Criteria:
- <e.g., p95 < 300ms, coverage ≥ 80%>
Skill Composition
- Depends on: None
- Compatible with: None
- Conflicts with: None
- Related Skills: None
Quick Start / Implementation Example
- Review requirements and constraints
- Set up development environment
- Implement core functionality following patterns
- Write tests for critical paths
- Run tests and fix issues
- Document any deviations or decisions
# Example implementation following best practices
def example_function():
# Your implementation here
pass
Assumptions
- System has access to persistent storage for logs
- Time synchronization is available across services
- User identification is available for logged events
Compatibility
- PostgreSQL 12+
- Node.js 14+
- Elasticsearch 7+ (for log aggregation)
- Any web framework (Express, Fastify, etc.)
Test Scenario Matrix
| Scenario |
Input |
Expected Output |
Priority |
| Log authentication event |
User login data |
Audit log entry created |
P0 |
| Query audit trail |
User ID, date range |
All events for user |
P0 |
| Export logs |
Query, format |
JSON/CSV export |
P1 |
| Check compliance |
Framework name |
Compliance report |
P0 |
| Apply retention |
Days threshold |
Old logs archived |
P1 |
| Verify immutability |
Log chain |
Integrity verified |
P0 |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives & Error Recovery
(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)
- Thinking Process: Analyze root cause before fixing. Do not brute-force.
- Fallback Strategy: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
- Self-Review: Check against Guardrails & Anti-patterns before finalizing.
- Output Constraints: Output ONLY the modified code block. Do not explain unless asked.
Definition of Done (DoD) Checklist
Anti-patterns
- Logging Everything: Only log what's required for compliance
- Synchronous Logging: Use async logging to avoid performance impact
- Storing PII in Logs: Mask or hash sensitive data
- No Retention Policy: Implement automated retention
- Ignoring Failed Logs: Monitor and alert on failures
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure
1---2name: audit-logging-33description: Audit logging is a critical security and compliance practice that records system events, user actions, and data access patterns. This skill provides comprehensive patterns for implementing audit loggi4---5
6# Audit Logging
7
8## Skill Profile
9*(Select at least one profile to enable specific modules)*
10- [ ] **DevOps**
11- [x] **Backend**
12- [ ] **Frontend**
13- [ ] **AI-RAG**
14- [ ] **Security Critical**
15
16## Overview
17Audit logging is a critical security and compliance practice that records system events, user actions, and data access patterns. This skill provides comprehensive patterns for implementing audit logging systems that meet various compliance frameworks including GDPR, HIPAA, PCI DSS, SOX, and ISO 27001.
18
19## Why This Matters
20Audit logging is essential for:
21- **Compliance**: Meeting regulatory requirements for data protection and security
22- **Security**: Detecting and investigating security incidents
23- **Accountability**: Tracking who did what, when, and how
24- **Forensics**: Providing evidence for investigations
25- **Risk Management**: Identifying patterns of suspicious activity
26
27---
28
29## Core Concepts & Rules
30
31### 1. Core Principles
32- Follow established patterns and conventions
33- Maintain consistency across codebase
34- Document decisions and trade-offs
35
36### 2. Implementation Guidelines
37- Start with the simplest viable solution
38- Iterate based on feedback and requirements
39- Test thoroughly before deployment
40
41
42## Inputs / Outputs / Contracts
43* **Inputs**:
44 - <e.g., env vars, request payload, file paths, schema>
45* **Entry Conditions**:
46 - <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
47* **Outputs**:
48 - <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
49* **Artifacts Required (Deliverables)**:
50 - <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
51* **Acceptance Evidence**:
52 - <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
53* **Success Criteria**:
54 - <e.g., p95 < 300ms, coverage ≥ 80%>
55
56## Skill Composition
57* **Depends on**: None
58* **Compatible with**: None
59* **Conflicts with**: None
60* **Related Skills**: None
61
62## Quick Start / Implementation Example
63
641. Review requirements and constraints
652. Set up development environment
663. Implement core functionality following patterns
674. Write tests for critical paths
685. Run tests and fix issues
696. Document any deviations or decisions
70
71```python
72# Example implementation following best practices
73def example_function():
74 # Your implementation here
75 pass
76```
77
78
79## Assumptions
80- System has access to persistent storage for logs
81- Time synchronization is available across services
82- User identification is available for logged events
83
84## Compatibility
85- PostgreSQL 12+
86- Node.js 14+
87- Elasticsearch 7+ (for log aggregation)
88- Any web framework (Express, Fastify, etc.)
89
90---
91
92## Test Scenario Matrix
93| Scenario | Input | Expected Output | Priority |
94|----------|-------|-----------------|----------|
95| Log authentication event | User login data | Audit log entry created | P0 |
96| Query audit trail | User ID, date range | All events for user | P0 |
97| Export logs | Query, format | JSON/CSV export | P1 |
98| Check compliance | Framework name | Compliance report | P0 |
99| Apply retention | Days threshold | Old logs archived | P1 |
100| Verify immutability | Log chain | Integrity verified | P0 |
101
102---
103
104## Technical Guardrails & Security Threat Model
105
106### 1. Security & Privacy (Threat Model)
107* **Top Threats**: Injection attacks, authentication bypass, data exposure
108- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII
109- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager
110- [ ] **Authorization**: Validate user permissions before state changes
111
112### 2. Performance & Resources
113- [ ] **Execution Efficiency**: Consider time complexity for algorithms
114- [ ] **Memory Management**: Use streams/pagination for large data
115- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks
116
117### 3. Architecture & Scalability
118- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection
119- [ ] **Modularity**: Decouple logic from UI/Frameworks
120
121### 4. Observability & Reliability
122- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`
123- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`
124- [ ] **Error Handling**: Standardized error codes, no bare except
125- [ ] **Observability Artifacts**:
126 - **Log Fields**: timestamp, level, message, request_id
127 - **Metrics**: request_count, error_count, response_time
128 - **Dashboards/Alerts**: High Error Rate > 5%
129
130
131## Agent Directives & Error Recovery
132*(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)*
133
134- **Thinking Process**: Analyze root cause before fixing. Do not brute-force.
135- **Fallback Strategy**: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
136- **Self-Review**: Check against Guardrails & Anti-patterns before finalizing.
137- **Output Constraints**: Output ONLY the modified code block. Do not explain unless asked.
138
139
140## Definition of Done (DoD) Checklist
141
142- [ ] Tests passed + coverage met
143- [ ] Lint/Typecheck passed
144- [ ] Logging/Metrics/Trace implemented
145- [ ] Security checks passed
146- [ ] Documentation/Changelog updated
147- [ ] Accessibility/Performance requirements met (if frontend)
148
149
150## Anti-patterns
151- **Logging Everything**: Only log what's required for compliance
152- **Synchronous Logging**: Use async logging to avoid performance impact
153- **Storing PII in Logs**: Mask or hash sensitive data
154- **No Retention Policy**: Implement automated retention
155- **Ignoring Failed Logs**: Monitor and alert on failures
156
157## Reference Links & Examples
158
159* Internal documentation and examples
160* Official documentation and best practices
161* Community resources and discussions
162
163
164## Versioning & Changelog
165
166* **Version**: 1.0.0
167* **Changelog**:
168 - 2026-02-22: Initial version with complete template structure
169