semantic_logger 5.1.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.
Files changed (103) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +13 -12
  3. data/Rakefile +15 -4
  4. data/docs/api.md +196 -19
  5. data/docs/appenders.md +579 -68
  6. data/docs/config.md +647 -38
  7. data/docs/index.md +31 -5
  8. data/docs/log.md +56 -17
  9. data/docs/metrics.md +144 -30
  10. data/docs/operations.md +339 -24
  11. data/docs/rails.md +396 -8
  12. data/docs/security.md +222 -27
  13. data/docs/testing.md +28 -3
  14. data/docs/upgrading.md +938 -7
  15. data/lib/semantic_logger/appender/async.rb +42 -11
  16. data/lib/semantic_logger/appender/bugsnag.rb +7 -2
  17. data/lib/semantic_logger/appender/cloudwatch_logs.rb +168 -33
  18. data/lib/semantic_logger/appender/elasticsearch_base.rb +221 -28
  19. data/lib/semantic_logger/appender/elasticsearch_http.rb +23 -6
  20. data/lib/semantic_logger/appender/file.rb +160 -37
  21. data/lib/semantic_logger/appender/graylog.rb +101 -11
  22. data/lib/semantic_logger/appender/honeybadger.rb +7 -1
  23. data/lib/semantic_logger/appender/honeybadger_insights.rb +8 -2
  24. data/lib/semantic_logger/appender/http.rb +308 -46
  25. data/lib/semantic_logger/appender/io.rb +11 -6
  26. data/lib/semantic_logger/appender/kafka.rb +204 -44
  27. data/lib/semantic_logger/appender/loki.rb +55 -9
  28. data/lib/semantic_logger/appender/mongodb.rb +109 -5
  29. data/lib/semantic_logger/appender/new_relic.rb +3 -4
  30. data/lib/semantic_logger/appender/new_relic_logs.rb +35 -15
  31. data/lib/semantic_logger/appender/open_telemetry.rb +37 -35
  32. data/lib/semantic_logger/appender/rabbitmq.rb +246 -17
  33. data/lib/semantic_logger/appender/sentry.rb +3 -4
  34. data/lib/semantic_logger/appender/sentry_ruby.rb +159 -18
  35. data/lib/semantic_logger/appender/splunk.rb +11 -2
  36. data/lib/semantic_logger/appender/splunk_http.rb +92 -1
  37. data/lib/semantic_logger/appender/syslog.rb +149 -32
  38. data/lib/semantic_logger/appender/tcp.rb +73 -98
  39. data/lib/semantic_logger/appender/text_output.rb +65 -0
  40. data/lib/semantic_logger/appender/udp.rb +140 -18
  41. data/lib/semantic_logger/appender/wrapper.rb +10 -7
  42. data/lib/semantic_logger/appender.rb +115 -10
  43. data/lib/semantic_logger/appenders.rb +145 -5
  44. data/lib/semantic_logger/backtrace_cleaning.rb +77 -0
  45. data/lib/semantic_logger/base.rb +115 -81
  46. data/lib/semantic_logger/call_site.rb +235 -0
  47. data/lib/semantic_logger/context.rb +222 -0
  48. data/lib/semantic_logger/core_ext/process.rb +20 -5
  49. data/lib/semantic_logger/core_ext/warning.rb +70 -0
  50. data/lib/semantic_logger/deprecation.rb +139 -0
  51. data/lib/semantic_logger/exception_details.rb +51 -0
  52. data/lib/semantic_logger/formatters/base.rb +186 -20
  53. data/lib/semantic_logger/formatters/color.rb +18 -3
  54. data/lib/semantic_logger/formatters/default.rb +53 -8
  55. data/lib/semantic_logger/formatters/ecs.rb +9 -4
  56. data/lib/semantic_logger/formatters/json.rb +9 -0
  57. data/lib/semantic_logger/formatters/logfmt.rb +155 -21
  58. data/lib/semantic_logger/formatters/loki/labels.rb +282 -0
  59. data/lib/semantic_logger/formatters/loki.rb +430 -38
  60. data/lib/semantic_logger/formatters/new_relic_logs.rb +15 -13
  61. data/lib/semantic_logger/formatters/one_line.rb +101 -3
  62. data/lib/semantic_logger/formatters/open_telemetry.rb +191 -35
  63. data/lib/semantic_logger/formatters/pattern.rb +68 -12
  64. data/lib/semantic_logger/formatters/raw.rb +40 -11
  65. data/lib/semantic_logger/formatters/signalfx.rb +55 -15
  66. data/lib/semantic_logger/formatters/syslog.rb +114 -20
  67. data/lib/semantic_logger/formatters/syslog_cee.rb +38 -19
  68. data/lib/semantic_logger/formatters/syslog_header.rb +49 -0
  69. data/lib/semantic_logger/formatters.rb +1 -0
  70. data/lib/semantic_logger/levels.rb +10 -1
  71. data/lib/semantic_logger/log.rb +384 -82
  72. data/lib/semantic_logger/loggable.rb +56 -73
  73. data/lib/semantic_logger/logger.rb +31 -5
  74. data/lib/semantic_logger/metric/new_relic.rb +33 -18
  75. data/lib/semantic_logger/metric/signalfx.rb +29 -18
  76. data/lib/semantic_logger/metric/statsd.rb +41 -15
  77. data/lib/semantic_logger/processor.rb +194 -5
  78. data/lib/semantic_logger/queue_processor/backoff.rb +140 -0
  79. data/lib/semantic_logger/queue_processor/batch_failure.rb +69 -0
  80. data/lib/semantic_logger/queue_processor/held_write.rb +62 -0
  81. data/lib/semantic_logger/queue_processor/inbox.rb +97 -0
  82. data/lib/semantic_logger/queue_processor/reopener.rb +56 -0
  83. data/lib/semantic_logger/queue_processor/reporter.rb +113 -0
  84. data/lib/semantic_logger/queue_processor/request.rb +93 -0
  85. data/lib/semantic_logger/queue_processor/throttled_counter.rb +89 -0
  86. data/lib/semantic_logger/queue_processor.rb +519 -170
  87. data/lib/semantic_logger/ractor_copy.rb +120 -0
  88. data/lib/semantic_logger/ractor_processor.rb +82 -0
  89. data/lib/semantic_logger/ractor_receiver.rb +282 -0
  90. data/lib/semantic_logger/ractor_support.rb +28 -0
  91. data/lib/semantic_logger/redactor.rb +310 -0
  92. data/lib/semantic_logger/semantic_logger.rb +328 -81
  93. data/lib/semantic_logger/subscriber.rb +250 -10
  94. data/lib/semantic_logger/sync_processor.rb +237 -26
  95. data/lib/semantic_logger/test/capture_log_events.rb +26 -5
  96. data/lib/semantic_logger/test/minitest.rb +2 -1
  97. data/lib/semantic_logger/test/rspec.rb +1 -1
  98. data/lib/semantic_logger/trap_safe.rb +113 -0
  99. data/lib/semantic_logger/utils.rb +482 -67
  100. data/lib/semantic_logger/version.rb +1 -1
  101. data/lib/semantic_logger.rb +36 -3
  102. metadata +41 -5
  103. data/lib/semantic_logger/core_ext/thread.rb +0 -30
