Class: SemanticLogger::Log
- Inherits:
-
Object
- Object
- SemanticLogger::Log
- Defined in:
- lib/semantic_logger/log.rb
Overview
Log
Class to hold all log entry information
level Log level of the supplied log call :trace, :debug, :info, :warn, :error, :fatal
thread_name Name of the thread in which the logging call was called, or its object id when the thread has no name
name Class name supplied to the logging instance
message Text message to be logged
payload Optional Hash or Ruby Exception object to be logged
time The time at which the log entry was created
duration The time taken to complete a measure call
tags Any tags active on the thread when the log call was made
level_index Internal index of the log level
exception Ruby Exception object to log
metric [Object] Object supplied when measure_x was called
backtrace [Array
call_site [CallSite]
Where the entry was logged: the path, line, and label (usually the method) of the code that
made the log call, when the log level >= SemanticLogger.call_site_level. The one the log call
supplies as call_site:, or nil for call_site: false, or else the first line of a backtrace
it supplies. nil below that level.
metric_amount [Numeric] Used for numeric or counter metrics. For example, the number of inquiries or, the amount purchased etc.
context [Hash] Named contexts that were captured when the log entry was created.
captures [Hash] Objects that an appender captured on the logging thread for its own use when the log entry was created, such as the OpenTelemetry context. Only a formatter built for that appender writes them, as the NewRelicLogs formatter writes the linking metadata its appender captures.
The payload, named tags, context, and dimensions have the values of sensitive keys replaced before the entry is written to any appender, when SemanticLogger.sensitive_keys is set (see #redact).
Constant Summary collapse
- NON_PAYLOAD_KEYS =
Keys passed in without a payload that will be extracted and the remainder passed into the payload.
%i[message exception backtrace call_site duration min_duration log_exception on_exception_level metric metric_amount dimensions].freeze
- ASSIGNABLE_KEYS =
Log attributes that a Hash returned by a logging block can set (see #assign_hash). Its other keys go to the payload, so that it cannot set fields such as :level, :name, or :time.
%i[message exception backtrace duration metric metric_amount dimensions].freeze
- MAX_EXCEPTIONS_TO_UNWRAP =
5
Instance Attribute Summary collapse
-
#backtrace ⇒ Object
Returns the value of attribute backtrace.
-
#call_site ⇒ Object
Returns the value of attribute call_site.
-
#captures ⇒ Object
Returns the value of attribute captures.
-
#context ⇒ Object
Returns the value of attribute context.
-
#dimensions ⇒ Object
Returns the value of attribute dimensions.
-
#duration ⇒ Object
Returns the value of attribute duration.
-
#exception ⇒ Object
Returns the value of attribute exception.
-
#level ⇒ Object
Returns the value of attribute level.
-
#level_index ⇒ Object
Returns the value of attribute level_index.
-
#message ⇒ Object
Returns the value of attribute message.
-
#metric ⇒ Object
Returns the value of attribute metric.
-
#metric_amount ⇒ Object
Returns the value of attribute metric_amount.
-
#name ⇒ Object
Returns the value of attribute name.
-
#named_tags ⇒ Object
Returns the value of attribute named_tags.
-
#payload ⇒ Object
Returns the value of attribute payload.
-
#tags ⇒ Object
Returns the value of attribute tags.
-
#thread_name ⇒ Object
Returns the value of attribute thread_name.
-
#time ⇒ Object
Returns the value of attribute time.
Class Method Summary collapse
-
.argument?(key, value) ⇒ Boolean
Returns [true|false] whether the value can be used as the log argument named by the key.
-
.negative_metric_amount_deprecated ⇒ Object
Reports, once per process, that a log call gave a negative metric amount, which is deprecated: a metric counts upward, and v6 drops a negative amount.
-
.thread_name_for(thread) ⇒ Object
Returns [String] the name that identifies the thread in a log entry: the thread's own name, or its object id when it has none, which Ruby never reuses within a process.
Instance Method Summary collapse
-
#assign(message: nil, payload: nil, min_duration: 0.0, exception: nil, metric: nil, metric_amount: nil, duration: nil, backtrace: nil, call_site: nil, log_exception: :full, on_exception_level: nil, dimensions: nil) ⇒ Object
Assign named arguments to this log entry, supplying defaults where applicable.
-
#assign_hash(hash) ⇒ Object
Assign the Hash returned by a logging block, after #assign has applied the log call.
-
#backtrace_of(exception, cleaner: nil) ⇒ Object
Returns [Array
] the backtrace of the supplied exception, or nil when it has none. -
#backtrace_to_s(cleaner: nil, &block) ⇒ Object
Returns [String] the exception backtrace including all of the child / caused by exceptions.
-
#capture(key, value) ⇒ Object
Keeps the value, captured on the logging thread, for the appender that uses it.
-
#captured(key) ⇒ Object
Returns the value captured with the key, or nil when there is none.
-
#cleansed_message ⇒ Object
Strip the standard Rails colorizing from the logged message.
-
#dimensions? ⇒ Boolean
Returns [true|false] whether the log entry has a metric with dimensions: a Hash that is not empty.
-
#duration_human ⇒ Object
Returns [String] the duration in human readable form.
- #duration_to_s ⇒ Object
-
#each_exception(first = exception) ⇒ Object
Call the block for exception and any nested exception.
-
#exception_details(exception, source: false) ⇒ Object
Returns [String] the detail that Ruby's Exception#detailed_message adds to the message of the supplied exception, without the class name that Ruby also adds.
-
#extract_arguments(payload, message = nil) ⇒ Object
Extract the arguments from a Hash Payload.
-
#extract_file_and_line(stack, short_name = false) ⇒ Object
Extract the file name and line number from the first line of the supplied backtrace.
-
#file_name_and_line(short_name = false) ⇒ Object
Returns [String, Integer] the file name and line number where the entry was logged: from the call site, or else the first line of the backtrace, or of the exception's backtrace.
-
#initialize(name, level, index = nil, thread = Thread.current) ⇒ Log
constructor
Parameters thread: [Thread] The thread whose name, tags, and named tags the entry has.
-
#level_to_s ⇒ Object
Returns [String] single character upper case log level.
-
#make_copyable ⇒ Object
Replaces the values of this entry that cannot be copied to another Ractor, such as a Proc in its payload (see RactorCopy).
-
#metric_only? ⇒ Boolean
A metric only event has a metric but no message or exception.
-
#payload? ⇒ Boolean
Returns [true|false] whether the log entry has a payload.
-
#payload_to_s ⇒ Object
Return the payload in text form Returns nil if payload is missing or empty.
-
#process_info(thread_name_length = 30) ⇒ Object
DEPRECATED.
-
#redact(redactor) ⇒ Object
Replaces this entry's payload, named tags, context, and metric dimensions, the fields that hold keyed data, with copies in which the value of every sensitive key is replaced (see Redactor#redact).
-
#set_context(key, value) ⇒ Object
Lazy initializes the context hash and assigns a key value pair.
- #to_h(host = SemanticLogger.host, application = SemanticLogger.application, environment = SemanticLogger.environment) ⇒ Object
Constructor Details
#initialize(name, level, index = nil, thread = Thread.current) ⇒ Log
Parameters thread: [Thread] The thread whose name, tags, and named tags the entry has. Default: Thread.current
111 112 113 114 115 116 117 118 119 |
# File 'lib/semantic_logger/log.rb', line 111 def initialize(name, level, index = nil, thread = Thread.current) @level = level @thread_name = Log.thread_name_for(thread) @name = name @time = Time.now @tags = Context.(thread) @named_tags = Context.(thread) @level_index = index.nil? ? Levels.index(level) : index end |
Instance Attribute Details
#backtrace ⇒ Object
Returns the value of attribute backtrace.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def backtrace @backtrace end |
#call_site ⇒ Object
Returns the value of attribute call_site.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def call_site @call_site end |
#captures ⇒ Object
Returns the value of attribute captures.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def captures @captures end |
#context ⇒ Object
Returns the value of attribute context.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def context @context end |
#dimensions ⇒ Object
Returns the value of attribute dimensions.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def dimensions @dimensions end |
#duration ⇒ Object
Returns the value of attribute duration.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def duration @duration end |
#exception ⇒ Object
Returns the value of attribute exception.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def exception @exception end |
#level ⇒ Object
Returns the value of attribute level.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def level @level end |
#level_index ⇒ Object
Returns the value of attribute level_index.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def level_index @level_index end |
#message ⇒ Object
Returns the value of attribute message.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def @message end |
#metric ⇒ Object
Returns the value of attribute metric.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def metric @metric end |
#metric_amount ⇒ Object
Returns the value of attribute metric_amount.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def metric_amount @metric_amount end |
#name ⇒ Object
Returns the value of attribute name.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def name @name end |
#named_tags ⇒ Object
Returns the value of attribute named_tags.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def @named_tags end |
#payload ⇒ Object
Returns the value of attribute payload.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def payload @payload end |
#tags ⇒ Object
Returns the value of attribute tags.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def @tags end |
#thread_name ⇒ Object
Returns the value of attribute thread_name.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def thread_name @thread_name end |
#time ⇒ Object
Returns the value of attribute time.
102 103 104 |
# File 'lib/semantic_logger/log.rb', line 102 def time @time end |
Class Method Details
.argument?(key, value) ⇒ Boolean
Returns [true|false] whether the value can be used as the log argument named by the key.
Never raises, so it can check values from untrusted data before they are passed to #assign. A nil value is never an argument, since it means the argument was not supplied. Arguments without a validator in ARGUMENT_VALIDATORS (such as :message, :metric, or :exception, which #assign logs as an ArgumentError when it is not an Exception) accept any other value.
247 248 249 250 251 252 |
# File 'lib/semantic_logger/log.rb', line 247 def self.argument?(key, value) return false if value.nil? || !NON_PAYLOAD_KEYS.include?(key) validator = ARGUMENT_VALIDATORS[key] validator.nil? || validator.call(value) end |
.negative_metric_amount_deprecated ⇒ Object
Reports, once per process, that a log call gave a negative metric amount, which is deprecated: a metric counts upward, and v6 drops a negative amount. The entry is still logged with it.
Only once, so that a negative amount in a loop does not report a warning for each log call, and only once deprecation warnings are on, so that turning them on later still reports it. Not from a Ractor other than the main one, which cannot record that it was reported. Two threads that report at the same moment can each report it, which costs a second warning at worst. Remove in v6, where the metrics API drops a negative amount instead.
Internal: called by #assign and #assign_hash only (@api private).
229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/semantic_logger/log.rb', line 229 def self.negative_metric_amount_deprecated return if !Warning[:deprecated] || RactorSupport.other_ractor? || @negative_metric_amount_reported @negative_metric_amount_reported = true Deprecation.warn( "A negative metric_amount is deprecated: a metric counts upward, and v6 drops a negative amount. " \ "Count what goes down as a metric of its own, such as \"cart/items_removed\". " \ "This is reported for the first negative amount only. See " \ "https://logger.reidmorrison.com/upgrading.html#negative-metric-amounts" ) end |
.thread_name_for(thread) ⇒ Object
Returns [String] the name that identifies the thread in a log entry: the thread's own name, or its object id when it has none, which Ruby never reuses within a process.
100 |
# File 'lib/semantic_logger/log.rb', line 100 def self.thread_name_for(thread) = thread.name || thread.object_id.to_s |
Instance Method Details
#assign(message: nil, payload: nil, min_duration: 0.0, exception: nil, metric: nil, metric_amount: nil, duration: nil, backtrace: nil, call_site: nil, log_exception: :full, on_exception_level: nil, dimensions: nil) ⇒ Object
Assign named arguments to this log entry, supplying defaults where applicable
Returns [true|false] whether this log entry should be logged
Example:
logger.info(name: 'value')
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/semantic_logger/log.rb', line 127 def assign(message: nil, payload: nil, min_duration: 0.0, exception: nil, metric: nil, metric_amount: nil, duration: nil, backtrace: nil, call_site: nil, log_exception: :full, on_exception_level: nil, dimensions: nil) self. = self.payload = payload self.duration = duration self.metric = metric self.metric_amount = metric_amount self.dimensions = dimensions Log.negative_metric_amount_deprecated if counted_negative_amount? if exception unless exception.is_a?(Exception) exception = ArgumentError.new("Invalid value for logger exception: #{Utils.safe_inspect(exception)}") exception.set_backtrace(Utils.extract_backtrace(caller)) end case log_exception when :full self.exception = exception when :partial # The class and message of the exception, then of each exception that caused it: the same # exceptions that :full writes (see #backtrace_to_s). self. = with_class(" -- Exception: ", exception, ": ", (exception)) each_exception(exception) { |ex, depth| self. = with_cause(ex) unless depth.zero? } when nil, :none # Log the message without the exception that was raised nil else raise(ArgumentError, "Invalid value:#{log_exception.inspect} for argument :log_exception") end # On exception change the log level if on_exception_level # Normalized through the index, so that a level supplied as a String or an Integer is # still stored as its Symbol. self.level_index = Levels.index(on_exception_level) self.level = Levels.level(level_index) end end # Elastic logging: Log when :duration exceeds :min_duration # Except if there is an exception when it will always be logged return false if duration && (duration < min_duration) && exception.nil? if backtrace backtrace = self.backtrace = Utils.extract_backtrace(backtrace) elsif level_index >= SemanticLogger.backtrace_level_index self.backtrace = Utils.extract_backtrace(caller) end # A call site or backtrace supplied by the log call says where the entry is about, such as the # application code that ran a query, or the thread whose backtrace is logged. if level_index >= SemanticLogger.call_site_level_index self.call_site = CallSite.locate(call_site: call_site, backtrace: backtrace) end true end |
#assign_hash(hash) ⇒ Object
Assign the Hash returned by a logging block, after #assign has applied the log call.
A block can return untrusted data, such as a parsed request body, so its keys are classified by #extract_arguments, as for a Hash passed after the message. A log argument is only assigned when this entry does not have it yet (an exception must also be an Exception), and otherwise goes to the payload like any other key. Whatever the key order, the log call's values win, then the block's top-level keys, then those of its :payload. No supplied Hash is modified.
206 207 208 209 210 211 212 213 214 215 216 217 |
# File 'lib/semantic_logger/log.rb', line 206 def assign_hash(hash) args = extract_arguments(hash) added = args.delete(:payload) assigned, kept = args.partition { |key, value| block_attribute?(key, value) } assigned.each { |key, value| public_send(:"#{key}=", value) } # Once per process, so that #assign having reported it already does no harm. Log.negative_metric_amount_deprecated if counted_negative_amount? # An argument this entry already has wins over the block's :payload, like the block's other keys. added = merge_payload(kept.to_h, added) unless kept.empty? self.payload = merge_payload(payload, added) self end |
#backtrace_of(exception, cleaner: nil) ⇒ Object
Returns [Array
Parameters
exception: [Exception]
This entry's exception, or one of its causes (see #each_exception).
cleaner: [Object|nil]
A backtrace cleaner, such as Rails.backtrace_cleaner, that responds to #clean or
#call. The backtrace is returned as it cleans it (see BacktraceCleaning.clean), and the
exception's own backtrace is left unchanged. Any other value, such as the true of the
formatter option, is reported to the internal logger as a broken cleaner, and the full
backtrace is returned.
Default: nil (the exception's own backtrace)
A cleaned backtrace is frozen, as are its lines, and cached on this entry, since every appender's formatter may ask for it. Nothing is cached while the exception has no backtrace: one that was never raised can be given one later, as the Bugsnag appender does.
358 359 360 361 362 |
# File 'lib/semantic_logger/log.rb', line 358 def backtrace_of(exception, cleaner: nil) return exception.backtrace unless cleaner && exception.backtrace cached([:backtrace, exception.__id__, cleaner.__id__]) { BacktraceCleaning.clean(exception.backtrace, cleaner) } end |
#backtrace_to_s(cleaner: nil, &block) ⇒ Object
Returns [String] the exception backtrace including all of the child / caused by exceptions
When a cleaner is supplied, each backtrace is cleaned by it first (see #backtrace_of).
When a block is supplied, each cause's message and each backtrace line is passed to it, in the order they are written, and the value it returns is written in its place. This lets a caller, for example a formatter, transform that text while this method keeps the layout.
Lines are separated by a line break, with none added before the first or after the last, even when an exception in the chain has no backtrace, so that a caller can put the text on the line after its own.
Never raises because of what it writes: each cause is named as Utils.exception_name names it,
as Ruby names its class, without asking the class, such as #<Class:0x000...> for an anonymous
class, which has no name; its message is read as Utils.exception_message reads it, so
that a #message that raises, or does not return a String, cannot make it raise, nor pass the
block anything but a String; and the lines are joined as Utils.join_lines joins them, whatever
their encodings.
Example:
log.backtrace_to_s { |text| text.gsub("\n", "\\n") }
log.backtrace_to_s(cleaner: Rails.backtrace_cleaner)
387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/semantic_logger/log.rb', line 387 def backtrace_to_s(cleaner: nil, &block) lines = [] each_exception do |exception, i| unless i.zero? = block ? yield((exception)) : (exception) lines << Utils.join_texts("Cause: ", Utils.exception_name(exception), ": ", ) end backtrace = backtrace_of(exception, cleaner: cleaner) || [] lines.concat(block ? backtrace.map(&block) : backtrace) end Utils.join_lines(lines) end |
#capture(key, value) ⇒ Object
Keeps the value, captured on the logging thread, for the appender that uses it. Unlike the context, formatters do not write it, unless one is built for that appender and reads its key.
500 |
# File 'lib/semantic_logger/log.rb', line 500 def capture(key, value) = (self.captures ||= {}).store(key, value) |
#captured(key) ⇒ Object
Returns the value captured with the key, or nil when there is none.
503 |
# File 'lib/semantic_logger/log.rb', line 503 def captured(key) = captures&.[](key) |
#cleansed_message ⇒ Object
Strip the standard Rails colorizing from the logged message.
Note: This unconditionally strips ANSI colorization, and is used to keep terminal escape codes out of structured (JSON/Loki) output. It is distinct from Formatters::Base#escape_control_characters, which instead escapes (preserves) control characters and is opt-in for the text formatters.
A message tagged UTF-8 can hold invalid bytes, for example a request parameter that Rack decoded from "%FF", or be in another encoding, such as a binary request body. Stripping or matching such a String raises, so it is converted to valid UTF-8 first, dropping the invalid bytes, as the JSON formatters do.
468 469 470 471 472 473 |
# File 'lib/semantic_logger/log.rb', line 468 def msg = Utils.encode_utf8_string(.to_s) return msg.strip unless msg.include?("\e") msg.gsub(/\e\[[\d;]*[mz]?|\e/, "").strip end |
#dimensions? ⇒ Boolean
Returns [true|false] whether the log entry has a metric with dimensions: a Hash that is not empty.
487 |
# File 'lib/semantic_logger/log.rb', line 487 def dimensions? = metric ? dimensions.is_a?(Hash) && !dimensions.empty? : false |
#duration_human ⇒ Object
Returns [String] the duration in human readable form
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 |
# File 'lib/semantic_logger/log.rb', line 416 def duration_human return nil unless duration seconds = duration / 1000 if seconds >= 86_400.0 # 1 day "#{(seconds / 86_400).to_i}d #{Time.at(seconds).utc.strftime('%-Hh %-Mm')}" elsif seconds >= 3600.0 # 1 hour Time.at(seconds).utc.strftime("%-Hh %-Mm") elsif seconds >= 60.0 # 1 minute Time.at(seconds).utc.strftime("%-Mm %-Ss") elsif seconds >= 1.0 # 1 second "#{format('%.3f', seconds)}s" else duration_to_s end end |
#duration_to_s ⇒ Object
404 405 406 |
# File 'lib/semantic_logger/log.rb', line 404 def duration_to_s "#{duration.to_i}ms" if duration end |
#each_exception(first = exception) ⇒ Object
Call the block for exception and any nested exception
Parameters first: [Exception|nil] The exception to start from, for one that this entry does not keep, such as the one that log_exception: :partial writes into the message. Default: this entry's exception
Yields each exception with its depth: 0 for the first one, 1 for the exception that caused it, and so on.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'lib/semantic_logger/log.rb', line 302 def each_exception(first = exception) # With thanks to https://github.com/bugsnag/bugsnag-ruby/blob/6348306e44323eee347896843d16c690cd7c4362/lib/bugsnag/notification.rb#L81 exceptions = [] ex = first while !ex.nil? && !exceptions.include?(ex) && exceptions.length < MAX_EXCEPTIONS_TO_UNWRAP exceptions << ex yield(ex, exceptions.length - 1) ex = if ex.respond_to?(:cause) && ex.cause ex.cause elsif ex.respond_to?(:continued_exception) && ex.continued_exception ex.continued_exception elsif ex.respond_to?(:original_exception) && ex.original_exception ex.original_exception end end end |
#exception_details(exception, source: false) ⇒ Object
Returns [String] the detail that Ruby's Exception#detailed_message adds to the message of the supplied exception, without the class name that Ruby also adds. Since Ruby 3.2 this is where did_you_mean suggestions ("Did you mean? upcase") and the detail an exception class supplies by overriding #detailed_message appear, rather than in #message. Returns nil when there is no detail.
Parameters exception: [Exception] This entry's exception, or one of its causes (see #each_exception). source: [true|false] Whether to include error_highlight's snippet of the failing source line, for example "user_name.upcas" with "^^^^^^" under the unknown method. It re-parses that source file on every call, so it is about 100 times slower, and it copies source code into the log. Default: false
The result is cached on this entry, since every appender's formatter may ask for it.
338 339 340 |
# File 'lib/semantic_logger/log.rb', line 338 def exception_details(exception, source: false) cached([:exception_details, exception.__id__, source]) { ExceptionDetails.extract(exception, source: source) } end |
#extract_arguments(payload, message = nil) ⇒ Object
Extract the arguments from a Hash Payload
The hash can hold untrusted data, so this never fails because of its content: keys that are not log attributes, or that hold a value that is not valid for it (see .argument?), are kept in the payload. A log attribute key with a nil value counts as not supplied, so #assign uses its default. When the hash supplies an explicit :payload, any other keys are merged into it, and win over its values of the same name, since the explicit payload is where untrusted data goes (see docs/security.md).
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/semantic_logger/log.rb', line 262 def extract_arguments(payload, = nil) raise(ArgumentError, "payload must be a Hash") unless payload.is_a?(Hash) = nil if == "" explicit = HASH_KEY.bind_call(payload, :payload) new_payload = {} args = {} payload.each_pair do |key, value| if explicit && key == :payload args[:payload] = value elsif key == :message && !.nil? # Supplied message takes precedence new_payload[key] = value unless explicit elsif Log.argument?(key, value) args[key] = value elsif value.nil? && NON_PAYLOAD_KEYS.include?(key) # Not supplied, so #assign uses its default next else new_payload[key] = value end end unless new_payload.empty? args[:payload] = explicit ? merge_payload(new_payload, args[:payload]) : new_payload end args[:message] = if args end |
#extract_file_and_line(stack, short_name = false) ⇒ Object
Extract the file name and line number from the first line of the supplied backtrace.
445 446 447 |
# File 'lib/semantic_logger/log.rb', line 445 def extract_file_and_line(stack, short_name = false) CallSite.parse(stack&.first)&.file_name_and_line(short_name: short_name) end |
#file_name_and_line(short_name = false) ⇒ Object
Returns [String, Integer] the file name and line number where the entry was logged: from the call site, or else the first line of the backtrace, or of the exception's backtrace. nil when there are none.
452 453 454 455 |
# File 'lib/semantic_logger/log.rb', line 452 def file_name_and_line(short_name = false) call_site&.file_name_and_line(short_name: short_name) || extract_file_and_line(backtrace || exception&.backtrace, short_name) end |
#level_to_s ⇒ Object
Returns [String] single character upper case log level
434 |
# File 'lib/semantic_logger/log.rb', line 434 def level_to_s = level.to_s[0..0].upcase |
#make_copyable ⇒ Object
Replaces the values of this entry that cannot be copied to another Ractor, such as a Proc in its payload (see RactorCopy). Returns self. Experimental, Ruby 4.0 and later only.
526 527 528 529 530 531 532 533 |
# File 'lib/semantic_logger/log.rb', line 526 def make_copyable %i[message payload tags named_tags context captures metric dimensions].each do |field| public_send(:"#{field}=", RactorCopy.copyable(public_send(field))) end self.exception = RactorCopy.copyable_exception(exception) if exception @cache = nil self end |
#metric_only? ⇒ Boolean
A metric only event has a metric but no message or exception.
522 |
# File 'lib/semantic_logger/log.rb', line 522 def metric_only? = metric && .nil? && exception.nil? |
#payload? ⇒ Boolean
Returns [true|false] whether the log entry has a payload
484 |
# File 'lib/semantic_logger/log.rb', line 484 def payload? = !(payload.nil? || (payload.respond_to?(:empty?) && payload.empty?)) |
#payload_to_s ⇒ Object
Return the payload in text form Returns nil if payload is missing or empty
Rendered with #inspect, or with the block when given (for example Amazing Print). A payload nested too deeply for either is first cut off at Utils::MAX_JSON_SAFE_DEPTH, rather than raising SystemStackError (see Utils.safe_inspect).
481 |
# File 'lib/semantic_logger/log.rb', line 481 def payload_to_s(&) = (Utils.safe_inspect(payload, &) if payload?) |
#process_info(thread_name_length = 30) ⇒ Object
DEPRECATED
437 438 439 440 441 442 |
# File 'lib/semantic_logger/log.rb', line 437 def process_info(thread_name_length = 30) file, line = file_name_and_line(true) file_name = " #{file}:#{line}" if file "#{$$}:#{format("%.#{thread_name_length}s", thread_name)}#{file_name}" end |
#redact(redactor) ⇒ Object
Replaces this entry's payload, named tags, context, and metric dimensions, the fields that hold keyed data, with copies in which the value of every sensitive key is replaced (see Redactor#redact). Returns self.
The values replaced are left as they are, since they can be the application's own, or be shared with other entries, as named tags are. A field with no sensitive key is kept as it is.
Called once, before the entry is written to any appender (see SemanticLogger.sensitive_keys=).
513 514 515 516 517 518 519 |
# File 'lib/semantic_logger/log.rb', line 513 def redact(redactor) self.payload = redactor.redact(payload) self. = redactor.redact() self.context = redactor.redact(context) self.dimensions = redactor.redact(dimensions) self end |
#set_context(key, value) ⇒ Object
Lazy initializes the context hash and assigns a key value pair.
496 |
# File 'lib/semantic_logger/log.rb', line 496 def set_context(key, value) = (self.context ||= {}).store(key, value) |
#to_h(host = SemanticLogger.host, application = SemanticLogger.application, environment = SemanticLogger.environment) ⇒ Object
489 490 491 492 493 |
# File 'lib/semantic_logger/log.rb', line 489 def to_h(host = SemanticLogger.host, application = SemanticLogger.application, environment = SemanticLogger.environment) logger = Struct.new(:host, :application, :environment).new(host, application, environment) SemanticLogger::Formatters::Raw.new.call(self, logger) end |