Management Commands
Logmancer provides management commands for maintaining your log database.
logmancer_cleanup
- class logmancer.management.commands.logmancer_cleanup.Command(stdout=None, stderr=None, no_color=False, force_color=False)[source]
Bases:
BaseCommand- help = 'Logmancer: Cleans up old log entries.'
Command Class
Usage
Basic cleanup (uses CLEANUP_AFTER_DAYS setting, default 30 days):
python manage.py logmancer_cleanup
Custom retention period:
# Delete logs older than 60 days
python manage.py logmancer_cleanup --days=60
Dry run (preview what would be deleted):
python manage.py logmancer_cleanup --dry-run
Options
--daysNumber of days to retain logs. Logs older than this will be deleted.
Type:
intDefault: Uses
LOGMANCER_CLEANUP_AFTER_DAYSsetting (default: 30)Example:
python manage.py logmancer_cleanup --days=90
--dry-runShow how many logs would be deleted without actually deleting them.
Type:
flagExample:
python manage.py logmancer_cleanup --dry-run
Examples
Clean up logs older than 7 days:
python manage.py logmancer_cleanup --days=7
Preview cleanup without deleting:
python manage.py logmancer_cleanup --days=30 --dry-run
Output:
[Logmancer] 1,234 log entries older than 30 days would be deleted (dry run).
Automated cleanup with cron:
# Run daily at 2 AM
0 2 * * * cd /path/to/project && python manage.py logmancer_cleanup --days=30
Windows Task Scheduler:
cd C:\path\to\project
python manage.py logmancer_cleanup --days=30
Configuration
Set default cleanup period in settings.py:
LOGMANCER = {
'CLEANUP_AFTER_DAYS': 30, # Default retention period
}
Note
The --days argument overrides the CLEANUP_AFTER_DAYS setting.
Behavior
When executed, the command:
Calculates threshold date (current date - days)
Queries
LogEntryrecords older than thresholdDeletes matching records (unless
--dry-run)Logs cleanup action to database
Outputs summary to console
Warning
This operation cannot be undone. Use --dry-run first to verify.
Integration with Django
The command integrates with Django’s management framework:
from django.core.management import call_command
# Call from Python code
call_command('logmancer_cleanup', days=60)
# With dry-run
call_command('logmancer_cleanup', dry_run=True)
Testing
Test the command in your project:
from django.core.management import call_command
from django.test import TestCase
from logmancer.models import LogEntry
class TestCleanup(TestCase):
def test_cleanup_old_logs(self):
# Create old log
old_log = LogEntry.objects.create(message="Old")
LogEntry.objects.filter(pk=old_log.pk).update(
timestamp=timezone.now() - timedelta(days=31)
)
# Run cleanup
call_command('logmancer_cleanup')
# Verify deletion
assert not LogEntry.objects.filter(pk=old_log.pk).exists()
See Also
Log Cleanup Strategy - Best practices for log retention
Configuration - Full configuration reference
Models - LogEntry model documentation