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
@@ -2,6 +2,10 @@ require "json"
2
2
  module SemanticLogger
3
3
  module Formatters
4
4
  class Signalfx < Base
5
+ # Text of a dimension value that is blank (see #blank_value?).
6
+ BLANK_VALUE = /\A[[:space:]]*\z/
7
+ private_constant :BLANK_VALUE
8
+
5
9
  attr_accessor :token, :dimensions, :hash, :gauge_name, :counter_name
6
10
 
7
11
  def initialize(token:,
@@ -21,9 +25,14 @@ module SemanticLogger
21
25
  # Create SignalFx friendly metric.
22
26
  # Strip leading '/'
23
27
  # Convert remaining '/' to '.'
28
+ # A name that is not valid UTF-8, such as one with invalid bytes or in UTF-16, which matching
29
+ # it raises for, is converted to valid UTF-8 first (see Utils.encode_utf8_string).
30
+ #
31
+ # A metric with dimensions that are not blank (see #present_dimensions) is sent under its own name.
32
+ # Any other is sent as the gauge or the counter, with the class and action taken from its name.
24
33
  def metric
25
- name = log.metric.to_s.sub(%r{\A/+}, "")
26
- if log.dimensions
34
+ name = Utils.encode_utf8_string(log.metric.to_s).sub(%r{\A/+}, "")
35
+ if metric_dimensions
27
36
  name.tr!("/", ".")
28
37
  hash[:metric] = name
29
38
  else
@@ -53,21 +62,19 @@ module SemanticLogger
53
62
  hash[:value] = log.metric_amount || log.duration || 1
54
63
  end
55
64
 
56
- # Dimensions for this metric
65
+ # Dimensions for this metric: those of the log entry that are not blank, or when it has none, the
66
+ # named tags listed in the dimensions option whose values are not blank (see #blank_value?).
57
67
  def format_dimensions
58
68
  h = (hash[:dimensions] ||= {})
59
- if log.dimensions
60
- log.dimensions.each_pair do |name, value|
61
- value = value.to_s
62
- h[name] = value unless value.empty?
63
- end
64
- else
69
+ if metric_dimensions
70
+ h.merge!(metric_dimensions)
71
+ elsif dimensions
65
72
  log.named_tags.each_pair do |name, value|
66
- name = name.to_sym
67
- value = value.to_s
68
- next if value.empty?
73
+ name = name.to_sym
74
+ next unless dimensions.include?(name)
69
75
 
70
- h[name] = value if dimensions&.include?(name)
76
+ value = value.to_s
77
+ h[name] = value unless blank_value?(value)
71
78
  end
72
79
  end
73
80
  h[:host] = logger.host if log_host && logger.host
@@ -91,7 +98,7 @@ module SemanticLogger
91
98
  if log.duration
92
99
  data[:gauge] = [hash]
93
100
  # Also send a count metric whenever it is a gauge so that it can be counted.
94
- unless log.dimensions
101
+ unless metric_dimensions
95
102
  count_hash = hash.dup
96
103
  count_hash[:value] = log.metric_amount || 1
97
104
  count_hash[:metric] = counter_name
@@ -125,7 +132,7 @@ module SemanticLogger
125
132
  add_gauge(gauges, hash)
126
133
 
127
134
  # Also send a count metric whenever it is a gauge so that it can be counted.
128
- unless log.dimensions
135
+ unless metric_dimensions
129
136
  count_hash = hash.dup
130
137
  count_hash[:value] = log.metric_amount || 1
131
138
  count_hash[:metric] = counter_name
@@ -141,8 +148,41 @@ module SemanticLogger
141
148
  Utils.to_json(data)
142
149
  end
143
150
 
151
+ # The log entry to format. Also keeps the dimensions of its metric that are sent (see
152
+ # #present_dimensions), which formatting the entry asks for several times.
153
+ def log=(log)
154
+ super
155
+ @metric_dimensions = log && present_dimensions
156
+ end
157
+
144
158
  private
145
159
 
160
+ # The dimensions of the entry's metric that are sent, or nil when there are none.
161
+ attr_reader :metric_dimensions
162
+
163
+ # Returns [Hash] the dimensions of the entry's metric, as Log#dimensions? tells, with each value as
164
+ # text, leaving out those that are blank (see #blank_value?). Returns nil when there are none, or only
165
+ # blank ones, such as `{state: ""}`, so that the metric is sent as a metric without dimensions is:
166
+ # as the gauge or the counter, with the class and action taken from its name. Log#dimensions?
167
+ # counts such dimensions, which the formatters that write the entry's data write as they are.
168
+ def present_dimensions
169
+ return unless log.dimensions?
170
+
171
+ present = {}
172
+ log.dimensions.each_pair do |name, value|
173
+ value = value.to_s
174
+ present[name] = value unless blank_value?(value)
175
+ end
176
+ present unless present.empty?
177
+ end
178
+
179
+ # Returns [true|false] whether the text of a dimension value is blank: empty, as for nil, or only
180
+ # whitespace, which includes Unicode whitespace such as a no-break space, but not NUL. The text is
181
+ # converted to valid UTF-8 first (see Utils.encode_utf8_string): matching raises for UTF-8 text
182
+ # with invalid bytes, or text that is not ASCII-compatible, such as UTF-16, and would not find the
183
+ # Unicode whitespace in text in an encoding such as binary or Shift_JIS.
184
+ def blank_value?(text) = BLANK_VALUE.match?(Utils.encode_utf8_string(text))
185
+
146
186
  def add_gauge(gauges, metric)
147
187
  gauges << metric
148
188
  end
@@ -1,15 +1,64 @@
1
- begin
2
- require "syslog_protocol"
3
- rescue LoadError
4
- raise LoadError,
5
- "Gem syslog_protocol is required for remote logging using the Syslog protocol. " \
6
- 'Please add the gem "syslog_protocol" to your Gemfile.'
7
- end
8
-
9
1
  module SemanticLogger
10
2
  module Formatters
11
3
  class Syslog < Default
12
- attr_accessor :level_map, :facility, :max_size
4
+ include SyslogHeader
5
+
6
+ attr_accessor :max_size
7
+ attr_reader :facility, :level_map
8
+
9
+ # Syslog severities and facilities, with the same values as the matching `::Syslog` constants.
10
+ # The `syslog` gem is only needed to log to a local syslog daemon, and since Ruby 3.4 it is a
11
+ # bundled gem, so remote syslog must not depend on it for these values.
12
+ LOG_CRIT = 2
13
+ LOG_ERR = 3
14
+ LOG_WARNING = 4
15
+ LOG_NOTICE = 5
16
+ LOG_INFO = 6
17
+ LOG_DEBUG = 7
18
+
19
+ # Syslog facilities, as syslog(3) defines them: the facility number shifted left by 3 bits.
20
+ LOG_KERN = 0 << 3
21
+ LOG_USER = 1 << 3
22
+ LOG_MAIL = 2 << 3
23
+ LOG_DAEMON = 3 << 3
24
+ LOG_AUTH = 4 << 3
25
+ LOG_SYSLOG = 5 << 3
26
+ LOG_LPR = 6 << 3
27
+ LOG_NEWS = 7 << 3
28
+ LOG_UUCP = 8 << 3
29
+ LOG_CRON = 9 << 3
30
+ LOG_AUTHPRIV = 10 << 3
31
+ LOG_FTP = 11 << 3
32
+ LOG_LOCAL0 = 16 << 3
33
+ LOG_LOCAL1 = 17 << 3
34
+ LOG_LOCAL2 = 18 << 3
35
+ LOG_LOCAL3 = 19 << 3
36
+ LOG_LOCAL4 = 20 << 3
37
+ LOG_LOCAL5 = 21 << 3
38
+ LOG_LOCAL6 = 22 << 3
39
+ LOG_LOCAL7 = 23 << 3
40
+
41
+ # Default maximum size of a syslog packet, in bytes, as for the syslog appender.
42
+ DEFAULT_MAX_SIZE = 1024
43
+
44
+ # The highest facility the syslog protocol can encode.
45
+ MAX_FACILITY = LOG_LOCAL7
46
+
47
+ # Returns [Integer] the facility number (0 to 23) that the syslog protocol sends, for a facility
48
+ # given as documented: one of the `::Syslog::LOG_*` facility constants, such as
49
+ # `::Syslog::LOG_LOCAL0`. syslog(3) defines each of those as the facility number shifted left
50
+ # by 3 bits, so `::Syslog::LOG_USER` is 8 and its facility number is 1.
51
+ #
52
+ # Raises ArgumentError for any other value, including a bare facility number.
53
+ def self.facility_number(facility)
54
+ unless facility.is_a?(Integer) && (facility % 8).zero? && facility.between?(0, MAX_FACILITY)
55
+ raise(ArgumentError,
56
+ "Invalid syslog facility: #{facility.inspect}. Must be one of the ::Syslog::LOG_* facility " \
57
+ "constants, for example ::Syslog::LOG_USER or ::Syslog::LOG_LOCAL0.")
58
+ end
59
+
60
+ facility >> 3
61
+ end
13
62
 
14
63
  # Default level map for every log level
15
64
  #
@@ -26,8 +75,14 @@ module SemanticLogger
26
75
  class LevelMap
27
76
  attr_accessor :trace, :debug, :info, :warn, :error, :fatal
28
77
 
29
- def initialize(trace: ::Syslog::LOG_DEBUG, debug: ::Syslog::LOG_INFO, info: ::Syslog::LOG_NOTICE,
30
- warn: ::Syslog::LOG_WARNING, error: ::Syslog::LOG_ERR, fatal: ::Syslog::LOG_CRIT)
78
+ # Returns [LevelMap] the supplied level map, or a new one with a Hash of overrides applied,
79
+ # for example `{warn: LOG_NOTICE}`.
80
+ def self.build(level_map)
81
+ level_map.is_a?(LevelMap) ? level_map : new(**level_map)
82
+ end
83
+
84
+ def initialize(trace: LOG_DEBUG, debug: LOG_INFO, info: LOG_NOTICE,
85
+ warn: LOG_WARNING, error: LOG_ERR, fatal: LOG_CRIT)
31
86
  @trace = trace
32
87
  @debug = debug
33
88
  @info = info
@@ -41,11 +96,23 @@ module SemanticLogger
41
96
  end
42
97
  end
43
98
 
99
+ # Load the syslog_protocol gem, which builds the packets for remote syslog.
100
+ # Called when a syslog formatter is created, so the gem is only needed by applications
101
+ # that log to a remote syslog server.
102
+ def self.require_syslog_protocol
103
+ require "syslog_protocol"
104
+ rescue LoadError
105
+ raise LoadError,
106
+ "Gem syslog_protocol is required for remote logging using the Syslog protocol. " \
107
+ 'Please add the gem "syslog_protocol" to your Gemfile.'
108
+ end
109
+
44
110
  # Create a Syslog Log Formatter
45
111
  #
46
112
  # Parameters:
47
113
  # facility: [Integer]
48
- # Default: ::Syslog::LOG_USER
114
+ # One of the ::Syslog::LOG_* facility constants, for example ::Syslog::LOG_LOCAL0.
115
+ # Default: LOG_USER
49
116
  #
50
117
  # level_map: [Hash | SemanticLogger::Formatters::Syslog::LevelMap]
51
118
  # Supply a custom map of SemanticLogger levels to syslog levels.
@@ -57,27 +124,49 @@ module SemanticLogger
57
124
  # Default: true (unlike other formatters, since syslog frames records
58
125
  # with a separator)
59
126
  #
127
+ # max_size: [Integer]
128
+ # Maximum size of each syslog packet, in bytes.
129
+ # Default: DEFAULT_MAX_SIZE (1024)
130
+ #
60
131
  # Example:
61
132
  # # Change the warn level to LOG_NOTICE level instead of a the default of LOG_WARNING.
62
133
  # SemanticLogger.add_appender(appender: :syslog, level_map: {warn: ::Syslog::LOG_NOTICE})
63
- def initialize(facility: ::Syslog::LOG_USER, level_map: LevelMap.new, max_size: Integer,
134
+ def initialize(facility: LOG_USER, level_map: LevelMap.new, max_size: DEFAULT_MAX_SIZE,
64
135
  escape_control_chars: true, **args)
65
- @facility = facility
66
- @level_map = level_map.is_a?(LevelMap) ? level_map : LevelMap.new(**level_map)
67
- @max_size = max_size
136
+ self.class.require_syslog_protocol
137
+
138
+ self.facility = facility
139
+ self.level_map = level_map
140
+ @max_size = max_size
68
141
  # Syslog frames records with a separator, so embedded newlines or other
69
142
  # control characters in untrusted log data can forge or split records.
70
143
  # Default to escaping them, overridable for backwards compatibility.
71
144
  super(escape_control_chars: escape_control_chars, **args)
72
145
  end
73
146
 
147
+ # Set the facility to one of the ::Syslog::LOG_* facility constants.
148
+ # Raises ArgumentError for any other value, so that a mistake surfaces here rather than on
149
+ # every log entry.
150
+ def facility=(facility)
151
+ @facility_number = Syslog.facility_number(facility)
152
+ @facility = facility
153
+ end
154
+
155
+ # Set the map of log levels to syslog severities, as a LevelMap or a Hash of overrides.
156
+ def level_map=(level_map)
157
+ @level_map = LevelMap.build(level_map)
158
+ end
159
+
74
160
  # Time is part of the syslog packet and is not included in the formatted message.
75
161
  def time
76
162
  nil
77
163
  end
78
164
 
79
165
  def call(log, logger)
80
- message = super
166
+ # The individual fields are already escaped. Also escape the newlines that the
167
+ # exception and its backtrace are laid out with, so that a record never spans more
168
+ # than one line, which a receiver framing records by newline would split.
169
+ message = escape_control_characters(super)
81
170
  create_syslog_packet(message)
82
171
  end
83
172
 
@@ -86,14 +175,19 @@ module SemanticLogger
86
175
  # Create Syslog Packet
87
176
  def create_syslog_packet(message)
88
177
  packet = SyslogProtocol::Packet.new
89
- packet.hostname = logger.host
90
- packet.facility = facility
91
- packet.tag = logger.application.delete(" ")
178
+ packet.hostname = syslog_hostname(logger.host)
179
+ packet.facility = @facility_number
180
+ packet.tag = syslog_tag(logger.application)
92
181
  packet.content = message
93
182
  packet.time = log.time
94
183
  packet.severity = level_map[log.level]
95
184
  packet.assemble(@max_size)
96
185
  end
186
+
187
+ # Off by default, so that existing syslog records do not change.
188
+ def default_log_exception_details
189
+ false
190
+ end
97
191
  end
98
192
  end
99
193
  end
@@ -1,15 +1,10 @@
1
- begin
2
- require "syslog_protocol"
3
- rescue LoadError
4
- raise LoadError,
5
- "Gem syslog_protocol is required for remote logging using the Syslog protocol. " \
6
- 'Please add the gem "syslog_protocol" to your Gemfile.'
7
- end
8
-
9
1
  module SemanticLogger
10
2
  module Formatters
11
3
  class SyslogCee < Raw
12
- attr_accessor :level_map, :facility, :max_size
4
+ include SyslogHeader
5
+
6
+ attr_accessor :max_size
7
+ attr_reader :facility, :level_map
13
8
 
14
9
  # CEE JSON Syslog format
15
10
  # Untested prototype code. Based on documentation only.
@@ -17,20 +12,44 @@ module SemanticLogger
17
12
  #
18
13
  # Parameters:
19
14
  # facility: [Integer]
20
- # Default: ::Syslog::LOG_USER
15
+ # One of the ::Syslog::LOG_* facility constants, for example ::Syslog::LOG_LOCAL0.
16
+ # Default: SemanticLogger::Formatters::Syslog::LOG_USER
21
17
  #
22
18
  # level_map: [Hash | SemanticLogger::Formatters::Syslog::LevelMap]
23
19
  # Supply a custom map of SemanticLogger levels to syslog levels.
24
20
  #
21
+ # max_size: [Integer]
22
+ # Maximum size of each syslog packet, in bytes.
23
+ # Default: SemanticLogger::Formatters::Syslog::DEFAULT_MAX_SIZE (1024)
24
+ #
25
+ # Any other options are those of SemanticLogger::Formatters::Raw, such as `log_host` or
26
+ # `log_exception_details`. Its time options (`time_format`, `time_key`, and `precision`)
27
+ # have no effect, since the time is in the header of the syslog packet.
28
+ #
25
29
  # Example:
26
30
  # # Log via udp to a remote syslog server on host: `server1` and port `8514`, using the CEE format.
27
31
  # SemanticLogger.add_appender(appender: :syslog, formatter: :syslog_cee, url: 'udp://server1:8514')
28
- def initialize(facility: ::Syslog::LOG_USER, level_map: SemanticLogger::Formatters::Syslog::LevelMap.new,
29
- max_size: Integer)
30
- @facility = facility
31
- @level_map = level_map.is_a?(SemanticLogger::Formatters::Syslog::LevelMap) ? level_map : SemanticLogger::Formatters::Syslog::LevelMap.new(level_map)
32
- @max_size = max_size
33
- super()
32
+ def initialize(facility: SemanticLogger::Formatters::Syslog::LOG_USER, level_map: SemanticLogger::Formatters::Syslog::LevelMap.new,
33
+ max_size: SemanticLogger::Formatters::Syslog::DEFAULT_MAX_SIZE, **args)
34
+ SemanticLogger::Formatters::Syslog.require_syslog_protocol
35
+
36
+ self.facility = facility
37
+ self.level_map = level_map
38
+ @max_size = max_size
39
+ super(**args)
40
+ end
41
+
42
+ # Set the facility to one of the ::Syslog::LOG_* facility constants.
43
+ # Raises ArgumentError for any other value, so that a mistake surfaces here rather than on
44
+ # every log entry.
45
+ def facility=(facility)
46
+ @facility_number = SemanticLogger::Formatters::Syslog.facility_number(facility)
47
+ @facility = facility
48
+ end
49
+
50
+ # Set the map of log levels to syslog severities, as a LevelMap or a Hash of overrides.
51
+ def level_map=(level_map)
52
+ @level_map = SemanticLogger::Formatters::Syslog::LevelMap.build(level_map)
34
53
  end
35
54
 
36
55
  # Time is part of the syslog packet and is not included in the formatted message.
@@ -47,9 +66,9 @@ module SemanticLogger
47
66
  # Create Syslog Packet
48
67
  def create_syslog_packet(message)
49
68
  packet = SyslogProtocol::Packet.new
50
- packet.hostname = logger.host
51
- packet.facility = facility
52
- packet.tag = logger.application.delete(" ")
69
+ packet.hostname = syslog_hostname(logger.host)
70
+ packet.facility = @facility_number
71
+ packet.tag = syslog_tag(logger.application)
53
72
  packet.content = message
54
73
  packet.time = log.time
55
74
  packet.severity = level_map[log.level]
@@ -0,0 +1,49 @@
1
+ module SemanticLogger
2
+ module Formatters
3
+ # The host name and the application name (the TAG) that the formatters building a remote syslog
4
+ # packet (Syslog and SyslogCee) write in its header.
5
+ #
6
+ # The syslog_protocol gem, following RFC 3164, allows only printable ASCII characters other than
7
+ # the space (33 to 126) in either, and up to 32 in the TAG, and raises for any other, which made
8
+ # the formatter lose every entry, such as for an application named "Café", or with a name over
9
+ # 32 characters. So the other characters are left out, as the spaces always were from the TAG,
10
+ # and the TAG is cut to 32 characters. When no character is left, "localhost" or
11
+ # "SemanticLogger" is written instead.
12
+ #
13
+ # Each is worked out once, and again only when the host or application name changes.
14
+ module SyslogHeader
15
+ # The most characters that the TAG of a syslog header can hold.
16
+ MAX_TAG_SIZE = 32
17
+
18
+ # Written in place of a host name with no character left.
19
+ DEFAULT_HOSTNAME = "localhost".encode(Encoding::US_ASCII).freeze
20
+
21
+ # Written in place of an application name with no character left.
22
+ DEFAULT_TAG = "SemanticLogger".encode(Encoding::US_ASCII).freeze
23
+
24
+ private
25
+
26
+ # Returns [String] the host name as the syslog header holds it.
27
+ def syslog_hostname(host) = syslog_header_field(:hostname, host, DEFAULT_HOSTNAME)
28
+
29
+ # Returns [String] the application name as the TAG of the syslog header holds it.
30
+ def syslog_tag(application) = syslog_header_field(:tag, application, DEFAULT_TAG, MAX_TAG_SIZE)
31
+
32
+ # Returns [String] the field cleaned (see SyslogHeader), frozen, from the cache when the text
33
+ # is the one it was worked out from, or holds the same characters, such as an appender's own
34
+ # name that was changed in place, which the cache keeps a frozen copy of. Any other object,
35
+ # other than a Symbol, is read as its #to_s first, so that one changed in place is noticed too.
36
+ def syslog_header_field(field, text, fallback, max_size = nil)
37
+ text = text.to_s unless text.is_a?(String) || text.is_a?(Symbol)
38
+ cached = (@syslog_header_fields ||= {})[field]
39
+ return cached.last if cached && (cached.first.equal?(text) || cached.first == text)
40
+
41
+ value = text.to_s.b.delete("^\x21-\x7E")
42
+ value = value[0, max_size] if max_size
43
+ value = value.empty? ? fallback : value.force_encoding(Encoding::US_ASCII).freeze
44
+ @syslog_header_fields[field] = [text.is_a?(String) && !text.frozen? ? text.dup.freeze : text, value]
45
+ value
46
+ end
47
+ end
48
+ end
49
+ end
@@ -14,6 +14,7 @@ module SemanticLogger
14
14
  autoload :Logfmt, "semantic_logger/formatters/logfmt"
15
15
  autoload :Pattern, "semantic_logger/formatters/pattern"
16
16
  autoload :SyslogCee, "semantic_logger/formatters/syslog_cee"
17
+ autoload :SyslogHeader, "semantic_logger/formatters/syslog_header"
17
18
  autoload :NewRelicLogs, "semantic_logger/formatters/new_relic_logs"
18
19
  autoload :Loki, "semantic_logger/formatters/loki"
19
20
 
@@ -23,11 +23,20 @@ module SemanticLogger
23
23
  when String
24
24
  LEVELS.index(level.downcase.to_sym)
25
25
  when Integer
26
- MAPPED_LEVELS[level]
26
+ # Bounded first, since Array#[] raises RangeError for an Integer too large for a C long.
27
+ MAPPED_LEVELS[level] if level.abs <= MAPPED_LEVELS.size
27
28
  end ||
28
29
  raise(ArgumentError, "Invalid level:#{level.inspect} being requested. Must be one of #{LEVELS.inspect}")
29
30
  end
30
31
 
32
+ # Returns [true|false] whether the supplied value is a level that #index accepts.
33
+ # Never raises, so it can be used to check values that come from untrusted data.
34
+ def self.valid?(level)
35
+ !index(level).nil?
36
+ rescue ArgumentError
37
+ false
38
+ end
39
+
31
40
  # Returns the symbolic level for the supplied level index
32
41
  def self.level(level_index)
33
42
  LEVELS[level_index]