Code Examples

Copy-paste examples for common audit logging scenarios. All examples work with both Python and JavaScript SDKs.

Authentication Events

Log user authentication activities:

Python
1# Successful login
2client.log(
3 action="user.login",
4 actor_id=user.id,
5 metadata={
6 "ip_address": request.ip,
7 "user_agent": request.headers.get("User-Agent"),
8 "method": "password" # or "sso", "magic_link", etc.
9 }
10)
11
12# Failed login attempt
13client.log(
14 action="user.login_failed",
15 actor_id=email, # Use email since user might not exist
16 metadata={
17 "ip_address": request.ip,
18 "reason": "invalid_password" # or "user_not_found", "account_locked"
19 }
20)
21
22# Logout
23client.log(
24 action="user.logout",
25 actor_id=user.id,
26 metadata={
27 "session_duration": session.duration_seconds
28 }
29)
30
31# Password change
32client.log(
33 action="user.password_changed",
34 actor_id=user.id,
35 metadata={
36 "ip_address": request.ip,
37 "triggered_by": "user" # or "admin", "forgot_password"
38 }
39)

Resource CRUD Operations

Log create, read, update, delete operations:

Python
1# Document created
2client.log(
3 action="document.created",
4 actor_id=user.id,
5 target_id=document.id,
6 target_type="document",
7 metadata={
8 "title": document.title,
9 "size_bytes": document.size,
10 "mime_type": document.mime_type
11 }
12)
13
14# Document viewed
15client.log(
16 action="document.viewed",
17 actor_id=user.id,
18 target_id=document.id,
19 target_type="document",
20 metadata={
21 "duration_seconds": view_duration
22 }
23)
24
25# Document updated
26client.log(
27 action="document.updated",
28 actor_id=user.id,
29 target_id=document.id,
30 target_type="document",
31 metadata={
32 "changes": ["title", "content"], # Fields that changed
33 "previous_version": document.version - 1
34 }
35)
36
37# Document deleted
38client.log(
39 action="document.deleted",
40 actor_id=user.id,
41 target_id=document.id,
42 target_type="document",
43 metadata={
44 "title": document.title,
45 "deleted_permanently": False # or True for hard delete
46 }
47)

Payment Events

Log payment and subscription activities:

Python
1# Payment processed
2client.log(
3 action="payment.processed",
4 actor_id=user.id,
5 target_id=payment.id,
6 target_type="payment",
7 metadata={
8 "amount": payment.amount,
9 "currency": payment.currency,
10 "payment_method": "card", # Don't log card details!
11 "invoice_id": payment.invoice_id
12 }
13)
14
15# Payment failed
16client.log(
17 action="payment.failed",
18 actor_id=user.id,
19 target_id=payment.id,
20 target_type="payment",
21 metadata={
22 "amount": payment.amount,
23 "currency": payment.currency,
24 "failure_reason": "insufficient_funds"
25 }
26)
27
28# Subscription created
29client.log(
30 action="subscription.created",
31 actor_id=user.id,
32 target_id=subscription.id,
33 target_type="subscription",
34 metadata={
35 "plan": subscription.plan_name,
36 "billing_cycle": "monthly",
37 "trial_days": 14
38 }
39)
40
41# Subscription cancelled
42client.log(
43 action="subscription.cancelled",
44 actor_id=user.id,
45 target_id=subscription.id,
46 target_type="subscription",
47 metadata={
48 "reason": "too_expensive", # User-provided reason
49 "effective_date": subscription.end_date.isoformat()
50 }
51)

Admin Actions

Log administrative activities:

Python
1# User invited
2client.log(
3 action="admin.user_invited",
4 actor_id=admin.id,
5 actor_type="admin",
6 target_id=invited_email,
7 target_type="user",
8 metadata={
9 "role": "member",
10 "team": team.name
11 }
12)
13
14# User role changed
15client.log(
16 action="admin.role_changed",
17 actor_id=admin.id,
18 actor_type="admin",
19 target_id=user.id,
20 target_type="user",
21 metadata={
22 "previous_role": "member",
23 "new_role": "admin"
24 }
25)
26
27# User removed
28client.log(
29 action="admin.user_removed",
30 actor_id=admin.id,
31 actor_type="admin",
32 target_id=user.id,
33 target_type="user",
34 metadata={
35 "reason": "offboarding"
36 }
37)
38
39# Settings changed
40client.log(
41 action="admin.settings_changed",
42 actor_id=admin.id,
43 actor_type="admin",
44 metadata={
45 "setting": "two_factor_required",
46 "previous_value": False,
47 "new_value": True
48 }
49)