@@ -23,15 +23,9 @@
23
23
  # end
24
24
  # end
25
25
  # end
26
- #
27
- # Notes:
28
- # * To forcibly replace Rails or any other existing logging methods
29
- # use `prepend` instead of `include`. For example:
30
- # ExternalSupplier.prepend SemanticLogger::Loggable
31
26
  module SemanticLogger
32
27
  module Loggable
33
28
  def self.included(base)
34
- base.extend ClassMethods
35
29
  base.singleton_class.class_eval do
36
30
  undef_method :logger if method_defined?(:logger)
37
31
  undef_method :logger= if method_defined?(:logger=)
@@ -42,91 +36,80 @@ module SemanticLogger
42
36
 
43
37
  # Returns [SemanticLogger::Logger] class level logger
44
38
  def self.logger
39
+ return Loggable.ractor_loggers[self] ||= SemanticLogger[self] if RactorSupport.other_ractor?
40
+
45
41
  @semantic_logger ||= SemanticLogger[self]
46
42
  end
47
43
 
48
44
  # Replace instance class level logger
49
45
  def self.logger=(logger)
50
- @semantic_logger = logger
46
+ if RactorSupport.other_ractor?
47
+ Loggable.ractor_loggers[self] = logger
48
+ else
49
+ @semantic_logger = logger
50
+ end
51
51
  end
