rails_semantic_logger 4.14.0 → 4.16.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b41a1fee07d074d18bcaed7538592f123ecbbbe0f232b52cbca96133654ac256
4
- data.tar.gz: df2d6ef10cb8aa051f56a3b916064d1c51afcc3c9ef6f834c2c26be5a3dfc9b4
3
+ metadata.gz: 7da18e2122c13f2b4325a6f3000dd74d22517608b3a32355ca3d2bf4e5f08789
4
+ data.tar.gz: b0503c3227cb0bfa5faa1c6f00b408968783c8d09092a960497ab9f004798875
5
5
  SHA512:
6
- metadata.gz: 70dec27d9976ae2edfc028bdfd03f51b3eade4cf1562681096ba3a882e2f0aacc9fba893cacd5ac7604f3810b2d6e3b880d2411d78a4372ad5b53ab579e41878
7
- data.tar.gz: 635c69136356a8c3ad62a81e0b2db7e397031878619c381fe52240405c2c0b720b9f4900fc2d2ae886d8c23943f8ebd1649444b35357c6178016bb99f036e7dd
6
+ metadata.gz: 30446e6a7553868e37cb56550d0a3e5c15b137991609e2cbb7aee84c7c7f5a75abe0bdd7f5e6263418546645f7a0892472e042ee09e0764be9f0ff9d90311917
7
+ data.tar.gz: 051ff94e24b1d9a4231f01d4148a966333b8d7b57539f7fa15ab953ad0a2fc9c998b61413ae2350716763f323eafa6d7302893b0c7b691e165c2200f7a8f3ef1
data/README.md CHANGED
@@ -3,12 +3,112 @@
3
3
 
