rails_semantic_logger 5.2.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '08056406dee88f7c5eb0d29107d9d82b95487cf913ace9a6dd292c49641f58c4'
4
- data.tar.gz: 5dfdb7970f4baf88676218aa9a0778245957c094dc1ee7103e7940c456a54e06
3
+ metadata.gz: 1a527b731a1597ede198e3b03639185480bf5b9d047ba77bfd7c3a2380496449
4
+ data.tar.gz: d314667c79d39c4e03a469a5f0ed87471731127f9a66a55fd3ee3e6ec78189f1
5
5
  SHA512:
6
- metadata.gz: e138fdae60edf8a40b1e0b57d4b351bc0069b48550f0ecd0ee443ef8bbb154984c8923a07632d441cf154b39f7777e266073254f6cd57bd6bf83c26dd59c5b63
7
- data.tar.gz: 5e7e1e27aded0d3a1731cab0f756dfada2d11dcf1f2a756bd41ecfa912c44f9931649df0a2e56f32d21328a64f22db1a9f97c02c6ac939f17974342f4805c7d8
6
+ metadata.gz: 6bd94d95dd37a0650e4ca44f32943db61e7891f0a120e4413a65d0a44fd9f43a99984cb043d7d054622befb664d7b4929cb58e5acd44ae1ffd26d7dd569df0bc
7
+ data.tar.gz: f80309e11fb62853276e4f2aa38f76a9a9742c0223f2442ce9a6d42c12a6fd1b6c4b257040afa6162517a0d0aae9fa76d54dc8d9060bfd9ba344d013748452e7
data/Rakefile CHANGED
@@ -27,10 +27,21 @@ end
27
27
  require "rubocop/rake_task"
28
28
  RuboCop::RakeTask.new
29
29
 
30
- # By default lint once, then run tests against all appraisals
30
+ # By default lint once, then run tests against every released Rails version. Rails edge is
31
+ # left out because it tracks rails/rails main; run it with `appraisal rails_edge rake test`.
31
32
  if !ENV["APPRAISAL_INITIALIZED"] && !ENV["TRAVIS"]
32
33
  require "appraisal"
33
- task default: %i[rubocop appraisal]
34
+
35
+ desc "Run the tests against every released Rails version (all appraisals except rails_edge)"
36
+ task :released do
37
+ Appraisal::AppraisalFile.each do |appraisal|
38
+ next if appraisal.name == "rails_edge"
39
+
40
+ sh "bundle exec appraisal #{appraisal.name} rake test"
41
+ end
42
+ end
43
+
44
+ task default: %i[rubocop released]
34
45
  else
35
46
  task default: :test
36
47
  end
@@ -12,7 +12,10 @@ module RailsSemanticLogger
12
12
  class LogSubscriber < ActiveSupport::LogSubscriber
13
13
  INTERNAL_PARAMS = %w[controller action format _method only_path].freeze
14
14
 
15
- class_attribute :backtrace_cleaner, default: ActiveSupport::BacktraceCleaner.new
15
+ # The application's, as Rails 8.1+ gives its own Action Controller log subscriber, on every
16
+ # supported Rails version: the backtraces logged here are relative to Rails.root and follow the
17
+ # application's backtrace silencers.
18
+ class_attribute :backtrace_cleaner, default: ::Rails.backtrace_cleaner
16
19
 
17
20
  class << self
18
21
  attr_accessor :action_message_format, :processing_log_level
@@ -23,11 +26,16 @@ module RailsSemanticLogger
23
26
  @processing_log_level = :debug
24
27
 
25
28
  def start_processing(event)
26
- controller_logger(event).send(self.class.processing_log_level) { action_message("Processing", event.payload) }
29
+ logger = controller_logger(event)
30
+ level = self.class.processing_log_level
31
+ logger&.send(level, call_site: call_site(event, logger, level, from_stack: false)) do
32
+ action_message("Processing", event.payload)
33
+ end
27
34
  end
28
35
 
29
36
  def process_action(event)
