You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Store additional context with your metrics by adding custom attributes. This is useful for segmenting metrics by various dimensions like source, country, device type, or any other custom data.
261
+
262
+
First, create a migration to add custom columns to the `metrics` table:
263
+
264
+
```php
265
+
use Illuminate\Database\Schema\Blueprint;
266
+
use Illuminate\Support\Facades\Schema;
267
+
268
+
Schema::table('metrics', function (Blueprint $table) {
269
+
$table->string('source')->nullable()->index();
270
+
$table->string('country')->nullable()->index();
271
+
$table->string('device')->nullable();
272
+
});
273
+
```
274
+
275
+
Then, use the `with()` method to record metrics with custom attributes:
276
+
277
+
```php
278
+
// Track page views with traffic source
279
+
metric('page_views')
280
+
->with(['source' => 'google'])
281
+
->record();
282
+
283
+
// Track conversions with multiple attributes
284
+
metric('conversions')
285
+
->with([
286
+
'source' => 'facebook',
287
+
'country' => 'US',
288
+
'device' => 'mobile',
289
+
])
290
+
->record();
291
+
292
+
// Combine with other methods
293
+
metric('api:requests')
294
+
->category('users')
295
+
->with(['client_id' => 'abc123'])
296
+
->record();
297
+
```
298
+
299
+
Custom attributes are included in the metric's uniqueness check, meaning metrics with different attribute values are stored separately:
You can also use custom attributes with the `MetricData` class:
330
+
331
+
```php
332
+
use DirectoryTree\Metrics\MetricData;
333
+
use DirectoryTree\Metrics\Facades\Metrics;
334
+
335
+
Metrics::record(new MetricData(
336
+
name: 'page_views',
337
+
additional: [
338
+
'source' => 'google',
339
+
'country' => 'US',
340
+
]
341
+
));
342
+
```
343
+
344
+
Or with the `PendingMetric` class:
345
+
346
+
```php
347
+
use DirectoryTree\Metrics\PendingMetric;
348
+
349
+
PendingMetric::make('page_views')
350
+
->with(['source' => 'google', 'country' => 'US'])
351
+
->record();
352
+
```
353
+
354
+
> [!important]
355
+
> Core metric attributes (`name`, `category`, `year`, `month`, `day`, `measurable_type`, `measurable_id`, `value`) cannot be overridden via custom attributes. They are protected and will always use the values set through their respective methods.
356
+
257
357
### Capturing & Committing
258
358
259
359
For high-performance scenarios, you may capture metrics in memory and commit them in batches:
0 commit comments