Search by

locastic / loggastic

antoniopericpaula_locastic

Activity logs and audit trail for Symfony, stored in Elasticsearch or your relational database

Package info

github.com/Locastic/Loggastic

Type:symfony-bundle

pkg:composer/locastic/loggastic

Statistics

Installs: 21 594

Dependents: 0

Suggesters: 0

Stars: 38

Open Issues: 0

v2.2.1 2026-12-02 13:22 UTC

README

Loggastic

Loggastic is an activity log and audit trail bundle for the Symfony framework. It tracks changes to your objects and their relations. It stores the activity logs in your relational database (via Doctrine DBAL) or in Elasticsearch.

Two kinds of records are stored for each tracked entity:

  1. Activity logs -> saving all CRUD actions made on an object. And additionally saving before and after values for Edit actions.
  2. Current data trackers -> saving the latest object values used for comparing the changes made on Edit actions. This enables us to only store before and after values for modified fields in the activity logs.

System requirements

  • PHP 8.2+ with Symfony 6.4, 7.x or 8.x (Symfony 8 requires PHP 8.4)
  • Doctrine ORM 3.4+ with DoctrineBundle 2.8+ or 3.x
  • A storage backend: any relational database supported by Doctrine DBAL, or Elasticsearch 8 or 9 (default)

Installation

composer require locastic/loggastic

With Symfony Flex, Composer asks if it can run the recipe of the bundle, because the recipe comes from the community ("contrib") repository. Answer y. The recipe registers the bundle and creates config/packages/loggastic.yaml with storage: doctrine.

The default answer is n, and an install with --no-interaction skips the question. In both cases, and in a project without Flex, the bundle is not registered. Register it yourself:

// config/bundles.php
return [
    // ...
    Locastic\Loggastic\LocasticLoggasticBundle::class => ['all' => true],
];

To skip the question, allow community recipes in your project before you install the bundle: composer config extra.symfony.allow-contrib true.

Quick start

Store the logs in the database your application already uses, so you need no extra infrastructure. The Flex recipe creates this file. If you did not run the recipe, create it yourself:

# config/packages/loggastic.yaml
locastic_loggastic:
    storage: doctrine

Mark an entity as loggable with the Loggable attribute and put the serialization group on every field you want to track:

<?php

namespace App\Entity;

use Locastic\Loggastic\Annotation\Loggable;
use Symfony\Component\Serializer\Attribute\Groups;

#[Loggable(groups: ['blog_post_log'])]
class BlogPost
{
    private int $id;

    #[Groups(groups: ['blog_post_log'])]
    private string $title;

    // ...
}

Initialize the storage (database tables or Elasticsearch indexes):

bin/console locastic:activity-logs:create-loggable-indexes

Every create, update and delete on BlogPost is now logged automatically. Read the logs back with the Locastic\Loggastic\DataProvider\ActivityLogProviderInterface service:

$activityLogs = $activityLogProvider->getActivityLogsByClassAndId(BlogPost::class, $blogPost->getId());

Without the storage option, logs are stored in Elasticsearch, which is the default (see Choose your storage). The rest of this README covers each step in detail.

Using Loggastic with coding agents

Loggastic ships a skill and short instructions for coding agents such as Claude Code, Codex and GitHub Copilot. The skill tells the agent how to make an entity loggable, prepare the storage, and read the activity logs.

With Symfony AI Mate in your project, run:

vendor/bin/mate discover

Mate installs the skill as mate-loggastic in .agents/skills/ and .claude/skills/, and adds the instructions to mate/AGENT_INSTRUCTIONS.md.

Without Mate, copy the skill folder into the skills folder of your agent, for example for Claude Code:

mkdir -p .claude/skills
cp -r vendor/locastic/loggastic/skills/loggastic .claude/skills/

Codex and GitHub Copilot read .agents/skills/. Copy the folder again after you update Loggastic.

How Loggastic compares

auditor-bundle is the most installed audit bundle for Symfony. Both bundles log the changes to your Doctrine entities. They differ in these points (compared with auditor-bundle 7.2 in November 2026):