API Key Management

Log API key lifecycle events:

Python
1# API key created
2client.log(
3 action="api_key.created",
4 actor_id=user.id,
5 target_id=api_key.id,
6 target_type="api_key",
7 metadata={
8 "name": api_key.name,
9 "scopes": api_key.scopes,
10 "expires_at": api_key.expires_at.isoformat() if api_key.expires_at else None
11 }
12)
13
14# API key used
15client.log(
16 action="api_key.used",
17 actor_id=api_key.id,
18 actor_type="api_key",
19 metadata={
20 "endpoint": request.path,
21 "ip_address": request.ip
22 }
23)
24
25# API key rotated
26client.log(
27 action="api_key.rotated",
28 actor_id=user.id,
29 target_id=api_key.id,
30 target_type="api_key",
31 metadata={
32 "reason": "scheduled_rotation"
33 }
34)
35
36# API key revoked
37client.log(
38 action="api_key.revoked",
39 actor_id=user.id,
40 target_id=api_key.id,
41 target_type="api_key",
42 metadata={
43 "reason": "compromised" # or "unused", "employee_offboarding"
44 }
45)

Data Export Events

Log data export activities (important for compliance):

Python
1# Data export requested
2client.log(
3 action="data.export_requested",
4 actor_id=user.id,
5 metadata={
6 "export_type": "full", # or "partial"
7 "format": "json",
8 "reason": "gdpr_request"
9 }
10)
11
12# Data export completed
13client.log(
14 action="data.export_completed",
15 actor_id=user.id,
16 target_id=export.id,
17 target_type="export",
18 metadata={
19 "file_size_bytes": export.size,
20 "records_exported": export.record_count,
21 "download_url_expires": export.url_expires_at.isoformat()
22 }
23)
24
25# Data deletion requested (GDPR)
26client.log(
27 action="data.deletion_requested",
28 actor_id=user.id,
29 metadata={
30 "reason": "gdpr_right_to_erasure",
31 "data_types": ["personal_info", "activity_logs"]
32 }
33)

Framework Integration

Django Middleware

Python
1# middleware.py
2import logvault
3
4client = logvault.Client(os.environ["LOGVAULT_API_KEY"])
5
6class AuditMiddleware:
7 def __init__(self, get_response):
8 self.get_response = get_response
9
10 def __call__(self, request):
11 response = self.get_response(request)
12
13 # Log significant actions
14 if request.method in ["POST", "PUT", "DELETE"]:
15 user_id = request.user.id if request.user.is_authenticated else "anonymous"
16 client.log(
17 action=f"api.{request.method.lower()}",
18 actor_id=str(user_id),
19 metadata={
20 "path": request.path,
21 "status_code": response.status_code,
22 "ip_address": self.get_client_ip(request)
23 }
24 )
25
26 return response
27
28 def get_client_ip(self, request):
29 x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
30 if x_forwarded_for:
31 return x_forwarded_for.split(",")[0]
32 return request.META.get("REMOTE_ADDR")

Express.js Middleware

JavaScript
1// middleware/audit.js
2const { LogVault } = require('@logvault/client');
3
4const client = new LogVault(process.env.LOGVAULT_API_KEY);
5
6function auditMiddleware(req, res, next) {
7 // Capture the original end function
8 const originalEnd = res.end;
9
10 res.end = function(...args) {
11 // Log after response is sent
12 if (['POST', 'PUT', 'DELETE'].includes(req.method)) {
13 client.log({
14 action: `api.${req.method.toLowerCase()}`,
15 actorId: req.user?.id || 'anonymous',
16 metadata: {
17 path: req.path,
18 statusCode: res.statusCode,
19 ipAddress: req.ip
20 }
21 }).catch(console.error);
22 }
23
24 originalEnd.apply(res, args);
25 };
26
27 next();
28}
29
30module.exports = auditMiddleware;

More Resources