Automatically delete old audit logs based on configurable retention policies using the cleanup command.
Configure retention policies in your config/app.php or config/app_local.php:
'AuditStash' => [
'persister' => \AuditStash\Persister\TablePersister::class,
'retention' => [
'default' => 90, // Keep logs for 90 days by default
'tables' => [
'Users' => 365, // Keep user logs for 1 year
'Orders' => 2555, // Keep order logs for 7 years
'Sessions' => 30, // Keep session logs for 30 days
'ComplianceLogs' => false, // Never delete (keep forever)
],
],
],- Tables listed in
tablesuse their specific retention period - Tables not listed inherit the
defaultretention period - If no
defaultis configured, falls back to 90 days - Set a table's retention to
falseto disable cleanup entirely (keep logs forever)
Table keys in the tables array must match the source column in your audit logs exactly (case-sensitive). By default, CakePHP uses CamelCase table names:
'tables' => [
'Users' => 365, // Match CamelCase table name
'OrderItems' => 730, // Not 'order_items' or 'orderitems'
'MyPlugin.Users' => 365, // Plugin-prefixed tables also supported
],Check your actual source values in the audit_logs table to ensure the keys match.
For compliance or legal requirements, you may need to keep certain logs forever. Set the table's retention to false:
'AuditStash' => [
'retention' => [
'default' => 90,
'tables' => [
'FinancialTransactions' => false, // Never delete
'UserConsentLogs' => false, // Never delete
],
],
],When running cleanup for a table with disabled retention:
bin/cake audit_stash cleanup --table FinancialTransactions --force
# Output: Retention is disabled for table "FinancialTransactions". No logs will be deleted.If you prefer not to use config-based retention, you can selectively cleanup specific tables using the --table flag:
#!/bin/bash
# cleanup-audit-logs.sh
bin/cake audit_stash cleanup --table Sessions --force
bin/cake audit_stash cleanup --table ApiRequests --force
# Orders and Users are intentionally not cleanedWarning: Setting a table's retention to 0 will delete all logs for that table immediately - this is probably not what you want! Use false instead to keep logs forever.
The cleanup command provides several options:
# Preview what would be deleted (dry run)
bin/cake audit_stash cleanup --dry-run
# Clean up logs older than configured retention period
bin/cake audit_stash cleanup --force
# Clean up logs for specific table only
bin/cake audit_stash cleanup --table Users --forceAdd to your crontab to run cleanup automatically:
# Run cleanup daily at 2am
0 2 * * * cd /path/to/app && bin/cake audit_stash cleanup --forceNote: The cleanup command only works with TablePersister.
For Elasticsearch, use Index Lifecycle Management (ILM) policies instead.