Loggastic auditor-bundle
Storage Your relational database (two shared tables), Elasticsearch 8 or 9, or in memory for tests Your relational database (one audit table for each audited entity)
Logged fields Only the fields that have the serialization group you select All fields, except the fields you exclude
How logs are written As Symfony Messenger messages. Route them to an async transport to keep the writes out of the request In the same database transaction as the entity change
Changes to related objects Logged on the parent object. Select related fields with serialization groups, or let a child object log to its parent (see Handling relations) Logged in the audit table of the related entity. Many-to-many links and unlinks are logged, and the changes from one flush share a transaction hash
Test suites in_memory storage, so tests need no log tables and no Elasticsearch No in-memory storage. The documentation suggests SQLite for development and testing
Web page to browse logs Not included. See Displaying activity logs for Twig and API Platform examples Built-in viewer at /audit
Delete old logs Not included audit:clean console command

Choose your storage

Relational database (no extra infrastructure). Store the logs in the database your application already uses (PostgreSQL, MySQL, SQLite, or anything else supported by Doctrine DBAL):

# config/packages/loggastic.yaml
locastic_loggastic:
    storage: doctrine

The Doctrine storage uses your default DBAL connection and keeps all activity logs in two shared tables (loggastic_activity_log and loggastic_current_data_tracker), with JSON columns for changes data. Timestamps are stored in UTC. No Elasticsearch server or configuration is needed. The Elasticsearch PHP client is still installed as a Composer dependency, but the bundle registers no Elasticsearch services.

Elasticsearch (the default). Without the storage option, activity logs are stored in Elasticsearch, which is a great fit for fast log browsing on high-traffic data. Requirements: Elasticsearch 8 or 9, and a PSR-18 HTTP client implementation for the Elasticsearch client (for example composer require symfony/http-client nyholm/psr7). Each loggable entity gets two indexes: entity_name_activity_log and entity_name_current_data_tracker.

Doctrine storage tables

Both tables are created by the locastic:activity-logs:create-loggable-indexes command and are shared by all loggable classes. Do not create them by hand. The exact column types depend on your database platform, Doctrine DBAL maps them per driver:

loggastic_activity_log
    id            BIGINT, autoincrement, primary key
    object_id     VARCHAR(255)
    object_class  VARCHAR(255)
    action        VARCHAR(255), nullable
    logged_at     DATETIME
    data_changes  JSON, nullable
    request_url   TEXT, nullable
    user_data     JSON, nullable
    context_data  JSON, nullable
    indexes on (object_class, object_id) and (object_class, logged_at)

loggastic_current_data_tracker
    id            BIGINT, autoincrement, primary key
    object_id     VARCHAR(255)
    object_class  VARCHAR(255)
    date_time     DATETIME
    data          JSON, nullable
    unique index on (object_class, object_id)

Doctrine also knows the two tables. doctrine:schema:update, doctrine:migrations:diff and make:migration keep them, and they create the tables when the database has none. So you can create the tables with a migration or with the command. A table that your schema_filter hides stays out of the migrations.

For test suites there is also an in_memory storage that keeps logs in the PHP process, so the full logging flow runs without any external service.

Making your entity loggable

To make your entity loggable you need to do the following steps:

1. Add Loggable attribute to your entity

Add the Locastic\Loggastic\Annotation\Loggable PHP attribute to your entity and define serialization group name:

<?php

namespace App\Entity;

use Locastic\Loggastic\Annotation\Loggable;

#[Loggable(groups: ['blog_post_log'])]
class BlogPost
{    
    // ...
}

If you are using YAML:

locastic_loggable:
        - { class: 'App\Entity\BlogPost', groups: [ 'blog_post_log' ] }

Or XML:

<?xml version="1.0" ?>

<locastic_loggable_classes xmlns="https://locastic.com/schema/metadata/loggable"
                           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                           xsi:schemaLocation="https://locastic.com/schema/metadata/loggable
           https://locastic.com/schema/metadata/loggable.xsd" >
    <loggable_class class="App\Entity\BlogPost">
        <group name="blog_post_log"/>
    </loggable_class>
</locastic_loggable_classes>