52
+ end
52
53
 
53
- # Returns [SemanticLogger::Logger] instance level logger
54
- def logger
55
- @semantic_logger ||= self.class.logger
56
- end
54
+ if base.is_a?(Class)
55
+ base.class_eval do
56
+ # Returns [SemanticLogger::Logger] instance level logger
57
+ def logger
58
+ @semantic_logger ||= self.class.logger
59
+ end
57
60
 
58
- # Replace instance level logger
59
- def logger=(logger)
60
- @semantic_logger = logger
61
+ # Replace instance level logger
62
+ def logger=(logger)
63
+ @semantic_logger = logger
64
+ end
61
65
  end
62
- end
63
- end
66
+ else
67
+ base.class_eval do
68
+ # Returns [SemanticLogger::Logger] instance level logger
69
+ #
70
+ # The module was included into, or extended, a class that need not include Loggable itself.
71
+ def logger
72
+ return Loggable.ractor_loggers[self] ||= Loggable.logger_for(self) if Loggable.ractor_owned?(self)
64
73
 
65
- module ClassMethods
66
- # Measure and log the performance of an instance method.
67
- #
68
- # Parameters:
69
- # method_name: [Symbol]
70
- # The name of the method that should be measured.
71
- #
72
- # options: [Hash]
73
- # Any valid options that can be passed to measure.
74
- #
75
- # Approximate overhead when logging a method call with a metric:
76
- # 0.044 ms per method call.
77
- # 0.009 ms per method call. If `min_duration` is not met
78
- # 0.0005 ms per method call. If `level` is not met
79
- def logger_measure_method(method_name,
80
- min_duration: 0.0,
81
- metric: "#{name}/#{method_name}",
82
- log_exception: :partial,
83
- on_exception_level: nil,
84
- message: "##{method_name}",
85
- level: :info)
86
- # unless visibility = Utils.method_visibility(self, method_name)
87
- # logger.warn("Unable to measure method: #{name}##{method_name} since it does not exist")
88
- # return false
89
- # end
90
-
91
- index = Levels.index(level)
74
+ @semantic_logger ||= Loggable.logger_for(self)
75
+ end
92
76
 
93
- logger_measure_module.module_eval(<<~MEASURE_METHOD, __FILE__, __LINE__ + 1)
94
- def #{method_name}(*args, &block)
95
- if logger.send(:level_index) <= #{index}
96
- logger.send(
97
- :measure_method,
98
- index: #{index},
99
- level: #{level.inspect},
100
- message: #{message.inspect},
101
- min_duration: #{min_duration},
102
- metric: #{metric.inspect},
103
- log_exception: #{log_exception.inspect},
104
- on_exception_level: #{on_exception_level.inspect}
105
- ) do
106
- super(*args, &block)
107
- end
77
+ # Replace instance level logger
78
+ def logger=(logger)
79
+ if Loggable.ractor_owned?(self)
80
+ Loggable.ractor_loggers[self] = logger
108
81
  else
109
- super(*args, &block)
82
+ @semantic_logger = logger
110
83
  end
111
84
  end
112
- MEASURE_METHOD
113
- # {"#{visibility} :#{method_name}" unless visibility == :public}
114
- true
85
+ end
115
86
  end
87
+ end
116
88
 
117
- private
89
+ # Returns [SemanticLogger::Logger] the logger for an object that uses a module that includes Loggable.
90
+ #
91
+ # A class or module that extended the module has a logger named after itself. An instance uses its
92
+ # class's class level logger when it has one, otherwise one named after its class.
93
+ def self.logger_for(object)
94
+ return SemanticLogger[object] if object.is_a?(Module)
118
95
 
119
- # Dynamic Module to intercept method calls for measuring purposes.
120
- def logger_measure_module
121
- if const_defined?(:SemanticLoggerMeasure, _search_ancestors = false)
122
- const_get(:SemanticLoggerMeasure)
123
- else
124
- mod = const_set(:SemanticLoggerMeasure, Module.new)
125
- prepend mod
96
+ klass = object.class
97
+ klass.respond_to?(:logger) ? klass.logger : SemanticLogger[klass]
98
+ end
126
99
 
