aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_support_instrumentation.md
blob: 9f15e70da69ac6e496d0a94d48325ad1241f6534 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**

Active Support Instrumentation
==============================

Active Support is a part of core Rails that provides Ruby language extensions, utilities, and other things. One of the things it includes is an instrumentation API that can be used inside an application to measure certain actions that occur within Ruby code, such as that inside a Rails application or the framework itself. It is not limited to Rails, however. It can be used independently in other Ruby scripts if it is so desired.

In this guide, you will learn how to use the instrumentation API inside of Active Support to measure events inside of Rails and other Ruby code.

After reading this guide, you will know:

* What instrumentation can provide.
* The hooks inside the Rails framework for instrumentation.
* Adding a subscriber to a hook.
* Building a custom instrumentation implementation.

--------------------------------------------------------------------------------

Introduction to instrumentation
-------------------------------

The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the [Rails framework](#rails-framework-hooks). With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.

For example, there is a hook provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's another hook around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.

You are even able to create your own events inside your application which you can later subscribe to.

Rails framework hooks
---------------------

Within the Ruby on Rails framework, there are a number of hooks provided for common events. These are detailed below.

Action Controller
-----------------

### write_fragment.action_controller

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```ruby
{
  key: 'posts/1-dashboard-view'
}
```

### read_fragment.action_controller

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```ruby
{
  key: 'posts/1-dashboard-view'
}
```

### expire_fragment.action_controller

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```ruby
{
  key: 'posts/1-dashboard-view'
}
```

### exist_fragment?.action_controller

| Key    | Value            |
| ------ | ---------------- |
| `:key` | The complete key |

```ruby
{
  key: 'posts/1-dashboard-view'
}
```

### write_page.action_controller

| Key     | Value             |
| ------- | ----------------- |
| `:path` | The complete path |

```ruby
{
  path: '/users/1'
}
```

### expire_page.action_controller

| Key     | Value             |
| ------- | ----------------- |
| `:path` | The complete path |

```ruby
{
  path: '/users/1'
}
```

### start_processing.action_controller

| Key           | Value                                                     |
| ------------- | --------------------------------------------------------- |
| `:controller` | The controller name                                       |
| `:action`     | The action                                                |
| `:params`     | Hash of request parameters without any filtered parameter |
| `:headers`    | Request headers                                           |
| `:format`     | html/js/json/xml etc                                      |
| `:method`     | HTTP request verb                                         |
| `:path`       | Request path                                              |

```ruby
{
  controller: "PostsController",
  action: "new",
  params: { "action" => "new", "controller" => "posts" },
  headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
  format: :html,
  method: "GET",
  path: "/posts/new"
}
```

### process_action.action_controller

| Key             | Value                                                     |
| --------------- | --------------------------------------------------------- |
| `:controller`   | The controller name                                       |
| `:action`       | The action                                                |
| `:params`       | Hash of request parameters without any filtered parameter |
| `:headers`      | Request headers                                           |
| `:format`       | html/js/json/xml etc                                      |
| `:method`       | HTTP request verb                                         |
| `:path`         | Request path                                              |
| `:status`       | HTTP status code                                          |
| `:view_runtime` | Amount spent in view in ms                                |
| `:db_runtime`   | Amount spent executing database queries in ms             |

```ruby
{
  controller: "PostsController",
  action: "index",
  params: {"action" => "index", "controller" => "posts"},
  headers: #<ActionDispatch::Http::Headers:0x0055a67a519b88>,
  format: :html,
  method: "GET",
  path: "/posts",
  status: 200,
  view_runtime: 46.848,
  db_runtime: 0.157
}
```

### send_file.action_controller

| Key     | Value                     |
| ------- | ------------------------- |
| `:path` | Complete path to the file |

INFO. Additional keys may be added by the caller.

### send_data.action_controller

`ActionController` does not add any specific information to the payload. All options are passed through to the payload.

### redirect_to.action_controller

| Key         | Value              |
| ----------- | ------------------ |
| `:status`   | HTTP response code |
| `:location` | URL to redirect to |

```ruby
{
  status: 302,
  location: "http://localhost:3000/posts/new"
}
```

### halted_callback.action_controller

| Key       | Value                         |
| --------- | ----------------------------- |
| `:filter` | Filter that halted the action |

```ruby
{
  filter: ":halting_filter"
}
```

### unpermitted_parameters.action_controller

| Key     | Value            |
| ------- | ---------------- |
| `:keys` | Unpermitted keys |

Action Dispatch
---------------

### process_middleware.action_dispatch

| Key           | Value                  |
| ------------- | ---------------------- |
| `:middleware` | Name of the middleware |

Action View
-----------

### render_template.action_view

| Key           | Value                 |
| ------------- | --------------------- |
| `:identifier` | Full path to template |
| `:layout`     | Applicable layout     |

```ruby
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/index.html.erb",
  layout: "layouts/application"
}
```

### render_partial.action_view

| Key           | Value                 |
| ------------- | --------------------- |
| `:identifier` | Full path to template |

```ruby
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb"
}
```

### render_collection.action_view

| Key           | Value                                 |
| ------------- | ------------------------------------- |
| `:identifier` | Full path to template                 |
| `:count`      | Size of collection                    |
| `:cache_hits` | Number of partials fetched from cache |

`:cache_hits` is only included if the collection is rendered with `cached: true`.

```ruby
{
  identifier: "/Users/adam/projects/notifications/app/views/posts/_post.html.erb",
  count: 3,
  cache_hits: 0
}
```

Active Record
------------

### sql.active_record

| Key                  | Value                                    |
| -------------------- | ---------------------------------------- |
| `:sql`               | SQL statement                            |
| `:name`              | Name of the operation                    |
| `:connection_id`     | Object ID of the connection object       |
| `:connection`        | Connection object                        |
| `:binds`             | Bind parameters                          |
| `:type_casted_binds` | Typecasted bind parameters               |
| `:statement_name`    | SQL Statement name                       |
| `:cached`            | `true` is added when cached queries used |

INFO. The adapters will add their own data as well.

```ruby
{
  sql: "SELECT \"posts\".* FROM \"posts\" ",
  name: "Post Load",
  connection_id: 70307250813140,
  connection: #<ActiveRecord::ConnectionAdapters::SQLite3Adapter:0x00007f9f7a838850>,
  binds: [#<ActiveModel::Attribute::WithCastValue:0x00007fe19d15dc00>],
  type_casted_binds: [11],
  statement_name: nil
}
```

### instantiation.active_record

| Key              | Value                                     |
| ---------------- | ----------------------------------------- |
| `:record_count`  | Number of records that instantiated       |
| `:class_name`    | Record's class                            |

```ruby
{
  record_count: 1,
  class_name: "User"
}
```

Action Mailer
-------------

### deliver.action_mailer

| Key                   | Value                                                |
| --------------------- | ---------------------------------------------------- |
| `:mailer`             | Name of the mailer class                             |
| `:message_id`         | ID of the message, generated by the Mail gem         |
| `:subject`            | Subject of the mail                                  |
| `:to`                 | To address(es) of the mail                           |
| `:from`               | From address of the mail                             |
| `:bcc`                | BCC addresses of the mail                            |
| `:cc`                 | CC addresses of the mail                             |
| `:date`               | Date of the mail                                     |
| `:mail`               | The encoded form of the mail                         |
| `:perform_deliveries` | Whether delivery of this message is performed or not |

```ruby
{
  mailer: "Notification",
  message_id: "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
  subject: "Rails Guides",
  to: ["users@rails.com", "dhh@rails.com"],
  from: ["me@rails.com"],
  date: Sat, 10 Mar 2012 14:18:09 +0100,
  mail: "...", # omitted for brevity
  perform_deliveries: true
}
```

### process.action_mailer

| Key           | Value                    |
| ------------- | ------------------------ |
| `:mailer`     | Name of the mailer class |
| `:action`     | The action               |
| `:args`       | The arguments            |

```ruby
{
  mailer: "Notification",
  action: "welcome_email",
  args: []
}
```

Active Support
--------------

### cache_read.active_support

| Key                | Value                                             |
| ------------------ | ------------------------------------------------- |
| `:key`             | Key used in the store                             |
| `:hit`             | If this read is a hit                             |
| `:super_operation` | :fetch is added when a read is used with `#fetch` |

### cache_generate.active_support

This event is only used when `#fetch` is called with a block.

| Key    | Value                 |
| ------ | --------------------- |
| `:key` | Key used in the store |

INFO. Options passed to fetch will be merged with the payload when writing to the store

```ruby
{
  key: 'name-of-complicated-computation'
}
```


### cache_fetch_hit.active_support

This event is only used when `#fetch` is called with a block.

| Key    | Value                 |
| ------ | --------------------- |
| `:key` | Key used in the store |

INFO. Options passed to fetch will be merged with the payload.

```ruby
{
  key: 'name-of-complicated-computation'
}
```

### cache_write.active_support

| Key    | Value                 |
| ------ | --------------------- |
| `:key` | Key used in the store |

INFO. Cache stores may add their own keys

```ruby
{
  key: 'name-of-complicated-computation'
}
```

### cache_delete.active_support

| Key    | Value                 |
| ------ | --------------------- |
| `:key` | Key used in the store |

```ruby
{
  key: 'name-of-complicated-computation'
}
```

### cache_exist?.active_support

| Key    | Value                 |
| ------ | --------------------- |
| `:key` | Key used in the store |

```ruby
{
  key: 'name-of-complicated-computation'
}
```

Active Job
----------

### enqueue_at.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |

### enqueue.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |

### enqueue_retry.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:job`       | Job object                             |
| `:adapter`   | QueueAdapter object processing the job |
| `:error`     | The error that caused the retry        |
| `:wait`      | The delay of the retry                 |

### perform_start.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |

### perform.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |

### retry_stopped.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |
| `:error`     | The error that caused the retry        |

### discard.active_job

| Key          | Value                                  |
| ------------ | -------------------------------------- |
| `:adapter`   | QueueAdapter object processing the job |
| `:job`       | Job object                             |
| `:error`     | The error that caused the discard      |

Action Cable
------------

### perform_action.action_cable

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |
| `:action`        | The action                |
| `:data`          | A hash of data            |

### transmit.action_cable

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |
| `:data`          | A hash of data            |
| `:via`           | Via                       |

### transmit_subscription_confirmation.action_cable

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |

### transmit_subscription_rejection.action_cable

| Key              | Value                     |
| ---------------- | ------------------------- |
| `:channel_class` | Name of the channel class |

### broadcast.action_cable

| Key             | Value                |
| --------------- | -------------------- |
| `:broadcasting` | A named broadcasting |
| `:message`      | A hash of message    |
| `:coder`        | The coder            |

Active Storage
--------------

### service_upload.active_storage

| Key          | Value                        |
| ------------ | ---------------------------- |
| `:key`       | Secure token                 |
| `:service`   | Name of the service          |
| `:checksum`  | Checksum to ensure integrity |

### service_streaming_download.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:key`       | Secure token        |
| `:service`   | Name of the service |

### service_download_chunk.active_storage

| Key          | Value                           |
| ------------ | ------------------------------- |
| `:key`       | Secure token                    |
| `:service`   | Name of the service             |
| `:range`     | Byte range attempted to be read |

### service_download.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:key`       | Secure token        |
| `:service`   | Name of the service |

### service_delete.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:key`       | Secure token        |
| `:service`   | Name of the service |

### service_delete_prefixed.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:prefix`    | Key prefix          |
| `:service`   | Name of the service |

### service_exist.active_storage

| Key          | Value                       |
| ------------ | --------------------------- |
| `:key`       | Secure token                |
| `:service`   | Name of the service         |
| `:exist`     | File or blob exists or not  |

### service_url.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:key`       | Secure token        |
| `:service`   | Name of the service |
| `:url`       | Generated URL       |

### service_update_metadata.active_storage

| Key             | Value                          |
| --------------- | ------------------------------ |
| `:key`          | Secure token                   |
| `:service`      | Name of the service            |
| `:content_type` | HTTP Content-Type field        |
| `:disposition`  | HTTP Content-Disposition field |

INFO. The only ActiveStorage service that provides this hook so far is GCS.

### preview.active_storage

| Key          | Value               |
| ------------ | ------------------- |
| `:key`       | Secure token        |

Railties
--------

### load_config_initializer.railties

| Key            | Value                                                 |
| -------------- | ----------------------------------------------------- |
| `:initializer` | Path to loaded initializer from `config/initializers` |

Rails
-----

### deprecation.rails

| Key          | Value                           |
| ------------ | ------------------------------- |
| `:message`   | The deprecation warning         |
| `:callstack` | Where the deprecation came from |

Subscribing to an event
-----------------------

Subscribing to an event is easy. Use `ActiveSupport::Notifications.subscribe` with a block to
listen to any notification.

The block receives the following arguments:

* The name of the event
* Time when it started
* Time when it finished
* A unique ID for the instrumenter that fired the event
* The payload (described in previous sections)

```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, started, finished, unique_id, data|
  # your own custom stuff
  Rails.logger.info "#{name} Received! (started: #{started}, finished: #{finished})" # process_action.action_controller Received (started: 2019-05-05 13:43:57 -0800, finished: 2019-05-05 13:43:58 -0800)
end
```

If you are concerned about the accuracy of `started` and `finished` to compute a precise elapsed time then use `ActiveSupport::Notifications.monotonic_subscribe`. The given block would receive the same arguments as above but the `started` and `finished` will have values with an accurate monotonic time instead of wall-clock time.

```ruby
ActiveSupport::Notifications.monotonic_subscribe "process_action.action_controller" do |name, started, finished, unique_id, data|
  # your own custom stuff
  Rails.logger.info "#{name} Received! (started: #{started}, finished: #{finished})" # process_action.action_controller Received (started: 1560978.425334, finished: 1560979.429234)
end
```

Defining all those block arguments each time can be tedious. You can easily create an `ActiveSupport::Notifications::Event`
from block arguments like this:

```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
  event = ActiveSupport::Notifications::Event.new *args

  event.name      # => "process_action.action_controller"
  event.duration  # => 10 (in milliseconds)
  event.payload   # => {:extra=>information}

  Rails.logger.info "#{event} Received!"
end
```

You may also pass block with only one argument, it will yield an event object to the block:

```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |event|
  event.name      # => "process_action.action_controller"
  event.duration  # => 10 (in milliseconds)
  event.payload   # => {:extra=>information}

  Rails.logger.info "#{event} Received!"
end
```

Most times you only care about the data itself. Here is a shortcut to just get the data.

```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
  data = args.extract_options!
  data # { extra: :information }
end
```

You may also subscribe to events matching a regular expression. This enables you to subscribe to
multiple events at once. Here's you could subscribe to everything from `ActionController`.

```ruby
ActiveSupport::Notifications.subscribe /action_controller/ do |*args|
  # inspect all ActionController events
end
```

Creating custom events
----------------------

Adding your own events is easy as well. `ActiveSupport::Notifications` will take care of
all the heavy lifting for you. Simply call `instrument` with a `name`, `payload` and a block.
The notification will be sent after the block returns. `ActiveSupport` will generate the start and end times
and add the instrumenter's unique ID. All data passed into the `instrument` call will make
it into the payload.

Here's an example:

```ruby
ActiveSupport::Notifications.instrument "my.custom.event", this: :data do
  # do your custom stuff here
end
```

Now you can listen to this event with:

```ruby
ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
  puts data.inspect # {:this=>:data}
end
```

You also have the option to call instrument without passing a block. This lets you leverage the
instrumentation infrastructure for other messaging uses.

```ruby
ActiveSupport::Notifications.instrument "my.custom.event", this: :data

ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
  puts data.inspect # {:this=>:data}
end
```

You should follow Rails conventions when defining your own events. The format is: `event.library`.
If your application is sending Tweets, you should create an event named `tweet.twitter`.