2. Add serialization groups to the fields you want to log

Use the serialization group defined in the Loggable attribute config on the fields you want to track. You can add them to the relations and their fields too.

<?php

namespace App\Entity;

use Locastic\Loggastic\Annotation\Loggable;
use Symfony\Component\Serializer\Attribute\Groups;

#[Loggable(groups: ['blog_post_log'])]
class BlogPost
{
    private int $id;

    #[Groups(groups: ['blog_post_log'])]
    private string $title;

    #[Groups(groups: ['blog_post_log'])]
    private ArrayCollection $tags;
    
    // ...
}

Example for logging fields from relations:

<?php

namespace App\Entity;

use Locastic\Loggastic\Annotation\Loggable;
use Symfony\Component\Serializer\Attribute\Groups;

class Tag
{
    private int $id;

    #[Groups(groups: ['blog_post_log'])]
    private string $name;

    #[Groups(groups: ['blog_post_log'])]
    private DateTimeImmutable $createdAt;
    
    // ...
}

Saving the logged-in user

Each activity log saves the user who made the change. Loggastic normalizes the logged-in user with the activity_log serialization group, so it saves only the fields of your user class that have this group:

<?php

namespace App\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Attribute\Groups;

class User implements UserInterface
{
    #[Groups(groups: ['activity_log'])]
    private string $username;

    // ...
}

The user field of the activity log is then {"username": "admin"}. Without the group, it is an empty array, and log.user.username in the examples below does not exist. When no user is logged in, for example in a console command, user is null.

Put the group only on the fields that identify the user, such as the username or the ID. Loggastic copies every field with this group into each activity log.

3. Initialize the storage

Create the database tables or Elasticsearch indexes for your loggable classes:

bin/console locastic:activity-logs:create-loggable-indexes

If you already have some data in the database, make sure to populate current data trackers with the following command:

bin/console locastic:activity-logs:populate-current-data-trackers

4. Displaying activity logs

Here are the examples for displaying activity logs in twig or as Api endpoints:

The activity log record

Each activity log entry contains the following fields: action (Created, Edited, Deleted or a custom action name), loggedAt (UTC timestamp), objectId, objectClass (the class of the loggable entity), user (the fields of the logged-in user that have the activity_log serialization group, e.g. user.username, see Saving the logged-in user), requestUrl, context (optional request data such as the IP address, null unless you turn it on, see Saving request context) and dataChanges. For edit actions dataChanges holds only the modified fields, split into the values before and after the change:

{
    "previousValues": {"title": "My first post"},
    "currentValues": {"title": "My updated post"}
}

Display activity logs in Twig

Locastic\Loggastic\DataProvider\ActivityLogProviderInterface service comes with a few useful methods for getting the activity logs data:

    public function getActivityLogsByClass(string $className, array $sort = [], int $limit = 20, int $offset = 0): array;

    public function getActivityLogsByClassAndId(string $className, $objectId, array $sort = [], int $limit = 20, int $offset = 0): array;

If you need to read logs directly from a specific Elasticsearch index, use Locastic\Loggastic\Bridge\Elasticsearch\Storage\ElasticsearchActivityLogStorage::findByIndexAndObjectId(). Use them to fetch the activity logs from the configured storage and display them in your views. Example for displaying results in Twig:

Activity logs for Blog Posts:
<br>
{% for log in activityLogs %}
    {{ log.action }} {{ log.objectClass|split('\\')|last }} with {{ log.objectId }} ID at {{ log.loggedAt|date('d.m.Y H:i:s') }} by {{ log.user.username ?? 'system' }}
{% endfor %}

objectClass holds the full class name, so the split and last filters show only the short name. A log without a logged-in user, for example from a console command, shows system.

The output would look something like this:

Activity logs for Blog Posts:

Created BlogPost with 1 ID at 01.01.2023 12:00:00 by admin
Edited BlogPost with 1 ID at 02.01.2023 08:30:00 by admin
Deleted BlogPost with 1 ID at 01.01.2023 12:00:00 by admin

Expose activity logs as an API Platform endpoint (any storage)