4
4
  Rails Semantic Logger replaces the Rails default logger with [Semantic Logger](https://logger.rocketjob.io/)
5
5
 
6
+ When any large Rails application is deployed to production one of the first steps is to move to centralized logging, so that logs can be viewed and searched from a central location.
7
+
8
+ Centralized logging quickly falls apart when trying to consume the current human readable log files:
9
+ - Log entries often span multiple lines, resulting in unrelated log lines in the centralized logging system. For example, stack traces.
10
+ - Complex Regular Expressions are needed to parse the text lines and make them machine readable. For example to build queries, or alerts that are looking for specific elements in the message.
11
+ - Writing searches, alerts, or dashboards based on text logs is incredibly brittle, since a small change to the text logged can often break the parsing of those logs.
12
+ - Every log entry often has a completely different format, making it difficult to make consistent searches against the data.
13
+
14
+ For these and many other reasons switching to structured logging, or logs in JSON format, in testing and production makes centralized logging incredibly powerful.
15
+
16
+ For example, adding these lines to `config/application.rb` and removing any other log overrides from other environments, will switch automatically to structured logging when running inside Kubernetes:
17
+ ~~~ruby
18
+ # Setup structured logging
19
+ config.semantic_logger.application = "my_application"
20
+ config.semantic_logger.environment = ENV["STACK_NAME"] || Rails.env
21
+ config.log_level = ENV["LOG_LEVEL"] || :info
22
+
23
+ # Switch to JSON Logging output to stdout when running on Kubernetes
24
+ if ENV["LOG_TO_CONSOLE"] || ENV["KUBERNETES_SERVICE_HOST"]
25
+ config.rails_semantic_logger.add_file_appender = false
26
+ config.semantic_logger.add_appender(io: $stdout, formatter: :json)
27
+ end
28
+ ~~~
29
+
30
+ Then configure the centralized logging system to tell it that the data is in JSON format, so that it will parse it for you into a hierarchy.
31
+
32
+ For example, the following will instruct [Observe](https://www.observeinc.com/) to parse the JSON data and create machine readable data from it:
33
+ ~~~ruby
34
+ interface "log", "log":log
35
+
36
+ make_col event:parse_json(log)
37
+
38
+ make_col
39
+ time:parse_isotime(event.timestamp),
40
+ application:string(event.application),
41
+ environment:string(event.environment),
42
+ duration:duration_ms(event.duration_ms),
43
+ level:string(event.level),
44
+ name:string(event.name),
45
+ message:string(event.message),
46
+ named_tags:event.named_tags,
47
+ payload:event.payload,
48
+ metric:string(event.metric),
49
+ metric_amount:float64(event.metric_amount),
50
+ tags:array(event.tags),
51
+ exception:event.exception,
52
+ host:string(event.host),
53
+ pid:int64(event.pid),
54
+ thread:string(event.thread),
55
+ file:string(event.file),
56
+ line:int64(event.line),
57
+ dimensions:event.dimensions,
58
+ backtrace:array(event.backtrace),
59
+ level_index:int64(event.level_index)
60
+
61
+ set_valid_from(time)
62
+ drop_col timestamp, log, event, stream
63
+ rename_col timestamp:time
64
+ ~~~
65
+
66
+ Now queries can be built to drill down into each of these fields, including `payload` which is a nested object.
67
+
68
+ For example to find all failed Sidekiq job calls where the causing exception class name is `NoMethodError`:
69
+ ~~~ruby
70
+ filter environment = "uat2"
71
+ filter level = "error"
72
+ filter metric = "sidekiq.job.perform"
73
+ filter (string(exception.cause.name) = "NoMethodError")
74
+ ~~~
75
+
76
+ Example: create a dashboard showing the duration of all successful Sidekiq jobs:
77
+ ~~~ruby
78
+ filter environment = "production"
79
+ filter level = "info"
80
+ filter metric = "sidekiq.job.perform"
81
+ timechart duration:avg(duration), group_by(name)
82
+ ~~~
83
+
84
+ Example: create a dashboard showing the queue latency of all Sidekiq jobs.
85
+ The queue latency is the time between when the job was enqueued and when it was started:
86
+ ~~~ruby
87
+ filter environment = "production"
88
+ filter level = "info"
89
+ filter metric = "sidekiq.queue.latency"
90
+ timechart duration:avg(duration), group_by(name)
91
+ ~~~
92
+
6
93
  * http://github.com/reidmorrison/rails_semantic_logger
7
94
 
8
95
  ## Documentation
9
96
 
10
97
  For complete documentation see: https://logger.rocketjob.io/rails
11
98
 
99
+ ## Upgrading to Semantic Logger V4.16 - Sidekiq Metrics Support
100
+
101
+ Rails Semantic Logger now supports Sidekiq metrics.
102
+ Below are the metrics that are now available when the JSON logging format is used:
103
+ - `sidekiq.job.perform` - The duration of each Sidekiq job.
104
+ - `sidekiq.queue.latency` - The time between when a Sidekiq job was enqueued and when it was started.
105
+
106
+ ## Upgrading to Semantic Logger v4.15 & V4.16 - Sidekiq Support
107
+
108
+ Rails Semantic Logger introduces direct support for Sidekiq v4, v5, v6, and v7.
109
+ Please remove any previous custom patches or configurations to make Sidekiq work with Semantic Logger.
110
+ To see the complete list of patches being made, and to contribute your own changes, see: [Sidekiq Patches](https://github.com/reidmorrison/rails_semantic_logger/blob/master/lib/rails_semantic_logger/extensions/sidekiq/sidekiq.rb)
111
+
12
112
  ## Upgrading to Semantic Logger v4.4
13
113
 
14
114
  With some forking frameworks it is necessary to call `reopen` after the fork. With v4.4 the
@@ -19,7 +119,18 @@ I.e. Please remove the following line if being called anywhere:
19
119
  SemanticLogger::Processor.instance.instance_variable_set(:@queue, Queue.new)
20
120
  ~~~
21
121
 
22
- ## Supports
122
+ ## New Versions of Rails, etc.
123
+
124
+ The primary purpose of the Rails Semantic Logger gem is to patch other gems, primarily Rails, to make them support structured logging though Semantic Logger.
125
+
126
+ When new versions of Rails and other gems are published they often make changes to the internals, so the existing patches stop working.
127
+
128
+ Rails Semantic Logger survives only when someone in the community upgrades to a newer Rails or other supported libraries, runs into problems,
129
+ and then contributes the fix back to the community by means of a pull request.
130
+
131
+ Additionally, when new popular gems come out, we rely only the community to supply the necessary patches in Rails Semantic Logger to make those gems support structured logging.
132
+
133
+ ## Supported Platforms
23
134
 
24
135
  For the complete list of supported Ruby and Rails versions, see the [Testing file](https://github.com/reidmorrison/rails_semantic_logger/blob/master/.github/workflows/ci.yml).
25
136
 
@@ -224,6 +224,8 @@ module RailsSemanticLogger
224
224
  :action_mailer
225
225
  )
226
226
  end
227
+
228
+ require("rails_semantic_logger/extensions/sidekiq/sidekiq") if defined?(::Sidekiq)
227
229
  end
228
230
 
229
231
  #
@@ -239,7 +241,7 @@ module RailsSemanticLogger
239
241
  end
240
242
 
241
243
  # Re-open appenders after Resque has forked a worker
242
- Resque.after_fork { |_job| ::SemanticLogger.reopen } if defined?(Resque)
244
+ Resque.after_fork { |_job| ::SemanticLogger.reopen } if defined?(Resque.after_fork)
243
245
 
244
246
  # Re-open appenders after Spring has forked a process
245
247
  Spring.after_fork { |_job| ::SemanticLogger.reopen } if defined?(Spring.after_fork)
@@ -6,9 +6,17 @@ module ActionDispatch
6
6
  private
7
7
 
8
8
  undef_method :log_error
9
- def log_error(_request, wrapper)
10
- ActiveSupport::Deprecation.silence do
11
- ActionController::Base.logger.fatal(wrapper.exception)
9
+ if (Rails::VERSION::MAJOR == 7 && Rails::VERSION::MINOR >= 1) || Rails::VERSION::MAJOR > 7
10
+ def log_error(_request, wrapper)
11
+ Rails.application.deprecators.silence do
12
+ ActionController::Base.logger.fatal(wrapper.exception)
13
+ end
14
+ end
15
+ else
16
+ def log_error(_request, wrapper)
17
+ ActiveSupport::Deprecation.silence do
18
+ ActionController::Base.logger.fatal(wrapper.exception)
19
+ end
12
20
  end
13
21
  end
14
22
  end
@@ -0,0 +1,242 @@
1
+ # Sidekiq patches
2
+ #
3
+ # To re-enable stdout logging for sidekiq server processes, add the following snippet to config/initializers/sidekiq.rb:
4
+ # Sidekiq.configure_server do |config|
5
+ # SemanticLogger.add_appender(io: $stdout, level: :debug, formatter: :color)
6
+ # end
7
+ if Sidekiq::VERSION.to_i == 4
8
+ require "sidekiq/exception_handler"
9
+ require "sidekiq/logging"
10
+ require "sidekiq/middleware/server/logging"
11
+ require "sidekiq/processor"
12
+ require "sidekiq/worker"
13
+ elsif Sidekiq::VERSION.to_i == 5
14
+ require "sidekiq/exception_handler"
15
+ require "sidekiq/job_logger"
16
+ require "sidekiq/logging"
17
+ require "sidekiq/worker"
18
+ elsif Sidekiq::VERSION.to_i == 6 && Sidekiq::VERSION.to_f < 6.5
19
+ require "sidekiq/exception_handler"
20
+ require "sidekiq/job_logger"
21
+ require "sidekiq/worker"
22
+ elsif Sidekiq::VERSION.to_i == 6
23
+ require "sidekiq/job_logger"
24
+ require "sidekiq/worker"
25
+ else
26
+ require "sidekiq/config"
27
+ require "sidekiq/job_logger"
28
+ require "sidekiq/job"
29
+ end
30
+
31
+ module Sidekiq
32
+ # Sidekiq > v4
33
+ if defined?(::Sidekiq::JobLogger)
34
+ # Let Semantic Logger handle duration logging
35
+ class JobLogger
36
+ def call(item, queue, &block)
37
+ klass = item["wrapped"] || item["class"]
38
+ logger = klass ? SemanticLogger[klass] : Sidekiq.logger
39
+
40
+ SemanticLogger.tagged(queue: queue) do
41
+ # Latency is the time between when the job was enqueued and when it started executing.
42
+ logger.info(
43
+ "Start #perform",
44
+ metric: "sidekiq.queue.latency",
45
+ metric_amount: job_latency_ms(item)
46
+ )
47
+
48
+ # Measure the duration of running the job
49
+ logger.measure_info(
50
+ "Completed #perform",
51
+ on_exception_level: :error,
52
+ log_exception: :full,
53
+ metric: "sidekiq.job.perform",
54
+ &block
55
+ )
56
+ end
57
+ end
58
+
59
+ def prepare(job_hash, &block)
60
+ level = job_hash["log_level"]
61
+ if level
62
+ SemanticLogger.silence(level) do
63
+ SemanticLogger.tagged(job_hash_context(job_hash), &block)
64
+ end
65
+ else
66
+ SemanticLogger.tagged(job_hash_context(job_hash), &block)
67
+ end
68
+ end
69
+
70
+ def job_hash_context(job_hash)
71
+ h = {jid: job_hash["jid"]}
72
+ h[:bid] = job_hash["bid"] if job_hash["bid"]
73
+ h[:tags] = job_hash["tags"] if job_hash["tags"]
74
+ h[:queue] = job_hash["queue"] if job_hash["queue"]
75
+ h
76
+ end
77
+
78
+ def job_latency_ms(job)
79
+ return unless job && job["enqueued_at"]
80
+
81
+ (Time.now.to_f - job["enqueued_at"].to_f) * 1000
82
+ end
83
+ end
84
+ end
85
+
86
+ # Sidekiq <= v6
87
+ if defined?(::Sidekiq::Logging)
88
+ # Replace Sidekiq logging context
89
+ module Logging
90
+ def self.with_context(msg, &block)
91
+ SemanticLogger.tagged(msg, &block)
92
+ end
93
+
94
+ def self.job_hash_context(job_hash)
95
+ h = {jid: job_hash["jid"]}
96
+ h[:bid] = job_hash["bid"] if job_hash["bid"]
97
+ h[:queue] = job_hash["queue"] if job_hash["queue"]
98
+ h
99
+ end
100
+ end
101
+ end
102
+
103
+ # Exception is already logged by Semantic Logger during the perform call
104
+ if defined?(::Sidekiq::ExceptionHandler)
105
+ # Sidekiq <= v6.5
106
+ module ExceptionHandler
107
+ class Logger
108
+ def call(_exception, ctx)
109
+ return if ctx.empty?
110
+
111
+ job_hash = ctx[:job] || {}
112
+ klass = job_hash["display_class"] || job_hash["wrapped"] || job_hash["class"]
113
+ logger = klass ? SemanticLogger[klass] : Sidekiq.logger
114
+ ctx[:context] ? logger.warn(ctx[:context], ctx) : logger.warn(ctx)
115
+ end
116
+ end
117
+ end
118
+ elsif defined?(::Sidekiq::Config)
119
+ # Sidekiq >= v7
120
+ class Config
121
+ remove_const :ERROR_HANDLER
122
+
123
+ ERROR_HANDLER = ->(ex, ctx, cfg = Sidekiq.default_configuration) do
124
+ unless ctx.empty?
125
+ job_hash = ctx[:job] || {}
126
+ klass = job_hash["display_class"] || job_hash["wrapped"] || job_hash["class"]
127
+ logger = klass ? SemanticLogger[klass] : Sidekiq.logger
128
+ ctx[:context] ? logger.warn(ctx[:context], ctx) : logger.warn(ctx)
129
+ end
130
+ end
131
+ end
132
+ else
133
+ # Sidekiq >= 6.5
134
+ Sidekiq.error_handlers.delete(Sidekiq::DEFAULT_ERROR_HANDLER)
135
+ Sidekiq.error_handlers << ->(ex, ctx) do
136
+ unless ctx.empty?
137
+ job_hash = ctx[:job] || {}
138
+ klass = job_hash["display_class"] || job_hash["wrapped"] || job_hash["class"]
139
+ logger = klass ? SemanticLogger[klass] : Sidekiq.logger
140
+ ctx[:context] ? logger.warn(ctx[:context], ctx) : logger.warn(ctx)
141
+ end
142
+ end
143
+ end
144
+
145
+ # Logging within each worker should use its own logger
146
+ case Sidekiq::VERSION.to_i
147
+ when 4
148
+ module Worker
149
+ def self.included(base)
150
+ if base.ancestors.any? { |c| c.name == "ActiveJob::Base" }
151
+ raise ArgumentError, "You cannot include Sidekiq::Worker in an ActiveJob: #{base.name}"
152
+ end
153
+
154
+ base.extend(ClassMethods)
155
+ base.include(SemanticLogger::Loggable)
156
+ base.class_attribute :sidekiq_options_hash
157
+ base.class_attribute :sidekiq_retry_in_block
158
+ base.class_attribute :sidekiq_retries_exhausted_block
159
+ end
160
+ end
161
+ when 5
162
+ module Worker
163
+ def self.included(base)
164
+ if base.ancestors.any? { |c| c.name == "ActiveJob::Base" }
165
+ raise ArgumentError, "You cannot include Sidekiq::Worker in an ActiveJob: #{base.name}"
166
+ end
167
+
168
+ base.extend(ClassMethods)
169
+ base.include(SemanticLogger::Loggable)
170
+ base.sidekiq_class_attribute :sidekiq_options_hash
171
+ base.sidekiq_class_attribute :sidekiq_retry_in_block
172
+ base.sidekiq_class_attribute :sidekiq_retries_exhausted_block
173
+ end
174
+ end
175
+ when 6
176
+ module Worker
177
+ def self.included(base)
178
+ if base.ancestors.any? { |c| c.name == "ActiveJob::Base" }
179
+ raise ArgumentError, "Sidekiq::Worker cannot be included in an ActiveJob: #{base.name}"
180
+ end
181
+
182
+ base.include(Options)
183
+ base.extend(ClassMethods)
184
+ base.include(SemanticLogger::Loggable)
185
+ end
186
+ end
187
+ else
188
+ module Job
189
+ def self.included(base)
190
+ if base.ancestors.any? { |c| c.name == "ActiveJob::Base" }
191
+ raise ArgumentError, "Sidekiq::Job cannot be included in an ActiveJob: #{base.name}"
192
+ end
193
+
194
+ base.include(Options)
195
+ base.extend(ClassMethods)
196
+ base.include(SemanticLogger::Loggable)
197
+ end
198
+ end
199
+ end
200
+
201
+ if defined?(::Sidekiq::Middleware::Server::Logging)
202
+ # Sidekiq v4
203
+ # Convert string to machine readable format
204
+ class Processor
205
+ def log_context(job_hash)
206
+ h = {jid: job_hash["jid"]}
207
+ h[:bid] = job_hash["bid"] if job_hash["bid"]
208
+ h[:queue] = job_hash["queue"] if job_hash["queue"]
209
+ h
210
+ end
211
+ end
212
+
213
+ # Let Semantic Logger handle duration logging
214
+ module Middleware
215
+ module Server
216
+ class Logging
217
+ def call(worker, item, queue)
218
+ SemanticLogger.tagged(queue: queue) do
219
+ worker.logger.info(
220
+ "Start #perform",
221
+ metric: "sidekiq.queue.latency",
222
+ metric_amount: job_latency_ms(item)
223
+ )
224
+ worker.logger.measure_info(
225
+ "Completed #perform",
226
+ on_exception_level: :error,
227
+ log_exception: :full,
228
+ metric: "sidekiq.job.perform"
229
+ ) { yield }
230
+ end
231
+ end
232
+
233
+ def job_latency_ms(job)
234
+ return unless job && job["enqueued_at"]
235
+
236
+ (Time.now.to_f - job["enqueued_at"].to_f) * 1000
237
+ end
238
+ end
239
+ end
240
+ end
241
+ end
242
+ end
@@ -1,3 +1,3 @@
1
1
  module RailsSemanticLogger
2
- VERSION = "4.14.0".freeze
2
+ VERSION = "4.16.0".freeze
3
3
  end
@@ -67,6 +67,12 @@ end
67
67
  require("rails_semantic_logger/extensions/mongoid/config") if defined?(Mongoid)
68
68
  require("rails_semantic_logger/extensions/active_support/logger") if defined?(ActiveSupport::Logger)
69
69
  require("rails_semantic_logger/extensions/active_support/log_subscriber") if defined?(ActiveSupport::LogSubscriber)
70
+
71
+ begin
72
+ require "rackup"
73
+ rescue LoadError
74
+ # No need to do anything, will fall back to Rack
75
+ end
70
76
  if defined?(Rackup::Server)
71
77
  require("rails_semantic_logger/extensions/rackup/server")
72
78
  elsif defined?(Rack::Server)
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails_semantic_logger
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.14.0
4
+ version: 4.16.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Reid Morrison
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2023-11-16 00:00:00.000000000 Z
11
+ date: 2024-07-01 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rack
@@ -82,6 +82,7 @@ files:
82
82
  - lib/rails_semantic_logger/extensions/rack/server.rb
83
83
  - lib/rails_semantic_logger/extensions/rackup/server.rb
84
84
  - lib/rails_semantic_logger/extensions/rails/server.rb
85
+ - lib/rails_semantic_logger/extensions/sidekiq/sidekiq.rb
85
86
  - lib/rails_semantic_logger/options.rb
86
87
  - lib/rails_semantic_logger/rack/logger.rb
87
88
  - lib/rails_semantic_logger/version.rb
@@ -91,7 +92,7 @@ licenses:
91
92
  metadata:
92
93
  bug_tracker_uri: https://github.com/reidmorrison/rails_semantic_logger/issues
93
94
  documentation_uri: https://logger.rocketjob.io
94
- source_code_uri: https://github.com/reidmorrison/rails_semantic_logger/tree/v4.14.0
95
+ source_code_uri: https://github.com/reidmorrison/rails_semantic_logger/tree/v4.16.0
95
96
  rubygems_mfa_required: 'true'
96
97
  post_install_message:
97
98
  rdoc_options: []
@@ -108,7 +109,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
108
109
  - !ruby/object:Gem::Version
109
110
  version: '0'
110
111
  requirements: []
111
- rubygems_version: 3.4.9
112
+ rubygems_version: 3.5.3
112
113
  signing_key:
113
114
  specification_version: 4
114
115
  summary: Feature rich logging framework that replaces the Rails logger.