127
- mod
128
- end
129
- end
100
+ # Returns [true|false] whether the logger of the supplied object is held in the current Ractor
101
+ # rather than by the object: a class or module, which a Ractor other than the main one cannot change.
102
+ def self.ractor_owned?(object)
103
+ object.is_a?(Module) && RactorSupport.other_ractor?
104
+ end
105
+
106
+ # Returns [Hash] the class level loggers of the current Ractor, when it is not the main one.
107
+ #
108
+ # A Ractor other than the main one cannot set, or use, the class level logger of the main Ractor,
109
+ # which the class holds, so it has a logger of its own for each class (experimental, Ruby 4.0 and
110
+ # later).
111
+ def self.ractor_loggers
112
+ ::Ractor.store_if_absent(:semantic_logger_loggable) { {} }
130
113
  end
131
114
  end
132
115
  end
@@ -12,14 +12,37 @@ module SemanticLogger
12
12
  end
13
13
 
14
14
  subscribers = (@subscribers ||= Concurrent::Array.new)
15
- subscribers << subscriber unless subscribers.include?(subscriber)
15
+ return if subscribers.include?(subscriber)
16
+
17
+ subscribers << subscriber
18
+ # A Ractor other than the main one can only call a shareable subscriber.
19
+ if RactorSupport.enabled? && ::Ractor.shareable?(subscriber)
20
+ @ractor_subscribers = [*@ractor_subscribers, subscriber].freeze
21
+ end
22
+ subscribers
16
23
  end
17
24
 
18
25
  class << self
19
26
  attr_reader :subscribers
20
27
  end
21
28
 
29
+ # Removes the on_log subscriber.
30
+ def self.unsubscribe(subscriber)
31
+ @subscribers&.delete(subscriber)
32
+ @ractor_subscribers = (@ractor_subscribers - [subscriber]).freeze if @ractor_subscribers
33
+ end
34
+
35
+ # Removes every on_log subscriber.
36
+ def self.clear_subscribers
37
+ @subscribers&.clear
38
+ @ractor_subscribers = nil
39
+ end
40
+
41
+ # Returns the processor that writes log entries to the appenders, or in a Ractor other than the
42
+ # main one, the RactorProcessor that sends them to the main Ractor.
22
43
  def self.processor
44
+ return RactorProcessor.current if RactorSupport.other_ractor?
45
+
23
46
  @processor ||= Processor.new
24
47
  end
25
48
 
@@ -74,13 +97,16 @@ module SemanticLogger
74
97
  Logger.processor.log(log)
75
98
  end
76
99
 
77
- @processor = nil
78
- @subscribers = nil
100
+ @processor = nil
101
+ @subscribers = nil
102
+ @ractor_subscribers = nil
79
103
 
104
+ # Calls the on_log subscribers, or in a Ractor other than the main one, the shareable ones.
80
105
  def self.call_subscribers(log)
81
- return unless @subscribers
106
+ subscribers = RactorSupport.other_ractor? ? @ractor_subscribers : @subscribers
107
+ return unless subscribers
82
108
 
83
- @subscribers.each do |subscriber|
109
+ subscribers.each do |subscriber|
84
110
  subscriber.call(log)
85
111
  rescue Exception => e
86
112
  processor.logger.error("Exception calling :on_log subscriber", e)
@@ -7,31 +7,39 @@ end
7
7
 
8
8
  # Send Metrics to NewRelic
9
9
  #
10
- # The :error and :fatal log entries will show up under
11
- # "Applications" > "Application Name" > "Events" > "Errors" in New Relic.
10
+ # Records the metric of each log entry that has one as a New Relic custom metric, through the
11
+ # agent's metric API: with record_metric, in seconds, when the entry has a duration, otherwise with
12
+ # increment_metric, by its metric_amount, or 1. A metric's dimensions are left out, since that API
13
+ # takes none.
12
14
  #
13
15
  # Example:
14
16
  # SemanticLogger.add_appender(metric: :new_relic)
15
17
  module SemanticLogger
16
18
  module Metric
17
19
  class NewRelic < SemanticLogger::Subscriber
18
- attr_accessor :prefix
20
+ attr_reader :prefix
19
21
 