Loggastic has no dependency on API Platform. The examples in this section and in the next section are tested with API Platform 4.1, 4.2, 4.3, 4.4 and 5.0.

API Platform declares its routes stateless by default, and Loggastic reads the current user for each activity log. If the firewall of your API uses the session, Symfony reports Session was used while the request was declared stateless for each API request that writes a log: as an exception in debug mode, as a log warning otherwise. Set stateless: true on that firewall, or set stateless: false in the API Platform defaults.

A state provider that reads from ActivityLogProviderInterface works with the doctrine storage and with the elasticsearch storage. This example adds the GET /blog_posts/{id}/activity_logs endpoint. It returns the activity logs of one blog post, newest first.

The API resource:

<?php

namespace App\ApiResource;

use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Link;
use App\Entity\BlogPost;
use App\State\BlogPostActivityLogProvider;
use Locastic\Loggastic\Model\Output\ActivityLog;

#[ApiResource(
    operations: [
        new GetCollection(
            uriTemplate: '/blog_posts/{id}/activity_logs',
            uriVariables: ['id' => new Link(fromClass: BlogPost::class)],
            provider: BlogPostActivityLogProvider::class,
        ),
    ],
)]
class BlogPostActivityLog extends ActivityLog
{
    #[ApiProperty(identifier: true)]
    protected ?string $id = null;
}

The state provider:

<?php

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\ProviderInterface;
use App\Entity\BlogPost;
use Locastic\Loggastic\DataProvider\ActivityLogProviderInterface;

final class BlogPostActivityLogProvider implements ProviderInterface
{
    public function __construct(
        private readonly ActivityLogProviderInterface $activityLogProvider,
        private readonly Pagination $pagination,
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        return $this->activityLogProvider->getActivityLogsByClassAndId(
            BlogPost::class,
            $uriVariables['id'],
            ['loggedAt' => 'desc'],
            $this->pagination->getLimit($operation, $context),
            $this->pagination->getOffset($operation, $context),
        );
    }
}

Limits of this approach:

  • The page query parameter works. But totalItems in the response is the number of logs on the returned page, not the number of all logs, because the storage has no count method.
  • There are no filters, for example by user, action or date. The storage reads activity logs by class, or by class and object ID. For the logs of all blog posts, call getActivityLogsByClass() in the provider.
  • There is no endpoint for one activity log, because the storage has no method that reads one log by its ID. API Platform gives each log in the response a generated @id (/.well-known/genid/...).

Activity logs contain user data and the changed values. Protect the endpoint with the security option of API Platform.

Expose activity logs as an API Platform endpoint (Elasticsearch storage)

With the elasticsearch storage, API Platform can also read the activity log indexes directly, through its Elasticsearch integration: https://api-platform.com/docs/core/elasticsearch/. This approach adds filters and a correct totalItems value. It only applies to the elasticsearch storage.

Install the integration (api-platform/core already contains it):

composer require api-platform/elasticsearch

Set the Elasticsearch host for API Platform. This option is separate from locastic_loggastic.elastic_host:

# config/packages/api_platform.yaml
api_platform:
    elasticsearch:
        hosts: ['http://localhost:9200']

Example for displaying the activity logs of all loggable classes in the GET /activity_logs endpoint:

<?php

namespace App\ApiResource;

use ApiPlatform\Elasticsearch\Filter\MatchFilter;
use ApiPlatform\Elasticsearch\Filter\OrderFilter;
use ApiPlatform\Elasticsearch\State\CollectionProvider;
use ApiPlatform\Elasticsearch\State\Options;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use Locastic\Loggastic\Model\Output\ActivityLog as BaseActivityLog;

#[ApiResource(
    operations: [
        new GetCollection(provider: CollectionProvider::class),
    ],
    order: ['loggedAt' => 'DESC'],
    stateOptions: new Options(index: '*_activity_log'),
)]
#[ApiFilter(MatchFilter::class, properties: ['action', 'objectId'])]
#[ApiFilter(OrderFilter::class, properties: ['loggedAt'])]
class ActivityLog extends BaseActivityLog
{
    #[ApiProperty(identifier: true)]
    protected ?string $id = null;
}

