Configures and uses the Doctrine ORM audit-log provider (damienharper/auditor 2.x): standalone setup, #[Auditable]/#[Ignore]/#[Mask]/#[Security] attributes, audit table schema v2, migration from v1, and reading audits via Reader/Query/filters.
Ships in auditor-doctrine-provider. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Doctrine ORM provider of damienharper/auditor. On flush(), it turns the
UnitOfWork changesets of audited entities into audit entries (insert, update, remove, associate, dissociate) and
writes them to one audit table per entity (posts → posts_audit), in the same database transaction, just before
the COMMIT. It also reads them back (Reader, Query, filters).
Namespace: DH\Auditor\Provider\Doctrine; core classes (Auditor, Configuration, attributes, Entry): DH\Auditor.
In a Symfony app, install damienharper/auditor-bundle (8.x for provider 2.x) instead of wiring the provider by hand:
it creates the Auditor, the provider, the services, the DBAL middleware, the console commands and a viewer from YAML
configuration. Read the bundle docs; this skill then still applies to attributes, audit tables and the Reader.
| Provider | auditor (core) | PHP | doctrine/dbal | doctrine/orm | Symfony components |
|---|---|---|---|---|---|
| 2.x (current) | ^5.0 | >= 8.4 | ^4.6 | ^3.7 | ^8.1 (symfony/cache, symfony/lock) |
| 1.x (bug and security fixes) | ^4.1 | >= 8.4 | ^4.3 | ^3.2 | ^8.1 (symfony/cache, symfony/lock) |
2.x writes schema v2 audit tables; tables created by 1.x must be migrated (see "Migrating from 1.x").
The console commands extend Symfony\Component\Console\Command\Command: outside Symfony, composer require symfony/console to run them.
use DH\Auditor\Auditor;
use DH\Auditor\Configuration as AuditorConfiguration;
use DH\Auditor\User\User;
use DH\Auditor\Provider\Doctrine\Auditing\DBAL\Middleware\AuditorMiddleware;
use DH\Auditor\Provider\Doctrine\Configuration;
use DH\Auditor\Provider\Doctrine\DoctrineProvider;
use DH\Auditor\Provider\Doctrine\Persistence\Schema\SchemaManager;
use DH\Auditor\Provider\Doctrine\Service\AuditingService;
use DH\Auditor\Provider\Doctrine\Service\StorageService;
use Doctrine\DBAL\Configuration as DbalConfiguration;
use Doctrine\DBAL\DriverManager;
use Symfony\Component\EventDispatcher\EventDispatcher;
// 1. The DBAL connection of every auditing entity manager MUST have the AuditorMiddleware,
// set before the connection is created: it writes the audits at COMMIT. Without it, nothing is audited.
$dbalConfiguration = new DbalConfiguration();
$dbalConfiguration->setMiddlewares([new AuditorMiddleware()]);
$connection = DriverManager::getConnection($connectionParams, $dbalConfiguration);
// ... build $entityManager on $connection
// 2. Core auditor: blame (user, IP, firewall) comes from callables
$auditorConfiguration = new AuditorConfiguration(['timezone' => 'UTC']);
$auditorConfiguration->setUserProvider(fn (): ?User => new User('42', 'alice', App\Entity\User::class)); // id, username, class (user_fqdn); 4th: impersonator
$auditorConfiguration->setSecurityProvider(fn (): array => [$clientIp, $firewallName]); // [ip, firewall]
$auditor = new Auditor($auditorConfiguration, new EventDispatcher());
// 3. Provider
$provider = new DoctrineProvider(new Configuration([
'table_suffix' => '_audit',
'entities' => [App\Entity\Post::class => ['enabled' => true]], // merged with #[Auditable] entities
]));
$provider->registerAuditingService(new AuditingService('default', $entityManager)); // attaches the Doctrine listeners
$provider->registerStorageService(new StorageService('default', $entityManager)); // where audit rows are written
$auditor->registerProvider($provider);
// 4. Create / update the audit tables (NEW install only: on 1.x tables it drops the legacy columns unconverted;
// migrate them with audit:schema:migrate first, see "Migrating from 1.x")
(new SchemaManager($provider))->updateAuditSchema();
StorageService entity manager = audits in
another database (see "Several databases").registerAuditingService() attaches the listeners immediately; a DI container can call
$provider->disableListenerAttachment() first and declare $provider->getDoctrineSubscriber() (onFlush, postFlush,
and Gedmo's postSoftDelete when soft-deleteable is used)
and new CreateSchemaListener($provider) (postGenerateSchemaTable) itself.$provider->reset() between messages (it implements ResetInterface).DH\Auditor\Provider\Doctrine\Configuration)| Option | Default | Use |
|---|---|---|
table_prefix / table_suffix | '' / '_audit' | Audit table name = prefix + entity table + suffix |
ignored_columns | [] | PHP property names never audited, all entities |
entities | [] | FQCN => options (below) |
storage_mapper | null | Callable (or invokable class name) fn (string $entity, array $storageServices): StorageService |
batch_size | 0 | > 0: multi-row INSERTs at commit (faster; payload then has no id) |
full_snapshot_on_remove | false | remove entries record every audited field's last value |
skip_disabled_entities | false | No audit table for entities disabled by configuration |
compression | false | JSON COMPRESSED diffs/extra_data on MariaDB only |
utf8_convert | false | Convert strings to UTF-8 before storing |
mask_secret | null | Key of the #[Mask(strategy: MaskStrategy::KeyedHash)] HMACs, 32 bytes min.; changing it changes later hashes |
ignored_columns_resolver, root_resolver, entity_label_resolver, read_scope | null | Callables, see docs |
viewer | true | Used by the bundle viewer (page_size also defaults paginate()); auditor-bundle defaults it to false |
Entity options: enabled, ignored_columns, audited_columns (allowlist), roles (['view' => [...]]),
max_age (ISO 8601 duration) / max_entries (retention for audit:clean), roots.
Runtime: $provider->getConfiguration()->enableAuditFor(Post::class) / disableAuditFor().
Checks: $provider->isAuditable($e), isAudited($e), isAuditedField($e, 'title').
DH\Auditor\Attribute)use DH\Auditor\Attribute\{Auditable, Ignore, Mask, Security, DiffLabel, AuditRoot};
use DH\Auditor\Masking\MaskStrategy;
#[ORM\Entity]
#[Auditable] // enabled: true, maxAge: 'P7Y', maxEntries: 10_000 optional
#[Security(view: ['ROLE_ADMIN'])] // only declares roles: your core role_checker must enforce them (null = everyone reads)
#[Ignore(field: 'inheritedSecret')] // class-level form needs field:
class Post
{
#[ORM\Column] #[Ignore] private string $password; // never in diffs
#[ORM\Column] #[Mask(strategy: MaskStrategy::KeyedHash)] private string $email; // change kept, value = HMAC
#[ORM\Column(nullable: true)] #[Mask] private ?string $pin = null; // change kept, value = "***"
#[ORM\Column] #[DiffLabel(resolver: CategoryLabel::class)] private int $categoryId;
}
#[ORM\Entity] attribute; XML/PHP-mapped entities must be
listed in the entities option.enabled: false wins, config roles override #[Security] per scope,
config ignored_columns / roots are added. Ignoring always beats audited_columns.#[DiffLabel] resolvers implement DH\Auditor\Contract\DiffLabelResolverInterface and are fetched from a PSR-11
container set with $provider->setDiffLabelResolverLocator($container).#[Mask]: values compared first, then masked ("1234" → "5678" is recorded "***" → "***"); applies to
insert, update and (with full_snapshot_on_remove) remove entries, columns and to-one associations. A masked
field gets no #[DiffLabel] label and a masked JSON field no deep diff. #[Mask] on an identifier or a
collection, or KeyedHash without mask_secret, throws when the attributes are loaded. The label of the entity (its __toString() or a label resolver) is written in clear in the source of every entry: never build it from a masked field.#[AuditRoot('visit.property')] (repeatable) indexes entries under another entity's history (see Histories).One table per audited entity (single table inheritance: one table for the hierarchy, discriminator tells the class).
| Column | Content |
|---|---|
id | BIGINT autoincrement |
schema_version | 2 for current rows, 1 for legacy (1.x) rows |
type | insert, update, remove, associate, dissociate |
object_id | identifier of the audited entity (string) |
discriminator | entity class in inheritance hierarchies |
transaction_id | ULID (CHAR 26) shared by the entries of one database transaction (all its flushes) |
diffs | JSON: {"source": {...}, "changes": {"field": {"old": ..., "new": ...}}}; associations: source, target, is_owning_side, join_table |
extra_data | JSON, custom data (extra_data_provider or a LifecycleEvent listener) |
blame_id | user id |
blame | JSON: username, user_fqdn, user_firewall, ip (+ impersonator {id, username, fqdn} on switch user, + via with a blame context) |
created_at | datetime |
JSON columns are native JSON on MySQL/MariaDB, JSONB on PostgreSQL, TEXT on SQLite. When an entity has roots, one
{table_prefix}audit_root table per storage indexes entries under their roots.
Create/update tables with one of:
(new SchemaManager($provider))->updateAuditSchema(), or getUpdateAuditSchemaSql() to get the SQL (no v1 guard,
unlike the command);audit:schema:update --dump-sql / --force;doctrine:schema:update / Doctrine Migrations: the provider adds the audit tables to the Doctrine schema
(postGenerateSchemaTable), so doctrine:migrations:diff generates them. When upgrading 1.x tables managed this
way, follow "Audit tables managed by Doctrine Migrations" in the upgrade guide (replayable migration, deployment
order).Adding or removing entity fields needs no audit schema change (diffs are JSON). Removing an entity from auditing does not drop its audit table.
DH\Auditor\Provider\Doctrine\Persistence\Command)| Command | Class | Purpose |
|---|---|---|
audit:schema:update | UpdateSchemaCommand | Create/update audit tables; refuses while a v1 table exists |
audit:schema:migrate | MigrateSchemaCommand | Migrate v1 tables to v2 |
audit:clean | CleanAuditLogsCommand | Delete entries older than keep (default P12M), --date, -x/-i, --dry-run, --no-confirm |
audit:export | ExportAuditLogsCommand | NDJSON/JSON/CSV export, --id, --from, --to, --blame-id, --anonymize, --output |
audit:snapshot | SnapshotCommand | Record the current state of existing entities (--all, --batch-size, --force, --dry-run) |
audit:roots:rebuild | RebuildRootsCommand | Rebuild the audit_root index (--entity, --dry-run) |
Standalone: $application->addCommand((new UpdateSchemaCommand())->setAuditor($auditor)); for each command.
They hold a host-local lock (Symfony Lock). A concurrent run prints "already running in another process": the schema
and roots commands exit with a failure, audit:clean, audit:export and audit:snapshot with 0 (watch the output
in cron jobs). audit:export takes an optional entity argument and --format (ndjson default, json, csv);
audit:snapshot takes entities as arguments or --all; audit:clean also has --dump-sql.
v1 tables have transaction_hash, blame_user, blame_user_fqdn, blame_user_firewall, ip; v2 replaces them with
transaction_id (ULID) and blame (JSON). Follow the upgrade guide; the core sequence is:
doctrine:schema:update or a generated Doctrine migration on audit tables yet: on v1
tables they drop the legacy columns without converting their data.audit:schema:migrate --dump-sql --convert-all (preview), then audit:schema:migrate --force --convert-all.
--limit=N converts a sample and keeps legacy columns (resumable); --drop-transaction-hash drops
transaction_hash without conversion (loses grouping, only on request).audit:schema:update --force (v2 indexes, column types).audit:schema:migrate (no option) and audit:schema:update --dump-sql report nothing left.audit:roots:rebuild if entities declare roots. Update code reading $entry->transactionHash (removed) and raw
SQL using the legacy columns (blame_user → blame JSON username, transaction_hash → transaction_id).The Reader reads migrated and non-migrated tables alike.
use DH\Auditor\Provider\Doctrine\Persistence\Reader\Reader;
use DH\Auditor\Provider\Doctrine\Persistence\Reader\Query;
use DH\Auditor\Provider\Doctrine\Persistence\Reader\Filter\{DateRangeFilter, JsonFilter, NullFilter, SimpleFilter};
$reader = new Reader($provider);
$query = $reader->createQuery(Post::class, [
'object_id' => 42, // int|string|array
'type' => ['insert', 'update'],
'blame_id' => '7', // 'user_id' is an alias
'transaction_id' => null,
'changed_field' => 'title', // string|list, needs native JSON + v2 table
'blame_origin' => null, // 'http'|'console'|'messenger'|'system'
'page' => 1, 'page_size' => 50, // page_size null = no limit
]);
$query->addFilter(new DateRangeFilter(Query::CREATED_AT, new \DateTimeImmutable('-30 days'), null));
$entries = $query->execute(); // list<DH\Auditor\Model\Entry>, newest first
$total = $query->count();
$page = $reader->paginate($reader->createQuery(Post::class), page: 2, pageSize: 25);
// keys: results (ArrayIterator of Entry), currentPage, numPages, numResults, hasNextPage, nextPage, ...
$byEntity = $reader->getAuditsByTransactionId($ulid); // [FQCN => list<Entry>]
SimpleFilter (= / IN), DateRangeFilter, RangeFilter, NullFilter (IS NULL only),
JsonFilter($column, $path, $value, $operator, $strict) (=, !=, <>, LIKE, NOT LIKE, IN, NOT IN,
IS NULL, IS NOT NULL), ChangedFieldFilter, BlameOriginFilter, RootFilter,
ImpersonatorFilter(?string $impersonatorId = null) (native JSON). Filters are ANDed, except the SimpleFilters of
one column (including the object_id / type options), merged into one IN (ORed).page_size defaults to 50: createQuery(X)->execute() returns the 50 most recent entries only; pass
'page_size' => null or use iterate() to read everything (count() ignores the limit).DateRangeFilter bounds are formatted in their own timezone while created_at is stored in the auditor timezone:
build the bounds in the auditor timezone.Query::ID, TYPE, OBJECT_ID, DISCRIMINATOR, TRANSACTION_ID, USER_ID (= blame_id),
CREATED_AT. The default order is created_at DESC, id DESC: for oldest first, resetOrderBy() then
addOrderBy(Query::CREATED_AT, 'ASC')->addOrderBy(Query::ID, 'ASC'). Raw paging: limit($limit, $offset).count() throws on database errors (1.x returned 0); getAuditsByTransactionId() silently skips the entities
the role checker denies.Query::JSON is the filter slot name of JsonFilter, not a column: new NullFilter(Query::JSON) produces
json IS NULL and fails. Test JSON content with JsonFilter('extra_data', 'key', null, 'IS NULL'), or check
$entry->extraData === null in PHP.JsonFilter falls back to
LIKE with a warning ($strict = true throws instead); ChangedFieldFilter and BlameOriginFilter throw.createQuery() throws AccessDeniedException when the core role_checker denies the view role, and
InvalidArgumentException for a non-audited entity. Single table inheritance: 'strict' => true (default) keeps
only the queried class.Query::iterate() streams raw rows (created_at is a string) for large exports.One transaction (one action: the flushes of one database transaction share its id) often writes several entries, so
a page of entries (execute(), paginate()) cuts actions and holds a varying number of them. To show N whole
actions per page, page the transactions instead (the query's filters apply, its order and limit do not; most recent
first):
$query = $reader->createQuery(Post::class, ['page_size' => null]);
$total = $query->countTransactions();
$transactions = $query->transactions(limit: 25, offset: 25); // list<TransactionSummary>, page 2
$ids = array_values(array_filter(array_map(static fn ($t) => $t->transactionId, $transactions)));
$entries = $query->transactionEntries($ids); // same filters, most recent first
TransactionSummary (DH\Auditor\Provider\Doctrine\Persistence\Reader\TransactionSummary): transactionId,
createdAt (its most recent entry), entries (count). An entry written without transaction id is a transaction
of its own: transactionId is null and entryId + table identify it (transactionEntries() does not return it:
read it with a SimpleFilter(Query::ID, …)).Query::transactionsOf($queries, $limit, $offset) and Query::countTransactionsOf($queries)
(one query per table; a transaction that wrote in several tables counts once, twice across two connections).RootQuery::fetchTransactions($limit, after: $cursor) returns a RootPage of exactly $limit whole
actions (except the last page); RootQuery::countTransactions() counts them.countTransactions() cost a pass over the table.$query->countTransactionsByDay() returns ['Y-m-d' => count] (days of created_at as stored,
ascending, days without any left out; a transaction spanning midnight counts on each of its days).Entry (DH\Auditor\Model\Entry)Virtual properties: id, schemaVersion, type (plain string), objectId, discriminator, transactionId,
userId, blame (array), username, userFqdn, userFirewall, ip, impersonator, via, extraData
(already decoded ?array: never json_decode() it), createdAt (DateTimeImmutable in the auditor timezone),
entity and rootPath (set by root queries).
Methods: getDiffs() (the changes of a v2 diff, the whole diff for associations, raw diff for v1),
getDiffSource(), getDiffTarget(), isDeepDiff($field), isSnapshot().
$reader->createRootQuery(Property::class, 42)->fetch(20) returns a RootPage (cursor pagination: after:,
since:) merging the root's entries and those of entities declaring it with #[AuditRoot] / roots. By default a
page goes past its size to finish the transaction of its last entry (groupKey: false cuts it exactly); an invalid
cursor throws InvalidArgumentException (check with RootQuery::isCursor()); iterate() and count() also exist.
Blame contexts (via, DH\Auditor\Blame\BlameContext): wrap the work in $auditorConfiguration->getBlameContextStack()->run(new BlameContext('import', 'Batch #42'), fn () => $em->flush()); the context is captured at flush time, and a context carrying a user blames
that user. A custom DBAL type whose value needs converting implements
DH\Auditor\Provider\Doctrine\Transaction\NeedsConversionToAuditableType (moved from the core).
$reader->getLastChanges(Post::class, 42, ['title']) gives the last Change per field;
$reader->getFieldHistory(Post::class, 42, 'title') returns a Query.
Register one AuditingService per application entity manager and one StorageService per audit database. With more
than one StorageService, storage_mapper is required (otherwise ProviderException):
$provider = new DoctrineProvider(new Configuration([
'storage_mapper' => fn (string $entity, array $services): StorageService =>
$entity === User::class ? $services['audit_sensitive'] : $services['audit_general'],
]));
$provider->registerStorageService(new StorageService('audit_sensitive', $sensitiveEm));
$provider->registerStorageService(new StorageService('audit_general', $generalEm));
Audit writes to another connection are not atomic with the application transaction: on rollback the provider deletes
them best effort and logs failures to $provider->setLogger($psrLogger).
UPDATE/DELETE ($em->createQuery()), query builder bulk updates and raw DBAL/SQL: they bypass the
UnitOfWork. Only changes flushed through persist() / remove() / flush() are audited.AuditorMiddleware.associate/dissociate entries, not field diffs; ignored_columns and
audited_columns do not filter them.AuditorMiddleware on the connection: tables exist, flushes succeed, no audit row is written.ignored_columns / audited_columns / #[Ignore(field:)]: they take property names.transactions() / fetchTransactions().json_decode() on $entry->extraData, or reading $entry->transactionHash (removed in auditor 5.0, required by 2.x).new NullFilter(Query::JSON): there is no json column.$payload['id'] in a LifecycleEvent listener with batch_size > 0: buffered entries have no id yet.doctrine:schema:update --force on 1.x audit tables before audit:schema:migrate: data loss.extra_data_provider to be called per entry: it is called once per flush; use a LifecycleEvent
listener ($event->entity) for per-entity data.StorageServices without storage_mapper.#[Auditable] to an XML-mapped entity, or changing attributes without clearing the metadata cache.Published docs (https://damienharper.github.io/auditor-docs/auditor-doctrine-provider):
docs/upgrade/ in the repository): https://damienharper.github.io/auditor-docs/auditor-doctrine-provider/upgradeWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
/auditor-doctrine-provider:auditor-doctrine-providerfrom auditor-doctrine-provider
auditor-doctrine-provider@auditor is listed by damienharper/auditor — review the source before installing
npx claudepluginhub damienharper/auditor --plugin auditor-doctrine-provider