Logging model events | laravel-activitylog-go | Spatie       

 SPATIE  

laravel-activitylog-go
======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-activitylog-go](https://spatie.be/docs/laravel-activitylog-go/v1)  Advanced-usage  Logging model events

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-activitylog-go/v1) 

  Logging model events    
- [ Introduction ](https://spatie.be/docs/laravel-activitylog-go/v1/introduction)
- [ Requirements ](https://spatie.be/docs/laravel-activitylog-go/v1/requirements)
- [ Installation and setup ](https://spatie.be/docs/laravel-activitylog-go/v1/installation-and-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-activitylog-go/v1/questions-and-issues)
- [ Upgrading ](https://spatie.be/docs/laravel-activitylog-go/v1/upgrading)
- [ About us ](https://spatie.be/docs/laravel-activitylog-go/v1/about-us)
- [ Testing ](https://spatie.be/docs/laravel-activitylog-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-activitylog-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-activitylog-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-activitylog-go/v1/support-us)

Basic usage
-----------

- [ Logging activity ](https://spatie.be/docs/laravel-activitylog-go/v1/basic-usage/logging-activity)
- [ Cleaning up the log ](https://spatie.be/docs/laravel-activitylog-go/v1/basic-usage/cleaning-up-the-log)

Advanced usage
--------------

- [ Logging model events ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/logging-model-events)
- [ Define causer for runtime ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/define-causer-for-runtime)
- [ Using placeholders ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/using-placeholders)
- [ Using multiple logs ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/using-multiple-logs)
- [ Disabling logging ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/disabling-logging)
- [ Customizing actions ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/customizing-actions)
- [ Before logging hook ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/before-logging-hook)
- [ Buffering activities ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/buffering)
- [ Log options ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/log-options)
- [ Causer resolver ](https://spatie.be/docs/laravel-activitylog-go/v1/advanced-usage/causer-resolver)

 Logging model events
====================

###  On this page 

1. [ Basic example of what is logged ](#content-basic-example-of-what-is-logged)
2. [ Customizing the events being logged ](#content-customizing-the-events-being-logged)
3. [ Customizing the description ](#content-customizing-the-description)
4. [ Customizing the log name ](#content-customizing-the-log-name)
5. [ Skipping logging when only certain attributes change ](#content-skipping-logging-when-only-certain-attributes-change)
6. [ Logging only the changed attributes ](#content-logging-only-the-changed-attributes)
7. [ Logging directly related model attributes ](#content-logging-directly-related-model-attributes)
8. [ Logging only a specific JSON attribute sub-key ](#content-logging-only-a-specific-json-attribute-sub-key)
9. [ Prevent saving logs that have no changed attribute ](#content-prevent-saving-logs-that-have-no-changed-attribute)
10. [ Excluding attributes from the log output ](#content-excluding-attributes-from-the-log-output)
11. [ Using the CausesActivity and HasActivity relationships ](#content-using-the-causesactivity-and-hasactivity-relationships)
12. [ Using the ActivityEvent enum ](#content-using-the-activityevent-enum)
13. [ Logging restored events ](#content-logging-restored-events)
14. [ Disabling logging on demand ](#content-disabling-logging-on-demand)
15. [ Tap Activity before logged from event ](#content-tap-activity-before-logged-from-event)
16. [ Logging on pivot models ](#content-logging-on-pivot-models)

The package can automatically log events such as when a model is created, updated and deleted. Register `Observe` listeners for each model in the application's `Listeners` option. A typed `Observer` supplies the model's identity, snapshots and optional logging policy.

```
observer := activitylog.Observer[Article]{
    Snapshot: func(ctx context.Context, article Article, changes []model.Change) (activitylog.Snapshot, *activitylog.Snapshot, error) {
        current := activitylog.Snapshot{
            Reference: activitylog.Reference{Type: "article", ID: strconv.FormatInt(article.ID, 10)},
            Attributes: activitylog.Attributes{"name": article.Name, "text": article.Text},
        }
        previous := current
        previous.Attributes = activitylog.Attributes{"name": article.Name, "text": article.Text}
        for _, change := range changes {
            previous.Attributes[change.Column] = change.Old
        }
        return current, &previous, nil
    },
    Options: func(article Article) activitylog.LogOptions {
        options := activitylog.DefaultOptions()
        options.Attributes = []string{"name", "text"}
        return options
    },
}

options.Listeners = append(options.Listeners, activitylog.Observe(observer)...)
```

Here `options` is your `laravel.Options` value and `Article` is your native model. Import `context`, `strconv`, `go.laravel.com/model` and this package. No trait or global model registry is needed. Omitting `Options` records events without tracking attributes.

Basic example of what is logged
-----------------------------------------------------------------------------------------------------------------------------------------------------

Creating an article records `Event` and `Description` as `created`, with selected values under `AttributeChanges["attributes"]`. Updating it records both `attributes` and `old`. Deleting it records only `old`.

The snapshot function receives native `model.Change` values on update. It must reconstruct old formatted or related values when those differ from stored values. The package does not guess PHP accessor, casting or relationship behavior. Return errors rather than silently omitting failed relationship lookups.

Customizing the events being logged
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `LogOptions.Events` to a list such as `[]string{activitylog.Deleted}`. Use `RecordEvent(ctx, observer, article, "published")` for an application-defined event and include that name in `Events`.

Customizing the description
-----------------------------------------------------------------------------------------------------------------------------------------

Set `LogOptions.Description = func(event string) string { return "This model has been " + event }`. An empty description suppresses that event.

Customizing the log name
--------------------------------------------------------------------------------------------------------------------------------

Set `LogOptions.LogName` to a string pointer. Nil uses the configured default.

Skipping logging when only certain attributes change
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `IgnoreOnly = []string{"text", "updated_at"}`. Updates are skipped when no changed native column remains after removing those names. This does not remove attributes from output when another change triggers the log.

Logging only the changed attributes
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `OnlyDirty = true`. Equal selected values disappear from both the new and old maps. JSON selections are compared at their top-level output key, matching the PHP implementation.

Logging directly related model attributes
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Include related values in `Snapshot.Attributes`, such as `{"author": {"name": "Freek"}}`, and select `author.name`. The result uses the literal key `author.name`. Load relationships explicitly. Use nil for missing relationships.

Logging only a specific JSON attribute sub-key
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Select `preferences->notifications->status`. Only that path is written, nested under `preferences`. Other subkeys are omitted unless selected separately. Snapshots must expose JSON objects as `Attributes` or `map[string]any`.

Prevent saving logs that have no changed attribute
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `OnlyDirty = true` and `LogEmpty = false`. This prevents empty logs when selected attributes did not change.

Excluding attributes from the log output
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `Except = []string{"password"}`. Package-wide `DefaultExceptAttributes` is merged with this list. Exclusions match selected attribute names exactly, as in PHP. To exclude a selected JSON path, use its full arrow name. Do not select the whole parent object if it contains secrets you want to omit.

Using the CausesActivity and HasActivity relationships
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Go does not need traits. Query `Filter{Subject: &reference}` or `Filter{Causer: &reference}`. Both filters include the model type as well as ID and may be combined with logs and event filters. Native bulk query updates do not dispatch per-model events, so use individual model operations when audit events are required.

Using the ActivityEvent enum
--------------------------------------------------------------------------------------------------------------------------------------------

Use the string constants `Created`, `Updated`, `Deleted` and `Restored`. All event APIs also accept custom strings.

Logging restored events
-----------------------------------------------------------------------------------------------------------------------------

The observer recognizes an update that changes `deleted_at` from a non-nil value to nil and records `restored`, not a duplicate `updated`. Laravel Go v0.1.0 has no PHP SoftDeletes trait. Your application owns the soft-delete behavior and filtering. For a custom deleted column or restoration mechanism, dispatch an application event with `RecordEvent`.

Disabling logging on demand
-----------------------------------------------------------------------------------------------------------------------------------------

Return `LogOptions.Disabled = true` for a specific model instance, or pass a `WithoutLogging` context to suppress all package activity in that scope. Other model listeners continue running.

Tap Activity before logged from event
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Set `Observer.BeforeLogging` to `func(context.Context, Article, *Activity) error`. It runs after description resolution and change transformation, before package-wide hooks and saving. Return an error to fail logging.

Logging on pivot models
-----------------------------------------------------------------------------------------------------------------------------

A pivot model needs a stable identity to be an activity subject. Supply that identity in its snapshot and register its own typed observer. There is no automatic pivot-model discovery.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