The two ApiFilter lines add the query parameters ?action=Created, ?objectId=15 and ?order[loggedAt]=asc. You can add more of the existing ApiPlatform filters: https://api-platform.com/docs/core/filters/. If you want to have different fields in the response, use serialization groups or even create a custom DTO.

Using *_activity_log index will return all activity logs. An endpoint for one activity log (new Get(provider: ItemProvider::class)) does not work with an index pattern like *_activity_log: Elasticsearch reads a document by ID from one index only, so the endpoint returns 404.

If you want to return only logs for one entity, use the exact index name. Then the endpoint for one activity log works too. For example if you only want to show BlogPost entity logs, use blog_post_activity_log index in stateOptions config:

<?php

namespace App\ApiResource;

use ApiPlatform\Elasticsearch\State\CollectionProvider;
use ApiPlatform\Elasticsearch\State\ItemProvider;
use ApiPlatform\Elasticsearch\State\Options;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use Locastic\Loggastic\Model\Output\ActivityLog as BaseActivityLog;

#[ApiResource(
    operations: [
        new Get(provider: ItemProvider::class),
        new GetCollection(provider: CollectionProvider::class),
    ],
    order: ['loggedAt' => 'DESC'],
    stateOptions: new Options(index: 'blog_post_activity_log'),
)]
class BlogPostActivityLog extends BaseActivityLog
{
    #[ApiProperty(identifier: true)]
    protected ?string $id = null;
}

That's it!

Now you have the basic activity logs setup. Each time some change happens in the database for loggable entities, the activity log will be saved to the configured storage.

Customization guide

Now that you have the basic setup, you can add some additional options and customize the library to your needs.

Custom storage backends

The built-in backends are selected with the storage config option (elasticsearch, doctrine or in_memory). The core services only talk to three storage interfaces:

Locastic\Loggastic\Storage\ActivityLogStorageInterface        # writes and reads activity logs
Locastic\Loggastic\Storage\CurrentDataTrackerStorageInterface # tracks the latest state of each loggable object
Locastic\Loggastic\Storage\StorageInitializerInterface        # creates the underlying storage (indexes, tables, ...)

To store logs somewhere else, implement the three interfaces and alias them to your services:

# config/services.yaml
services:
    Locastic\Loggastic\Storage\ActivityLogStorageInterface: '@App\Loggastic\MyActivityLogStorage'
    Locastic\Loggastic\Storage\CurrentDataTrackerStorageInterface: '@App\Loggastic\MyCurrentDataTrackerStorage'
    Locastic\Loggastic\Storage\StorageInitializerInterface: '@App\Loggastic\MyStorageInitializer'

The loggers, message handlers, data providers and console commands will use your implementations without any further changes.

Console commands

locastic:activity-logs:create-loggable-indexes

Creates the storage for every loggable class: two Elasticsearch indexes per class (entity_name_activity_log and entity_name_current_data_tracker), or the two shared database tables when using the Doctrine storage. Existing indexes and tables are skipped, so the command is idempotent and safe to run on every deployment or after adding new loggable classes:

bin/console locastic:activity-logs:create-loggable-indexes

locastic:activity-logs:populate-current-data-trackers

Rebuilds the current data trackers from the objects already in your database. Run it after installing Loggastic on a project with existing data, or when logging was disabled for a while:

bin/console locastic:activity-logs:populate-current-data-trackers

The command is interactive: it asks which loggable class to process (or ALL) and an optional limit of latest objects. It recreates the current data tracker storage for the chosen class, which clears the previously tracked data for that class, and dispatches Messenger messages in batches of 250 objects to repopulate it. If those messages are routed to an async transport, run your consumers to process them.

Configuration reference

All options live under the locastic_loggastic key in config/packages/loggastic.yaml. The values below are the defaults.

General options