20
- # Create Appender
22
+ # Create the New Relic metrics subscriber
21
23
  #
22
24
  # Parameters
23
- # :prefix [String]
24
- # Prefix to add to every metric before forwarding to NewRelic.
25
+ # prefix: [String]
26
+ # Prefix to add, with a `/`, to every metric name that does not already start with it and
27
+ # a `/`, before forwarding to NewRelic, which charts custom metrics only under `Custom/`.
28
+ # So 'Customers/signup' is recorded as 'Custom/Customers/signup', and 'Custom/Orders/placed'
29
+ # as it is. Another prefix should start with `Custom/` too, such as 'Custom/MyApp'. A
30
+ # trailing `/` is left out, and an empty prefix adds nothing. Only the default formatter,
31
+ # #call, adds it.
25
32
  # Default: 'Custom'
26
33
  #
27
34
  # level: [:trace | :debug | :info | :warn | :error | :fatal]
28
- # Override the log level for this appender.
29
- # Default: :error
35
+ # Override the log level for this subscriber.
36
+ # Default: none (:trace), so it records every metric entry that a logger emits; each
37
+ # logger filters by its own level.
30
38
  #
31
39
  # formatter: [Object|Proc]
32
- # An instance of a class that implements #call, or a Proc to be used to format
33
- # the output from this appender
34
- # Default: Use the built-in formatter (See: #call)
40
+ # An instance of a class that implements #call, or a Proc, that returns the name to
41
+ # record the metric under.
42
+ # Default: #call, which adds the prefix to the name of the entry's metric.
35
43
  #
36
44
  # filter: [Regexp|Proc]
37
45
  # RegExp: Only include log messages where the class name matches the supplied.
@@ -39,20 +47,27 @@ module SemanticLogger
39
47
  # Proc: Only include log messages where the supplied Proc returns true
40
48
  # The Proc must return true or false.
41
49
  def initialize(prefix: "Custom", **args, &)
42
- @prefix = prefix
50
+ self.prefix = prefix
43
51
  super(**args, &)
44
52
  end
45
53
 
54
+ # Sets the prefix that #call adds, without a trailing `/`, since #call adds one. An empty
55
+ # prefix is added as an empty String, which every name already starts with.
56
+ def prefix=(prefix)
57
+ @prefix = prefix.to_s.delete_suffix("/")
58
+ @prefix_with_slash = @prefix.empty? ? "" : "#{@prefix}/"
59
+ end
60
+
46
61
  # Returns metric name to use.
47
62
  def call(log, _logger)
48
63
  metric = log.metric
49
- # Add prefix for NewRelic
50
- metric = "#{prefix}/#{metric}" unless metric.start_with?(prefix)
51
- metric
64
+ return metric if metric.start_with?(@prefix_with_slash)
65
+
66
+ "#{@prefix_with_slash}#{metric}"
52
67
  end
53
68
 
54
69
  def log(log)
55
- name = formatter.call(log, self)
70
+ name = format_log(log)
56
71
  if (duration = log.duration)
57
72
  # Convert duration to seconds
58
73
  ::NewRelic::Agent.record_metric(name, duration / 1000.0)
@@ -64,8 +79,8 @@ module SemanticLogger
64
79
 
65
80
  # Only forward log entries that contain metrics.
66
81
  def should_log?(log)
67
- # Does not support metrics with dimensions.
68
- log.metric && !log.dimensions && meets_log_level?(log) && !filtered?(log)
82
+ # Records a metric that has dimensions under its name alone, since the agent's metric API has none.
83
+ log.metric && meets_log_level?(log) && !filtered?(log)
69
84
  end
70
85
  end
71
86
  end
@@ -8,7 +8,7 @@
8
8
  module SemanticLogger
9
9
  module Metric
10
10
  class Signalfx < SemanticLogger::Appender::Http
11
- attr_reader :full_url
11
+ attr_reader :full_path
12
12
 
13
13
  END_POINT = "v2/datapoint".freeze
14
14
 
@@ -19,10 +19,15 @@ module SemanticLogger
19
19
  # Access Token to use for sending metrics.
20
20
  # Obtain the Signalfx token via the Signalfx Web UI under `Organization` -> `Access Tokens`.
