Skip to main content
Version: 4.x

Console Commands

Manage audit data via the command line

When using the auditor-bundle or standalone, the library provides console commands for managing audit data.

๐Ÿ“‹ Available Commandsโ€‹

CommandDescription
audit:schema:updateCreate or update audit table schemas
audit:cleanRemove old audit entries

๐Ÿ› ๏ธ audit:schema:updateโ€‹

Creates new audit tables and updates existing ones to match the current schema.

Usageโ€‹

php bin/console audit:schema:update [options]

Optionsโ€‹

OptionShortDescription
--dump-sqlShow SQL statements without executing them
--force-fExecute the SQL statements

Examplesโ€‹

# Preview the SQL that would be executed
php bin/console audit:schema:update --dump-sql

# Output:
# The following SQL statements will be executed:
#
# CREATE TABLE users_audit (...);
# CREATE INDEX idx_type_xxx ON users_audit (type);
# ...

# Execute the changes
php bin/console audit:schema:update --force

# Both: show SQL and execute
php bin/console audit:schema:update --dump-sql --force

When to Runโ€‹

Run this command:

  • After adding #[Auditable] to a new entity
  • After updating auditor to a new version
  • During deployment to ensure schema is up-to-date

TIP

The command is safe to run multiple times. Existing tables are updated (not recreated), existing data is preserved, and only necessary changes are applied.

Exit Codesโ€‹

CodeMeaning
0Success (including "nothing to update")
1Error or missing required options

๐Ÿงน audit:cleanโ€‹

Removes audit entries older than a specified retention period.

Usageโ€‹

php bin/console audit:clean [options] [keep]

Argumentsโ€‹

ArgumentDefaultDescription
keepP12MRetention period as ISO 8601 duration

Optionsโ€‹

OptionShortDescription
--no-confirmSkip confirmation prompt
--dry-runShow what would be deleted without executing
--dump-sqlShow the SQL statements
--date-dClean audits before a specific date
--exclude-xExclude specific entities (can be used multiple times)
--include-iInclude only specific entities (can be used multiple times)

Retention Period Formatโ€‹

The keep argument uses ISO 8601 duration format:

FormatMeaning
P12M12 months
P1Y1 year
P6M6 months
P30D30 days
P7D7 days
P1D1 day
PT12H12 hours

Examplesโ€‹

Basic Cleanupโ€‹

# Keep last 12 months (default)
php bin/console audit:clean

# Keep last 6 months
php bin/console audit:clean P6M

# Keep last 30 days
php bin/console audit:clean P30D

Preview Modeโ€‹

# See what would be deleted without actually deleting
php bin/console audit:clean P6M --dry-run

# See the SQL statements
php bin/console audit:clean P6M --dump-sql

Non-Interactiveโ€‹

# Skip confirmation (useful for cron jobs)
php bin/console audit:clean P12M --no-confirm

Custom Dateโ€‹

# Delete audits before a specific date
php bin/console audit:clean --date=2024-01-01

# Combine with no-confirm for scripts
php bin/console audit:clean --date=2023-12-31 --no-confirm

Entity Filteringโ€‹

# Exclude specific entities from cleanup
php bin/console audit:clean -x App\\Entity\\User -x App\\Entity\\Payment

# Include only specific entities
php bin/console audit:clean -i App\\Entity\\Log -i App\\Entity\\Session

# Long form
php bin/console audit:clean --exclude=App\\Entity\\User --include=App\\Entity\\Post

Outputโ€‹

You are about to clean audits created before 2024-01-15 14:30:45: 12 classes involved.
Do you want to proceed? (yes/no) [no]:
> yes

Starting...
Cleaning audit tables... (users_audit)
12/12 [============================] 100%
Cleaning audit tables... (done)

[OK] Success.

Schedulingโ€‹

For automated cleanup, add to your crontab:

# Clean up audits older than 12 months, daily at 2 AM
0 2 * * * /path/to/php /path/to/bin/console audit:clean P12M --no-confirm >> /var/log/audit-clean.log 2>&1

TIP

Use Symfony Messenger Scheduler if available for more robust scheduling.

Exit Codesโ€‹

CodeMeaning
0Success or cancelled by user
1Error

๐Ÿ’ป Programmatic Usageโ€‹

Both commands can be used programmatically:

Schema Updateโ€‹

use DH\Auditor\Provider\Doctrine\Persistence\Schema\SchemaManager;

$schemaManager = new SchemaManager($provider);

// Get SQL
$sqls = $schemaManager->getUpdateAuditSchemaSql();

// Execute
$schemaManager->updateAuditSchema();

// With progress callback
$schemaManager->updateAuditSchema(null, function (array $progress) {
// Handle progress
});

Cleaning Auditsโ€‹

use Doctrine\DBAL\Connection;

/** @var Connection $connection */
$connection = $storageService->getEntityManager()->getConnection();

$queryBuilder = $connection->createQueryBuilder();
$queryBuilder
->delete('users_audit')
->where('created_at < :until')
->setParameter('until', (new \DateTime('-12 months'))->format('Y-m-d H:i:s'))
;

$deleted = $queryBuilder->executeStatement();

๐Ÿ”’ Command Lockingโ€‹

Both commands use Symfony's Lock component to prevent concurrent execution:

The command is already running in another process.

NOTE

This ensures data integrity when running commands in parallel or from cron jobs.

๐Ÿ“ฆ Registering Commands (Standalone)โ€‹

When not using auditor-bundle, register commands manually:

use DH\Auditor\Provider\Doctrine\Persistence\Command\CleanAuditLogsCommand;
use DH\Auditor\Provider\Doctrine\Persistence\Command\UpdateSchemaCommand;
use Symfony\Component\Console\Application;

$application = new Application();

// Schema update command
$updateCommand = new UpdateSchemaCommand();
$updateCommand->setAuditor($auditor);
$application->add($updateCommand);

// Clean command
$cleanCommand = new CleanAuditLogsCommand();
$cleanCommand->setAuditor($auditor);
$application->add($cleanCommand);

$application->run();

โœ… Best Practicesโ€‹

  1. Always preview first - Use --dump-sql and --dry-run before executing
  2. Backup before cleanup - Especially for large deletions
  3. Schedule regular cleanups - Prevent unlimited growth
  4. Monitor disk space - Audit tables can grow quickly
  5. Consider retention policies - Different entities may need different retention
  6. Test in staging - Verify commands work as expected before production

๐Ÿ”ง Troubleshootingโ€‹

"The command is already running"โ€‹

WARNING

Wait for the other instance to finish, or check for stuck processes.

Schema update has no changesโ€‹

NOTE

This means your audit tables are already up-to-date.

Permission deniedโ€‹

IMPORTANT

Ensure the database user has CREATE TABLE and ALTER TABLE permissions.

Timeout during large cleanupโ€‹

For very large tables, consider:

  • Running during off-peak hours
  • Increasing PHP timeout
  • Breaking into smaller date ranges