# config/packages/loggastic.yaml
locastic_loggastic:
    # storage backend for activity logs: 'elasticsearch', 'doctrine' or 'in_memory'
    storage: elasticsearch

    # directory paths containing loggable classes or xml/yaml files
    loggable_paths:
        - '%kernel.project_dir%/Resources/config/loggastic'
        - '%kernel.project_dir%/src/Entity'

    # Turn on/off the default Doctrine subscriber
    default_doctrine_subscriber: true

    # Turn on/off collection identifier extractor 
    # if set to `true` objects identifiers in collections will be used as array keys
    # if set to `false` default numeric array keys will be used
    identifier_extractor: true

    # Request data saved with each activity log, all opt-in
    context:
        ip_address: false
        user_agent: false
        impersonator: false
        # MCP tool and MCP client (AI agent) of an MCP tool call, needs symfony/mcp-bundle
        mcp: false

Elasticsearch connection options

Only used when storage is elasticsearch:

# config/packages/loggastic.yaml
locastic_loggastic:
    elastic_host: 'localhost:9200'
    elastic_user: null              # basic auth username, for secured clusters
    elastic_password: null          # basic auth password, for secured clusters
    elastic_ssl_verification: true  # disable only for local development
    elastic_date_detection: true    #https://www.elastic.co/guide/en/elasticsearch/reference/current/date-detection.html
    elastic_dynamic_date_formats: "strict_date_optional_time||epoch_millis||strict_time"

Elasticsearch index mappings