30
- controller_logger(event).info do
37
+ logger = controller_logger(event)
38
+ logger&.info(call_site: call_site(event, logger, :info, from_stack: false)) do
31
39
  # `event.payload` is shared with every other subscriber on this notification, so we work on
32
40
  # a copy. A shallow `dup` is sufficient: only mutate `payload` via top-level key reassignment
33
41
  # (e.g. `payload[:format] = ...`) or by writing into a freshly-created hash (e.g. the `.except`
@@ -92,7 +100,8 @@ module RailsSemanticLogger
92
100
  end
93
101
 
94
102
  def halted_callback(event)
95
- controller_logger(event).info do
103
+ logger = controller_logger(event)
104
+ logger&.info(call_site: call_site(event, logger, :info, from_stack: false)) do
96
105
  {
97
106
  message: "Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected",
98
107
  metric: "rails.controller.halted_callback"
@@ -103,8 +112,11 @@ module RailsSemanticLogger
103
112
  # Rails 8.1+ emits this event when an exception is handled by a `rescue_from` callback.
104
113
  # On earlier Rails versions the event is never instrumented, so this handler is dormant.
105
114
  def rescue_from_callback(event)
106
- controller_logger(event).info do
107
- exception = event.payload[:exception]
115
+ logger = controller_logger(event)
116
+ exception = event.payload[:exception]
117
+ return unless logger
118
+
119
+ logger.info(call_site: RailsSemanticLogger.exception_call_site(exception, backtrace_cleaner, logger, :info)) do
108
120
  backtrace = exception.backtrace&.first
109
121
  backtrace = backtrace&.delete_prefix("#{Rails.root}/") if defined?(Rails.root) && Rails.root
110
122
 
@@ -121,39 +133,74 @@ module RailsSemanticLogger
121
133
  end
122
134
 
123
135
  def send_file(event)
124
- controller_logger(event).info(message: "Sent file",
125
- payload: {path: event.payload[:path]},
126
- duration: event.duration,
127
- metric: "rails.controller.send_file")
136
+ logger = controller_logger(event)
137
+ logger&.info(message: "Sent file", payload: {path: event.payload[:path]}, duration: event.duration,
138
+ metric: "rails.controller.send_file", call_site: call_site(event, logger, :info))
128
139
  end
129
140
 
130
141
  def redirect_to(event)
131
142
  payload = {location: event.payload[:location]}
132
143
 
133
144
  # Rails 8.1+ optionally logs the source location of the redirect when
134
- # ActionDispatch.verbose_redirect_logs is enabled.
145
+ # ActionDispatch.verbose_redirect_logs is enabled. The same frame is the entry's call site.
135
146
  if ActionDispatch.respond_to?(:verbose_redirect_logs) && ActionDispatch.verbose_redirect_logs
136
- source = redirect_source_location
147
+ frame = RailsSemanticLogger::ApplicationFrame.on_stack(backtrace_cleaner, for_source: true)
148
+ source = frame.source
137
149
  payload[:source] = source if source
138
150
  end
139
151
 
140
- controller_logger(event).info(message: "Redirected to", payload: payload,
141
- metric: "rails.controller.redirect_to")
152
+ logger = controller_logger(event)
153
+ logger&.info(message: "Redirected to", payload: payload, metric: "rails.controller.redirect_to",
154
+ call_site: call_site(event, logger, :info, frame: frame))
155
+ end
156
+
157
+ # Rails 8.1+ emits this event for a redirect to another host when
158
+ # `config.action_controller.action_on_open_redirect = :notify`. Rails' text subscriber never
159
+ # logs it: on Rails 8.1 nothing subscribes to it, and on Rails 8.2 only its
160
+ # StructuredEventSubscriber reports it, to `Rails.event`. So it is logged here at :warn, the
161
+ # level Rails uses for `action_on_open_redirect = :log`.
162
+ def open_redirect(event)
163
+ request = event.payload[:request]
164
+
165
+ log_redirect_warning(
166
+ event,
167
+ message: "Open redirect detected",
168
+ payload: {
169
+ location: event.payload[:location],
170
+ request_method: request&.method,
171
+ request_path: request&.path
172
+ }.compact,
173
+ metric: "rails.controller.open_redirect"
174
+ )
175
+ end
176
+
177
+ # Rails 8.1+ emits this event for a path relative redirect, such as `redirect_to "foo"`, when
178
+ # `config.action_controller.action_on_path_relative_redirect = :notify`. No Rails subscriber
179
+ # logs it, so it is logged here at :warn, the level Rails uses for `:log`.
180
+ def unsafe_redirect(event)
181
+ log_redirect_warning(
182
+ event,
183
+ message: event.payload[:message],
184
+ payload: {url: event.payload[:url]},
185
+ metric: "rails.controller.unsafe_redirect"
186
+ )
142
187
  end
143
188
 
144
189
  def send_data(event)
145
- controller_logger(event).info(message: "Sent data",
146
- payload: {file_name: event.payload[:filename]},
147
- duration: event.duration,
148
- metric: "rails.controller.send_data")
190
+ logger = controller_logger(event)
191
+ logger&.info(message: "Sent data", payload: {file_name: event.payload[:filename]}, duration: event.duration,
192
+ metric: "rails.controller.send_data", call_site: call_site(event, logger, :info))
149
193
  end
150
194
 
151
195
  def unpermitted_parameters(event)
152
- controller_logger(event).debug do
196
+ logger = controller_logger(event)
197
+ logger&.debug(call_site: call_site(event, logger, :debug)) do
153
198
  unpermitted_keys = event.payload[:keys]
154
199
  payload = {keys: unpermitted_keys}
155
- # Rails includes the controller/action context alongside the rejected keys.
156
- payload[:context] = event.payload[:context] if event.payload[:context]
200
+ # Rails includes the controller/action context alongside the rejected keys. Leave out the
201
+ # request, as Rails' structured event subscriber does: it refers back to itself, so a JSON
202
+ # formatter overflows the stack on it.
203
+ payload[:context] = event.payload[:context].except(:request) if event.payload[:context]
157
204
 
158
205
  {
159
206
  message: "Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.join(', ')}",
@@ -162,12 +209,28 @@ module RailsSemanticLogger
162
209
  end
163
210
  end
164
211
 
212
+ # Rails 8.2+ reports CSRF failures through these events instead of calling `logger.warn`
213
+ # directly from RequestForgeryProtection. On earlier Rails versions the events are never
214
+ # instrumented, so these handlers are dormant.
215
+ def csrf_token_fallback(event)
216
+ log_csrf_warning(__method__, event, "Falling back to CSRF token verification")
217
+ end
218
+
219
+ def csrf_request_blocked(event)
220
+ log_csrf_warning(__method__, event, event.payload[:message])
221
+ end
222
+
223
+ def csrf_javascript_blocked(event)
224
+ log_csrf_warning(__method__, event, event.payload[:message])
225
+ end
226
+
165
227
  %w[write_fragment read_fragment exist_fragment?
166
228
  expire_fragment expire_page write_page].each do |method|
167
229
  class_eval <<-METHOD, __FILE__, __LINE__ + 1
168
230
  def #{method}(event)
169
231
  return unless ::ActionController::Base.enable_fragment_cache_logging
170
- controller_logger(event).info do
232
+ logger = controller_logger(event)
233
+ logger&.info(call_site: call_site(event, logger, :info)) do
171
234
  key_or_path = event.payload[:key] || event.payload[:path]
172
235
  {message: "#{method.to_s.humanize} \#{key_or_path}", duration: event.duration, metric: "rails.controller.#{method.delete('?')}"}
173
236
  end
@@ -177,15 +240,126 @@ module RailsSemanticLogger
177
240
 
178
241
  private
179
242
 
180
- # Returns the logger for the supplied event.
181
- # Returns ActionController::Base.logger if no controller is present
243
+ # Returns the call site of an entry about the event logged at the level, or nil when the entry
244
+ # records none (see RailsSemanticLogger.call_site?).
245
+ #
246
+ # With from_stack, for an event that the action itself causes, such as a redirect_to call, it
247
+ # is the first frame of the application's code on the stack. Otherwise, or without one, it is
248
+ # where the controller defines its action, since Rails reports events such as a completed
249
+ # action once the action has returned. False when neither is known, so that the entry records
250
+ # no call site rather than Active Support's frame.
251
+ #
252
+ # The frame, a RailsSemanticLogger::ApplicationFrame, is the one already found for the entry's
253
+ # source, if any.
254
+ def call_site(event, logger, level, from_stack: true, frame: nil)
255
+ return unless logger && RailsSemanticLogger.call_site?(logger, level)
256
+
257
+ frame ||= RailsSemanticLogger::ApplicationFrame.on_stack(backtrace_cleaner) if from_stack
258
+ frame&.call_site || action_call_site(event.payload) || false
259
+ end
260
+
261
+ # Returns [SemanticLogger::CallSite|nil] where the controller handling the event defines its
262
+ # action. Most events carry the request, which knows its controller; the unpermitted parameters
263
+ # and CSRF events name the controller and action instead.
264
+ def action_call_site(payload)
265
+ controller = payload[:request]&.controller_instance
266
+ return RailsSemanticLogger.method_call_site(controller.class, controller.action_name) if controller
267
+
268
+ names = payload[:context] || payload
269
+ controller = names[:controller].is_a?(String) ? names[:controller].safe_constantize : nil
270
+ RailsSemanticLogger.method_call_site(controller, names[:action]) if controller && names[:action]
271
+ end
272
+
273
+ # Returns the logger of the controller that emitted the event, or ActionController::Base.logger
274
+ # when the event names no controller or it cannot be found. Like Rails, which skips logging
275
+ # when there is no logger, callers must allow for nil.
182
276
  def controller_logger(event)
183
- controller = event.payload[:controller]
184
- return ::ActionController::Base.logger unless controller
277
+ controller_class(event.payload)&.logger || ::ActionController::Base.logger
278
+ end
185
279
 
186
- controller.constantize.logger || ::ActionController::Base.logger
280
+ # Most events name their controller. The redirect events carry only the request, which knows
281
+ # the controller handling it.
282
+ def controller_class(payload)
283
+ if payload[:controller]
284
+ payload[:controller].constantize
285
+ else
286
+ payload[:request]&.controller_instance&.class
287
+ end
187
288
  rescue NameError
188
- ::ActionController::Base.logger
289
+ nil
290
+ end
291
+
292
+ # Removes framework and gem frames, leaving the application code that caused the event.
293
+ #
294
+ # When cleaning removes every frame, as for a redirect issued by an engine's controller, it
295
+ # keeps instead the frames from the first one in a file that defines the controller's action,
296
+ # or every frame when there is no such frame. They keep their gem paths shortened, and none is
297
+ # silenced. Formatters show the first frame as the entry's file and line, so the entry still
298
+ # shows where the action redirected.
299
+ def clean_backtrace(backtrace, controller = nil)
300
+ return unless backtrace
301
+
302
+ cleaned = backtrace_cleaner.clean(backtrace)
303
+ return cleaned unless cleaned.empty?
304
+
305
+ prefixes = action_files(controller).map { |file| "#{file}:" }
306
+ from_action = backtrace.drop_while { |frame| prefixes.none? { |prefix| frame.to_s.start_with?(prefix) } }
307
+ backtrace_cleaner.clean(from_action.presence || backtrace, :all)
308
+ end
309
+
310
+ # Returns the files that define the action the controller is handling: those of the action's
311
+ # method, of any method that wraps it from a prepended module, and of any it overrides. Empty
312
+ # when there is no controller or its action is not a method, as for an action that only renders
313
+ # a template. A wrapper that replaces the method, instead of calling it with super, hides the
314
+ # files below it.
315
+ def action_files(controller)
316
+ action = controller&.action_name
317
+ return [] unless action
318
+
319
+ method = controller.class.instance_method(action)
320
+ files = []
321
+ while method
322
+ files << method.source_location&.first
323
+ method = method.super_method
324
+ end
325
+ files.compact
326
+ rescue NameError
327
+ []
328
+ end
329
+
330
+ # Logs a redirect event at :warn with the redirect's stack trace, cleaned by #clean_backtrace,
331
+ # as the entry's backtrace. The backtrace goes with the log call rather than in a logging block's
332
+ # result: since semantic_logger 5.2 a block cannot replace a backtrace the entry already has,
333
+ # and the entry captures this subscriber's own stack whenever :warn is at or above the
334
+ # `backtrace_level`, as it is in the Rails console.
335
+ def log_redirect_warning(event, message:, payload:, metric:)
336
+ logger = controller_logger(event)
337
+ return unless logger&.warn?
338
+
339
+ controller = event.payload[:request]&.controller_instance
340
+ logger.warn(message: message,
341
+ payload: payload,
342
+ backtrace: clean_backtrace(event.payload[:stack_trace], controller),
343
+ metric: metric)
344
+ end
345
+
346
+ # Rails logs every CSRF event at :warn, and only while log_warning_on_csrf_failure is on.
347
+ def log_csrf_warning(event_name, event, message)
348
+ return unless ::ActionController::Base.log_warning_on_csrf_failure
349
+
350
+ logger = controller_logger(event)
351
+ logger&.warn(call_site: call_site(event, logger, :warn, from_stack: false)) do
352
+ payload = event.payload
353
+ {
354
+ message: message,
355
+ payload: {
356
+ controller: payload[:controller],
357
+ action: payload[:action],
358
+ sec_fetch_site: payload[:sec_fetch_site]
359
+ }.compact,
360
+ metric: "rails.controller.#{event_name}"
361
+ }
362
+ end
189
363
  end
190
364
 
191
365
  def extract_path(path)
@@ -193,11 +367,6 @@ module RailsSemanticLogger
193
367
  index ? path[0, index] : path
194
368
  end
195
369
 
196
- # Rails 8.1+ BacktraceCleaner exposes #first_clean_frame for verbose redirect logging.
197
- def redirect_source_location
198
- backtrace_cleaner.first_clean_frame if backtrace_cleaner.respond_to?(:first_clean_frame)
199
- end
200
-
201
370
  def action_message(message, payload)
202
371
  if self.class.action_message_format
203
372
  self.class.action_message_format.call(message, payload)
@@ -13,6 +13,9 @@ require "action_mailer"
13
13
  module RailsSemanticLogger
14
14
  module ActionMailer
15
15
  class LogSubscriber < ::ActiveSupport::LogSubscriber
16
+ # The application's, to find the application code that sent the mail.
17
+ class_attribute :backtrace_cleaner, default: ::Rails.backtrace_cleaner
18
+
16
19
  def deliver(event)
17
20
  # Rails gates this event with `subscribe_log_level :deliver, :debug`, so the upstream
18
21
  # subscriber only runs when the logger is at debug level (or lower). Match that here.
@@ -136,7 +139,24 @@ module RailsSemanticLogger
136
139
  # Emit a metric for every info/warn/error entry, named after the notification
137
140
  # (e.g. "deliver.action_mailer" -> "rails.mailer.deliver"). Debug entries (process) are excluded.
138
141
  msg[:metric] ||= "rails.mailer.#{kw_args[:event].name.split('.').first}" unless level == :debug
139
- logger.public_send(level, **msg, payload: fmt.payload)
142
+ logger.public_send(level, **msg, payload: fmt.payload, call_site: call_site(kw_args[:event], level))
143
+ end
144
+
145
+ # Returns the call site of an entry about the event logged at the level, or nil when it records
146
+ # none: the application code on the stack, such as the code that called deliver_now, else where
147
+ # the mailer defines the action that built the mail, as for mail delivered by a job, else false,
148
+ # so that the entry records no call site rather than Active Support's frame.
149
+ def call_site(event, level)
150
+ return unless RailsSemanticLogger.call_site?(logger, level)
151
+
152
+ RailsSemanticLogger::ApplicationFrame.on_stack(backtrace_cleaner).call_site ||
153
+ mailer_action_call_site(event.payload) || false
154
+ end
155
+
156
+ # Only the process event names the action.
157
+ def mailer_action_call_site(payload)
158
+ mailer = payload[:mailer].is_a?(String) ? payload[:mailer].safe_constantize : nil
159
+ RailsSemanticLogger.method_call_site(mailer, payload[:action]) if mailer && payload[:action]
140
160
  end
141
161
 
142
162
  def logger
@@ -18,9 +18,30 @@ module RailsSemanticLogger
18
18
  class LogSubscriber < ActiveSupport::LogSubscriber
19
19
  VIEWS_PATTERN = %r{^app/views/}
20
20
 
21
+ # The application's, to find the application code that rendered a template: the action, or
22
+ # the template that rendered a partial.
23
+ class_attribute :backtrace_cleaner, default: ::Rails.backtrace_cleaner
24
+
21
25
  class << self
22
- attr_reader :logger
23
26
  attr_accessor :rendered_log_level
27
+
28
+ # Looked up on first use rather than when this file loads: referencing ActionView::Base
29
+ # loads it, and Rails 8.2+ reports that when it happens before the application has
30
+ # initialized.
31
+ def logger
32
+ @logger ||= ::ActionView::Base.logger
33
+ end
34
+
35
+ # Returns the call site of a render entry that the logger logs at the level, or nil when it
36
+ # records none: the application code that rendered the template, such as the action that
37
+ # called render, or the template that rendered a partial. False when there is none, as for a
38
+ # template that Rails renders once the action has returned, even inside an around_action, so
39
+ # that the entry records no call site rather than Active Support's frame (see ApplicationFrame).
40
+ def call_site(logger, level)
41
+ return unless RailsSemanticLogger.call_site?(logger, level)
42
+
43
+ RailsSemanticLogger::ApplicationFrame.on_stack(backtrace_cleaner).call_site || false
44
+ end
24
45
  end
25
46
 
26
47
  def initialize
@@ -41,9 +62,10 @@ module RailsSemanticLogger
41
62
  logger.measure(
42
63
  self.class.rendered_log_level,
43
64
  "Rendered",
44
- payload: payload,
45
- duration: event.duration,
46
- metric: "rails.view.render.template"
65
+ payload: payload,
66
+ duration: event.duration,
67
+ metric: "rails.view.render.template",
68
+ call_site: call_site
47
69
  )
48
70
  end
49
71
 
@@ -61,9 +83,10 @@ module RailsSemanticLogger
61
83
  logger.measure(
62
84
  self.class.rendered_log_level,
63
85
  "Rendered",
64
- payload: payload,
65
- duration: event.duration,
66
- metric: "rails.view.render.partial"
86
+ payload: payload,
87
+ duration: event.duration,
88
+ metric: "rails.view.render.partial",
89
+ call_site: call_site
67
90
  )
68
91
  end
69
92
 
@@ -79,9 +102,10 @@ module RailsSemanticLogger
79
102
  logger.measure(
80
103
  self.class.rendered_log_level,
81
104
  "Rendered layout",
82
- payload: payload,
83
- duration: event.duration,
84
- metric: "rails.view.render.layout"
105
+ payload: payload,
106
+ duration: event.duration,
107
+ metric: "rails.view.render.layout",
108
+ call_site: call_site
85
109
  )
86
110
  end
87
111
 
@@ -101,9 +125,10 @@ module RailsSemanticLogger
101
125
  logger.measure(
102
126
  self.class.rendered_log_level,
103
127
  "Rendered",
104
- payload: payload,
105
- duration: event.duration,
106
- metric: "rails.view.render.collection"
128
+ payload: payload,
129
+ duration: event.duration,
130
+ metric: "rails.view.render.collection",
131
+ call_site: call_site
107
132
  )
108
133
  end
109
134
 
@@ -113,7 +138,8 @@ module RailsSemanticLogger
113
138
  payload = {template: from_rails_root(payload[:identifier])}
114
139
  payload[:within] = from_rails_root(payload[:layout]) if payload[:layout]
115
140
 
116
- logger.send(self.class.rendered_log_level, message: "Rendering#{qualifier}", payload: payload)
141
+ logger.send(self.class.rendered_log_level, message: "Rendering#{qualifier}", payload: payload,
142
+ call_site: call_site)
117
143
  end
118
144
 
119
145
  super
@@ -127,7 +153,7 @@ module RailsSemanticLogger
127
153
  payload = {template: from_rails_root(payload[:identifier])}
128
154
  payload[:within] = from_rails_root(payload[:layout]) if payload[:layout]
129
155
 
130
- logger.debug(message: "Rendering#{qualifier}", payload: payload)
156
+ logger.debug(message: "Rendering#{qualifier}", payload: payload, call_site: call_site)
131
157
  end
132
158
 
133
159
  def finish(name, id, payload)
@@ -148,6 +174,10 @@ module RailsSemanticLogger
148
174
  def logger
149
175
  @logger ||= ::ActionView::Base.logger
150
176
  end
177
+
178
+ def call_site
179
+ LogSubscriber.call_site(logger, :debug)
180
+ end
151
181
  end
152
182
 
153
183
  def self.attach_to(*)
@@ -163,7 +193,6 @@ module RailsSemanticLogger
163
193
 
164
194
  EMPTY = "".freeze
165
195
 
166
- @logger = ::ActionView::Base.logger
167
196
  @rendered_log_level = :debug
168
197
 
169
198
  private
@@ -185,6 +214,10 @@ module RailsSemanticLogger
185
214
  def logger
186
215
  self.class.logger
187
216
  end
217
+
218
+ def call_site
219
+ self.class.call_site(logger, self.class.rendered_log_level)
220
+ end
188
221
  end
189
222
  end
190
223
  end
@@ -17,16 +17,27 @@ require "active_job"
17
17
  # The Continuation handlers are defined unconditionally. On Rails < 8.1 those notifications are
18
18
  # never emitted, so the extra methods are simply never invoked.
19
19
  #
20
+ # When `verbose_enqueue_logs` is on, Rails logs a "↳ source" line, the first frame of the call stack
21
+ # that the backtrace cleaner keeps, after every info and error line of its subscriber. This
22
+ # subscriber adds it to the payload of the same entries, as `source`. For an enqueue it is the code
23
+ # that enqueued the job. A job performed by a worker has no application frame on its call stack
24
+ # outside the job itself, so its perform entries get none, while its Continuation step entries
25
+ # (Rails 8.1+), instrumented inside the job's own perform, get the job's line. A job performed
26
+ # inline, such as with `perform_now`, gets the code that performed it.
27
+ #
20
28
  module RailsSemanticLogger
21
29
  module ActiveJob
22
30
  class LogSubscriber < ::ActiveSupport::LogSubscriber
31
+ # The application's, as Rails gives its own Active Job log subscriber.
32
+ class_attribute :backtrace_cleaner, default: ::Rails.backtrace_cleaner
33
+
23
34
  def enqueue(event)
24
35
  ex = enqueue_error(event)
25
36
 
26
37
  if ex
27
38
  log_with_formatter level: :error, event: event do |fmt|
28
39
  {
29
- message: "Failed enqueuing #{fmt.job_info} (#{ex.class} (#{ex.message})",
40
+ message: "Failed enqueuing #{fmt.job_info}: #{ex.class} (#{ex.message})",
30
41
  exception: ex
31
42
  }
32
43
  end
@@ -47,7 +58,7 @@ module RailsSemanticLogger
47
58
  if ex
48
59
  log_with_formatter level: :error, event: event do |fmt|
49
60
  {
50
- message: "Failed enqueuing #{fmt.job_info} (#{ex.class} (#{ex.message})",
61
+ message: "Failed enqueuing #{fmt.job_info}: #{ex.class} (#{ex.message})",
51
62
  exception: ex
52
63
  }
53
64
  end
@@ -231,17 +242,20 @@ module RailsSemanticLogger
231
242
  "Failed enqueuing #{failed_count} #{'job'.pluralize(failed_count)} to #{adapter_name}"
232
243
  end
233
244
 
234
- logger.info(
235
- message: message,
236
- metric: "rails.job.enqueue_all",
237
- payload: {
238
- event_name: event.name,
239
- adapter: adapter_name,
240
- enqueued_count: enqueued_count,
241
- total_count: jobs.size,
242
- job_classes: jobs.map { |job| job.class.name }.tally
243
- }
244
- )
245
+ payload = {
246
+ event_name: event.name,
247
+ adapter: adapter_name,
248
+ enqueued_count: enqueued_count,
249
+ total_count: jobs.size,
250
+ job_classes: jobs.map { |job| job.class.name }.tally
251
+ }
252
+ frame = application_frame(:info)
253
+ source = frame&.source if enqueue_source?(:info)
254
+ payload[:source] = source if source
255
+ # No call site when no application code enqueued the jobs, rather than Active Support's frame.
256
+ call_site = frame&.call_site || false if RailsSemanticLogger.call_site?(logger, :info)
257
+
258
+ logger.info(message: message, metric: "rails.job.enqueue_all", payload: payload, call_site: call_site)
245
259
  end
246
260
 
247
261
  private
@@ -356,7 +370,41 @@ module RailsSemanticLogger
356
370
  # Emit a metric for every info/warn/error entry, named after the notification
357
371
  # (e.g. "enqueue.active_job" -> "rails.job.enqueue"). Debug entries are excluded.
358
372
  msg[:metric] ||= "rails.job.#{kw_args[:event].name.split('.').first}" unless level == :debug
359
- logger.public_send(level, **msg, payload: fmt.payload.merge(extra))
373
+ frame = application_frame(level)
374
+ source = frame&.source if enqueue_source?(level)
375
+ extra = extra.merge(source: source) if source
376
+ logger.public_send(
377
+ level,
378
+ **msg,
379
+ payload: fmt.payload.merge(extra),
380
+ call_site: call_site(frame, kw_args[:event], level)
381
+ )
382
+ end
383
+
384
+ # Returns [ApplicationFrame|nil] the application code behind an entry logged at the level, such as
385
+ # the code that enqueued or performed the job, when the entry needs it: as its source when
386
+ # `verbose_enqueue_logs` is on, or as its call site. nil when it needs neither.
387
+ def application_frame(level)
388
+ return unless enqueue_source?(level) || RailsSemanticLogger.call_site?(logger, level)
389
+
390
+ RailsSemanticLogger::ApplicationFrame.on_stack(backtrace_cleaner, for_source: enqueue_source?(level))
391
+ end
392
+
393
+ # Whether an entry logged at the level has a source: `verbose_enqueue_logs` is on, and Rails logs
394
+ # its "↳ source" below the entry, which it does for info and error lines, and the logger logs it.
395
+ def enqueue_source?(level)
396
+ ::ActiveJob.verbose_enqueue_logs && %i[info error].include?(level) && logger.public_send(:"#{level}?")
397
+ end
398
+
399
+ # Returns the call site of an entry logged at the level about the event's job, or nil when it
400
+ # records none: the application code behind it, such as the code that called perform_now, else
401
+ # the job's #perform, as for a job performed from its queue, else false, so that the entry records
402
+ # no call site rather than Active Support's frame.
403
+ def call_site(frame, event, level)
404
+ return unless RailsSemanticLogger.call_site?(logger, level)
405
+
406
+ job = event.payload[:job]
407
+ frame&.call_site || (job && RailsSemanticLogger.method_call_site(job.class, :perform)) || false
360
408
  end
361
409
 
362
410
  def logger