21
21
  #
22
- # dimensions: [Array<String>]
23
- # Dimensions to forward to signalfx when they are present in the named tags of any log message.
24
- # By default `application` and `host` are always included as dimensions in all forwarded metrics.
25
- # Example: [:user_id, :state]
22
+ # dimensions: [Array<Symbol|String>]
23
+ # Dimensions to forward to signalfx when they are present, and not blank, in the named tags of
24
+ # any log message whose metric has no dimensions of its own. A metric logged with `dimensions:`
25
+ # is sent with those instead, so add the named tags it needs to them.
26
+ # By default `application`, `host`, and, when it is set, `environment` are always included as
27
+ # dimensions in all forwarded metrics.
28
+ # Each value of a dimension makes a new metric time series, so list only named tags whose
29
+ # values are bounded, never a user or request id (see docs/metrics.md).
30
+ # Example: [:region, :plan]
26
31
  #
27
32
  # filter: [Regexp|Proc]
28
33
  # RegExp: Only include log messages where the class name matches the supplied
@@ -39,8 +44,7 @@ module SemanticLogger
39
44
  # Default: SemanticLogger.application
40
45
  #
41
46
  # url: [String]
42
- # Override the SignalFx service url.
43
- # For historical data use: https://backfill.signalfx.com/v1/backfill
47
+ # Override the SignalFx service url. The metrics are posted to `v2/datapoint` under its path.
44
48
  # Default: https://ingest.signalfx.com
45
49
  #
46
50
  # Notes:
@@ -51,16 +55,15 @@ module SemanticLogger
51
55
  # Using a `count` of a `gauge` in a chart will significantly under-count the number of occurrences.
52
56
  #
53
57
  # If dimensions are added to the metric, then the metric will be sent as-is and
54
- # the above logic will _not_ be applied.
55
- #
56
- # Example, Gauge metric, supplying the duration in `metric_amount`:
57
- # logger.info(metric: 'Filters.average', metric_amount: 1.2, dimensions: {user: 'jbloggs'})
58
+ # the above logic will _not_ be applied. A dimension whose value is blank (nil, or text that is
59
+ # empty or only whitespace) is left out, and dimensions that are empty, such as `{}`, or all
60
+ # blank, such as `{state: ""}`, count as none.
58
61
  #
59
62
  # Example, Counter metric:
60
- # logger.info(metric: 'Filters.count', dimensions: {user: 'jbloggs'})
63
+ # logger.info(metric: 'Filters.count', dimensions: {plan: 'premium'})
61
64
  #
62
65
  # Example, Counter metric with a count other than 1:
63
- # logger.info(metric: 'Filters.count', metric_amount: 23, dimensions: {user: 'jbloggs'})
66
+ # logger.info(metric: 'Filters.count', metric_amount: 23, dimensions: {plan: 'premium'})
64
67
  #
65
68
  # When a duration is supplied and no dimensions are supplied:
66
69
  # logger.info(metric: 'Common/User/authorize', duration: 1.4)
@@ -86,20 +89,28 @@ module SemanticLogger
86
89
  super(url: url, formatter: formatter, **args, &)
87
90
 
88
91
  @header["X-SF-TOKEN"] = token
89
- @full_url = "#{url}/#{END_POINT}"
92
+ # Built from the parsed path, not the supplied url, so that a query string in the
93
+ # url stays at the end of the request uri. See Appender::Http#uri_with_query.
94
+ @full_path = "#{@path.end_with?('/') ? @path : "#{@path}/"}#{END_POINT}"
90
95
  end
91
96
 
92
97
  def log(log)
93
- message = formatter.call(log, self)
98
+ message = format_log(log)
94
99
  logger.trace(message)
95
- post(message, full_url)
100
+ post(message, full_path)
96
101
  end
97
102
 
98
103
  # Logs in batches
99
104
  def batch(logs)
100
- message = formatter.batch(logs, self)
105
+ message = format_batch(logs)
101
106
  logger.trace(message)
102
- post(message, full_url)
107
+ post(message, full_path)
108
+ end
109
+
110
+ # The #batch above formats the whole batch with #format_batch, so it answers as
111
+ # Appender::Http#batch_refusal does for its own #batch: only while it is the one in use.
112
+ def batch_refusal
113
+ format_batch_refusal if batch_defined_by?(Signalfx)
103
114
  end