Index mappings for the activity log and current data tracker indexes, only used when storage is elasticsearch (see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html#mappings):

# config/packages/loggastic.yaml
locastic_loggastic:
    # ElasticSearch index mapping for ActivityLog
    activity_log:
        elastic_properties:
            id:
                type: keyword
            action:
                type: text
            loggedAt:
                type: date
            objectId:
                type: text
            objectType:
                type: text
            objectClass:
                type: text
            dataChanges:
                type: text
            user:
                type: object
                properties:
                    username:
                        type: text

    # ElasticSearch index mapping for CurrentDataTracker
    current_data_tracker:
        elastic_properties:
            dateTime:
                type: date
            objectId:
                type: text
            objectType:
                type: text
            objectClass:
                type: text
            data:
                type: text

Saving logs async

Activity logs are using Symfony messenger component and are made to work in the async way too. If you want to make them async add the following messages to the messenger config:

framework:
    messenger:
        routing:
            'Locastic\Loggastic\Message\PopulateCurrentDataTrackersMessage': async
            'Locastic\Loggastic\Message\CreateActivityLogMessage': async
            'Locastic\Loggastic\Message\DeleteActivityLogMessage': async
            'Locastic\Loggastic\Message\UpdateActivityLogMessage': async

Important note!

Only one consumer should be used per loggable object in order to not corrupt the data.

Optimising messenger for large amount of data

If you have a large amount of data, you might need more than one consumer to process the messages. In that case, you can configure different transports for the messages and use different consumer for each one. First step is to configure the transports. Here are the examples for AMQP and Doctrine transports for the activity_logs_default and activity_logs_product queues:

AMQP transport config example:

framework:
    messenger:
        transports:
             activity_logs_default:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    exchange:
                        name: activity_logs_default
                    queues:
                        activity_logs_default: ~
             activity_logs_product:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    queues:
                        activity_logs_product: ~
                    exchange:
                        name: activity_logs_product

        routing:
            'Locastic\Loggastic\Message\PopulateCurrentDataTrackersMessage': activity_logs_default
            'Locastic\Loggastic\Message\CreateActivityLogMessage': activity_logs_default
            'Locastic\Loggastic\Message\DeleteActivityLogMessage': activity_logs_default
            'Locastic\Loggastic\Message\UpdateActivityLogMessage': activity_logs_default

Doctrine transport config example:

framework:
    messenger:
        transports:
             activity_logs_default:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    queue_name: activity_logs_default
             activity_logs_product:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    queue_name: activity_logs_product
        routing:
            'Locastic\Loggastic\Message\PopulateCurrentDataTrackersMessage': activity_logs_default
            'Locastic\Loggastic\Message\CreateActivityLogMessage': activity_logs_default
            'Locastic\Loggastic\Message\DeleteActivityLogMessage': activity_logs_default
            'Locastic\Loggastic\Message\UpdateActivityLogMessage': activity_logs_default

Next step is to decorate ActivityLogDispatcher and add your own logic for dispatching messages to the transports. In this example we are sending all messages to the activity_logs_default transport except the ones for the Product entity which are sent to the activity_logs_product transport:

<?php

namespace App\MessageDispatcher;

use App\Entity\Product;
use Locastic\Loggastic\Message\ActivityLogMessageInterface;
use Locastic\Loggastic\MessageDispatcher\ActivityLogMessageDispatcherInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;

#[AsDecorator(ActivityLogMessageDispatcherInterface::class)]
class ActivityLogMessageDispatcher implements ActivityLogMessageDispatcherInterface
{
    public function __construct(private readonly ActivityLogMessageDispatcherInterface $decorated)
    {
    }

    public function dispatch(ActivityLogMessageInterface $activityLogMessage, ?string $transportName = null): void
    {
        if ($activityLogMessage->getClassName() === Product::class) {
            $this->decorated->dispatch($activityLogMessage, 'activity_logs_product');

            return;
        }

        $this->decorated->dispatch($activityLogMessage, $transportName);
    }
}

Depending on your project needs, you can have more transports and dispatch messages to them based on your own logic.

Handling relations

Sometimes you want to log changes made on some entity to some related entity. For example if you are using the Doctrine listener, you will only get the entity that actually had changes. Let's say you want to log Product changes which has a relation to the ProductVariant. On the edit form only fields from the ProductVariant were changed. Even if you run persist() method on Product, in this case only ProductVariant will be shown in the Doctrine listener. For this case you can use the Locastic\Loggastic\Loggable\LoggableChildInterface on ProductVariant:

<?php

namespace App\Entity;

use Locastic\Loggastic\Loggable\LoggableChildInterface;

class ProductVariant implements LoggableChildInterface
{
    private Product $product;
    
    public function getProduct(): Product
    {
        return $this->product;
    }
    
    public function logTo(): ?object
    {
        return $this->getProduct();
    }
    
    // ...
}

Now each change made on ProductVariant will be logged to the Product.

Warning: logTo() must still return the parent at the moment the child is deleted, or the removal will not be logged. Entity remove*() methods generated by the maker bundle set the owning side to null:

public function removeProductVariant(ProductVariant $productVariant): static
{
    if ($this->productVariants->removeElement($productVariant)) {
        if ($productVariant->getProduct() === $this) {
            $productVariant->setProduct(null); // breaks logTo(), remove this
        }
    }

    return $this;
}

With orphanRemoval enabled the variant is deleted as soon as it leaves the collection, so nulling the owning side is unnecessary, and it makes logTo() return null while Loggastic is logging the removal, silently dropping the parent's activity log. Keep the owning side set instead.

Custom event listeners for saving activity logs

You can use Locastic\Loggastic\Logger\ActivityLoggerInterface service to save item changes to the configured storage:

<?php
namespace App\Service;

use Locastic\Loggastic\Logger\ActivityLoggerInterface;

class SomeService
{
    public function __construct(private readonly ActivityLoggerInterface $activityLogger)
    {
    }
    
    public function logItem($item): void
    {
        $this->activityLogger->logCreatedItem($item, 'custom_action_name');
        $this->activityLogger->logDeletedItem($item->getId(), get_class($item), 'custom_action_name');
        $this->activityLogger->logUpdatedItem($item, 'custom_action_name');
    }
}

Depending on you application logic, you need to find the most fitting place to trigger logs saving.

In most cases that can be the Doctrine event listener which is triggered on each database change. Loggastic comes with a built-in Doctrine listener which is used by default. If you want to turn it off, you can do it by setting the default_doctrine_subscriber config option to false:

# config/packages/loggastic.yaml

locastic_loggastic:
    default_doctrine_subscriber: false

If you are using ApiPlatform, one of the good options would be to use its POST_WRITE event: https://api-platform.com/docs/core/events/#custom-event-listeners

And for the Sylius projects you can use the Resource bundle events: https://docs.sylius.com/en/1.12/book/architecture/events.html

Save activity logs when no data changes were made

Sometimes you want to save activity logs even if no data changes were made. For example if you want to log order confirmation email was sent or some PDF was downloaded.

You can do that by setting the 3rd parameter to true:

$this->activityLogger->logUpdatedItem($item, 'Order confirmation sent', true);

Saving request context (IP address, user agent, impersonator, custom data)

Each activity log can hold a context: additional data about how the change was made. Loggastic can collect three values for you. All three are turned off by default, so nothing changes until you turn them on:

# config/packages/loggastic.yaml
locastic_loggastic:
    context:
        ip_address: true    # client IP address, saved as "ipAddress"
        user_agent: true    # User-Agent request header, saved as "userAgent"
        impersonator: true  # identifier of the original user during impersonation (switch user), saved as "impersonator"

A value is left out when it is not available, for example in a console command. The context is collected before the message is dispatched, so it is also correct when the logs are saved async.

An IP address is personal data in most jurisdictions. Turn ip_address on only if you have a reason to store it. Behind a load balancer or a reverse proxy, configure Symfony's trusted proxies, otherwise the saved address is the address of the proxy.

Read the context from the activity log:

{% for log in activityLogs %}
    {{ log.action }} by {{ log.user.username }} from {{ log.context.ipAddress|default('unknown') }}
{% endfor %}

Locastic\Loggastic\Model\Output\ActivityLog implements Locastic\Loggastic\Model\ContextAwareLogInterface. Logs saved without context return null from getContext().

Saving which AI agent made a change (MCP)

An AI agent can change data through an MCP tool: an API Platform MCP tool (#[McpTool], #[ApiResource(mcp: [...])]) or a symfony/mcp-bundle tool. The activity log of such a change saves the user of the security token, or no user over stdio. Nothing in it shows that an agent made the change. Turn on the mcp option to save the tool and the agent app:

# config/packages/loggastic.yaml
locastic_loggastic:
    context:
        mcp: true

Each activity log of a tool call then has a context like this:

{"mcpTool": "update_product_price", "mcpClientName": "my-agent", "mcpClientVersion": "1.4.0"}
  • mcpTool: the name of the MCP tool that made the change.
  • mcpClientName and mcpClientVersion: the name and the version that the MCP client (the agent app) reports about itself.

The client name and version come from the agent app and are not a verified identity. The user of the log stays the user of the security token. Each value is left out when it is not available. Changes that do not come from an MCP tool call, for example in a controller or a console command, get no MCP values.

The option needs symfony/mcp-bundle 0.15 or later (mcp/sdk 0.9 or later). API Platform MCP uses the same bundle. Loggastic reads the values from the events of the MCP SDK, so the option works over HTTP and over stdio (bin/console mcp:server), and with each MCP protocol version that the SDK supports. Clients that use a protocol version before 2026-07-28 send their name and version only when they connect. Loggastic then reads them from the MCP session.

Custom data

To add your own data (a tenant, a correlation ID, the name of the console command, ...), implement ActivityLogContextProviderInterface. With autoconfiguration the service is picked up automatically, otherwise tag it with locastic_loggastic.context_provider:

<?php
namespace App\Loggastic;

use Locastic\Loggastic\Context\ActivityLogContextProviderInterface;

final class TenantContextProvider implements ActivityLogContextProviderInterface
{
    public function __construct(private readonly TenantResolver $tenantResolver)
    {
    }

    public function getContext(): array
    {
        return ['tenant' => $this->tenantResolver->getCurrentTenantId()];
    }
}

The returned data must be JSON-serializable. Custom providers always run, independent of the context config options.

Upgrading an existing Doctrine storage

The context is stored in a new context_data column of the loggastic_activity_log table. If the table was created before version 2.2, run the command below once before you turn on a context option or register a provider. It adds the column and keeps the existing logs:

bin/console locastic:activity-logs:create-loggable-indexes

Elasticsearch needs no change: the context field is added to the existing index mappings automatically.

Contribution

If you have idea on how to improve this bundle, feel free to contribute. If you have problems or you found some bugs, please open an issue.

Support

Want us to help you with this bundle or any ApiPlatform/Symfony project? Write us an email on info@locastic.com