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 login2client.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)1112# Failed login attempt13client.log(14 action="user.login_failed",15 actor_id=email, # Use email since user might not exist16 metadata={17 "ip_address": request.ip,18 "reason": "invalid_password" # or "user_not_found", "account_locked"19 }20)2122# Logout23client.log(24 action="user.logout",25 actor_id=user.id,26 metadata={27 "session_duration": session.duration_seconds28 }29)3031# Password change32client.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 created2client.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_type11 }12)1314# Document viewed15client.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_duration22 }23)2425# Document updated26client.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 changed33 "previous_version": document.version - 134 }35)3637# Document deleted38client.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 delete46 }47)
Payment Events
Log payment and subscription activities:
Python
1# Payment processed2client.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_id12 }13)1415# Payment failed16client.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)2728# Subscription created29client.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": 1438 }39)4041# Subscription cancelled42client.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 reason49 "effective_date": subscription.end_date.isoformat()50 }51)
Admin Actions
Log administrative activities:
Python
1# User invited2client.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.name11 }12)1314# User role changed15client.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)2627# User removed28client.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)3839# Settings changed40client.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": True48 }49)
API Key Management
Log API key lifecycle events:
Python
1# API key created2client.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 None11 }12)1314# API key used15client.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.ip22 }23)2425# API key rotated26client.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)3536# API key revoked37client.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 requested2client.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)1112# Data export completed13client.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)2425# 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.py2import logvault34client = logvault.Client(os.environ["LOGVAULT_API_KEY"])56class AuditMiddleware:7 def __init__(self, get_response):8 self.get_response = get_response910 def __call__(self, request):11 response = self.get_response(request)1213 # Log significant actions14 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 )2526 return response2728 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.js2const { LogVault } = require('@logvault/client');34const client = new LogVault(process.env.LOGVAULT_API_KEY);56function auditMiddleware(req, res, next) {7 // Capture the original end function8 const originalEnd = res.end;910 res.end = function(...args) {11 // Log after response is sent12 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.ip20 }21 }).catch(console.error);22 }2324 originalEnd.apply(res, args);25 };2627 next();28}2930module.exports = auditMiddleware;