104
115
 
105
116
  # Only forward log entries that contain metrics.
@@ -14,30 +14,48 @@ module SemanticLogger
14
14
  #
15
15
  # Parameters:
16
16
  # url: [String]
17
- # Valid URL to post to.
17
+ # Url of the Statsd server to send metrics to. Only udp is supported.
18
18
  # Example:
19
19
  # udp://localhost:8125
20
20
  # Example, send all metrics to a particular namespace:
21
21
  # udp://localhost:8125/namespace
22
22
  # Default: udp://localhost:8125
23
23
  #
24
+ # level, filter: See SemanticLogger::Subscriber, as for the other metric subscribers.
25
+ #
24
26
  # Example:
25
27
  # SemanticLogger.add_appender(
26
28
  # metric: :statsd,
27
29
  # url: 'udp://localhost:8125'
28
30
  # )
29
- def initialize(url: "udp://localhost:8125")
31
+ def initialize(url: "udp://localhost:8125", **args, &)
30
32
  @url = url
31
- super()
33
+ super(**args, &)
34
+ reopen
32
35
  end
33
36
 
37
+ # Creates the Statsd client, or reconnects it, such as in a forked process, which closes the socket that the
38
+ # client had, rather than leaving it open. The host is resolved first, so that a failure to resolve it leaves the
39
+ # client connected as it was. Only a url that drops the namespace creates a new client, since a client cannot be
40
+ # given back no namespace, which leaves the old client's socket for garbage collection to close.
34
41
  def reopen
35
- uri = URI.parse(@url)
42
+ uri = Utils.parse_url(@url)
36
43
  raise('Statsd only supports udp. Example: "udp://localhost:8125"') if uri.scheme != "udp"
37
44
 
38
- @statsd = ::Statsd.new(uri.host, uri.port)
39
- path = uri.path.chomp("/")
40
- @statsd.namespace = path.sub("/", "") if path != ""
45
+ # The host without the brackets of an IPv6 address.
46
+ host = uri.hostname
47
+ path = uri.path.chomp("/")
48
+ namespace = path.sub("/", "") unless path == ""
49
+ if @statsd && (namespace || @statsd.namespace.nil?)
50
+ Addrinfo.ip(host)
51
+ @statsd.host = host
52
+ @statsd.port = uri.port
53
+ @statsd.namespace = namespace if namespace
54
+ @statsd.connect
55
+ else
56
+ @statsd = ::Statsd.new(host, uri.port)
57
+ @statsd.namespace = namespace if namespace
58
+ end
41
59
  end
42
60
 
43
61
  def log(log)
@@ -45,19 +63,27 @@ module SemanticLogger
45
63
  if (duration = log.duration)
46
64
  @statsd.timing(metric, duration)
47
65
  else
48
- amount = (log.metric_amount || 1).round
49
- if amount.negative?
50
- amount.abs.times { @statsd.decrement(metric) }
51
- else
52
- amount.times { @statsd.increment(metric) }
53
- end
66
+ amount = log.metric_amount || 1
67
+ # Infinity and NaN cannot be counted, whether a Float or a BigDecimal.
68
+ return if amount.respond_to?(:finite?) && !amount.finite?
69
+
70
+ amount = amount.round
71
+ # A single counter packet, whatever the size of the amount. Incrementing once per unit
72
+ # would let a large amount, such as one supplied by a user, flood the network and
73
+ # stall the logging thread.
74
+ @statsd.count(metric, amount) unless amount.zero?
54
75
  end
55
76
  end
56
77
 
57
78
  # Only forward log entries that contain metrics.
58
79
  def should_log?(log)
59
- # Does not support metrics with dimensions.
60
- log.metric && !log.dimensions && meets_log_level?(log) && !filtered?(log)
80
+ # Records a metric that has dimensions under its name alone, since statsd-ruby has no tags.
81
+ log.metric && meets_log_level?(log) && !filtered?(log)
82
+ end
83
+
84
+ # The url without any credentials. See Subscriber#inspect.
85
+ def inspect_details
86
+ "url=#{Utils.redacted_url(url).inspect}"
61
87
  end
62
88
  end
63
89
  end