Class: SemanticLogger::Appenders

Inherits:
Concurrent::Array
  • Object
show all
Defined in:
lib/semantic_logger/appenders.rb

Overview

Manage a collection of appenders.

While the process exits, it also knows which of its appenders it skips: those without a queue of their own whose destination failed meanwhile, and how many log messages each has not been given since (see #process_exiting=).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger = Processor.logger.dup) ⇒ Appenders

Returns a new instance of Appenders.



19
20
21
22
23
24
25
# File 'lib/semantic_logger/appenders.rb', line 19

def initialize(logger = Processor.logger.dup)
  @logger      = logger
  @logger.name = self.class.name
  @exiting     = false
  @skipped     = {}.compare_by_identity
  super()
end

Instance Attribute Details

#logger ⇒ Object

Returns the value of attribute logger.



17
18
19
# File 'lib/semantic_logger/appenders.rb', line 17

def logger
  @logger
end

Instance Method Details

#add(**args) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/semantic_logger/appenders.rb', line 27

def add(**args, &)
  appender = SemanticLogger::Appender.factory(**args, &)

  stream = appender.respond_to?(:console_stream) && appender.console_stream
  if stream && console_streams.include?(stream)
    logger.warn "Ignoring attempt to add a second #{stream} console appender since it " \
                "would result in duplicate console output."
    return
  end

  self << appender
  appender
end

#close ⇒ Object

Flush and close every appender, then remove those closed. An appender that fails is reported, and the others are still closed.

A stack overflow is raised at once, as #log raises it, since the thread must not carry on: on macOS a second stack overflow on the same thread crashes Ruby. The appenders already closed are still removed. The one that overflowed the stack, and those after it, not yet closed, stay listed, as one whose close fails does.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/semantic_logger/appenders.rb', line 122

def close
  closed_appenders = []
  each do |appender|
    logger.trace "Closing appender: #{appender.name}"
    appender.flush
    appender.close
    closed_appenders << appender
  rescue SystemStackError
    raise
  rescue Exception => e
    logger.error "Failed to close appender: #{appender.name}", e
  end
  logger.trace "All appenders closed and removed from appender list"
ensure
  # Delete appenders outside the #each above which prevents changes during iteration.
  closed_appenders&.each { |appender| delete(appender) }
end

#console_output? ⇒ Boolean

Whether any of the existing appenders already output to the console? I.e. Writes to stdout or stderr.

Returns:

  • (Boolean)


48
49
50
# File 'lib/semantic_logger/appenders.rb', line 48

def console_output?
  console_streams.any?
end

#console_streams ⇒ Object

The console streams (:stdout and/or :stderr) already being written to by the existing appenders.



42
43
44
# File 'lib/semantic_logger/appenders.rb', line 42

def console_streams
  filter_map { |appender| appender.console_stream if appender.respond_to?(:console_stream) }
end

#flush ⇒ Object

Flush every appender. An appender that fails is reported, and the others are still flushed.

While the process exits, an appender that is skipped (see #process_exiting=) is first reported, with the number of log messages it has not been given since it was last reported, then flushed too, so that it delivers the messages it already accepted, such as those that the producer of a :kafka appender holds.



103
104
105
106
107
108
109
110
111
112
113
# File 'lib/semantic_logger/appenders.rb', line 103

def flush
  skipped = skipped_appenders
  each do |appender|
    report_skipped(appender, skipped[appender]) if skipped.key?(appender)
    logger.trace "Flushing appender: #{appender.name}"
    appender.flush
  rescue Exception => e
    logger.error "Failed to flush appender: #{appender.name}", e
  end
  logger.trace "All appenders flushed"
end

#holding_up?(thread = Thread.current) ⇒ Boolean

Returns [true|false] whether the thread is the worker thread of one of the appenders while that appender's queue is full, or a flush or close of it is waiting (see QueueProcessor#holding_up?): the thread that writes to every appender may then be waiting for it, to make room or to run that request. Takes no lock, as #worker_thread? takes none.

Returns:

  • (Boolean)


203
204
205
# File 'lib/semantic_logger/appenders.rb', line 203

def holding_up?(thread = Thread.current)
  any? { |appender| appender.respond_to?(:holding_up?) && appender.holding_up?(thread) }
end

#log(log) ⇒ Object

Write the log message to every appender that should log it. An appender that fails is reported, and the others still write the message.

While the process exits, an appender without a queue of its own is skipped once its destination has failed, and the message counted as not given to it (see #process_exiting=).

The values of the sensitive keys are first replaced, once, so that no appender writes them (see SemanticLogger.sensitive_keys=).

A stack overflow is not a failure of the appender but of the thread, which must not overflow again: on macOS a second stack overflow on the same thread crashes Ruby. It is raised to the processor running this thread instead, and the message goes to no further appenders.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/semantic_logger/appenders.rb', line 79

def log(log)
  redactor = SemanticLogger.redactor
  log.redact(redactor) if redactor
  skipped = skipped_appenders
  each do |appender|
    writing = appender.should_log?(log)
    next unless writing
    next skipped[appender].discarded += 1 if skipped.key?(appender)

    appender.log(log)
  rescue SystemStackError
    raise
  rescue Exception => e
    logger.error "Failed to log to appender: #{appender.name}", e
    skip_while_exiting(appender, e) if writing
  end
end

#process_exiting=(exiting) ⇒ Object

Tell each appender added with async: true or in batches whether the process is exiting: true before the flush at exit, and false once it has returned (see QueueProcessor#process_exiting=). Each one's queue processor is told straight away, rather than through the queue of the thread that writes to every appender, which can be held up handing an entry to the full queue of an appender whose worker thread is backing off during an outage. Takes no lock, so that it can be called from any thread, or a signal trap. An appender that raises is reported, as for #flush, and the others are still told, so that the flush at exit still runs.

The appenders without a queue of their own are written to here, one log message after another, by the thread that writes to every appender, so that during an outage the flush at exit would wait while each message queued ahead of it failed in turn, up to a timeout each against a server that does not answer. So while the process exits, once the destination of such an appender fails, other than for the content of a message (see Subscriber#message_error?), it is skipped until the process no longer exits: #log gives it no more messages, counting them, and #flush reports them, then still flushes it, so that it delivers what it already accepted. The other appenders are still given every message.

It applies only in the process that exits, not in a child process forked meanwhile.



174
175
176
177
178
179
180
181
182
# File 'lib/semantic_logger/appenders.rb', line 174

def process_exiting=(exiting)
  @skipped = {}.compare_by_identity if exiting
  @exiting = exiting && ::Process.pid
  each do |appender|
    appender.process_exiting = exiting if appender.respond_to?(:process_exiting=)
  rescue Exception => e
    logger.error "Failed to tell appender that the process is exiting: #{appender.name}", e
  end
end

#renew_after_fork ⇒ Object

After a fork, replace the queue and worker thread of each appender added with async: true or in batches with the child's own, on the calling thread (see QueueProcessor#renew_after_fork). Takes no lock, so that it can be called from a signal trap.



187
188
189
# File 'lib/semantic_logger/appenders.rb', line 187

def renew_after_fork
  each { |appender| appender.renew_after_fork if appender.respond_to?(:renew_after_fork) }
end

#reopen ⇒ Object

After a fork, or a log rotation, reopen each appender. Called on the thread that writes to the appenders: the worker thread of the main Processor, or the calling thread with sync!. An appender added with async: true or in batches is asked to reopen, by its own worker thread (see Appender::Async#reopen).



144
145
146
147
148
149
150
151
152
153
154
# File 'lib/semantic_logger/appenders.rb', line 144

def reopen
  each do |appender|
    next unless appender.respond_to?(:reopen)

    logger.trace "Reopening appender: #{appender.name}"
    appender.reopen
  rescue Exception => e
    logger.error "Failed to re-open appender: #{appender.name}", e
  end
  logger.trace "All appenders re-opened"
end

#stats ⇒ Object

Returns [Array] operational statistics for each appender.

Appenders that run asynchronously (see SemanticLogger::Appender::Async#stats) report their queue size and processed/dropped/failed counts. Appenders that log inline on the processor thread report only their name with async: false.



57
58
59
60
61
62
63
64
65
# File 'lib/semantic_logger/appenders.rb', line 57

def stats
  map do |appender|
    if appender.respond_to?(:stats)
      appender.stats
    else
      {name: appender.name, async: false}
    end
  end
end

#worker_thread?(thread = Thread.current) ⇒ Boolean

Returns [true|false] whether the thread is the worker thread of one of the appenders: one added with async: true or in batches, which writes to it (see QueueProcessor#worker_thread?). The thread that writes to every appender may be waiting for it, so it must not wait for that thread. Takes no lock, so that it can be called from a signal trap.

Returns:

  • (Boolean)


195
196
197
# File 'lib/semantic_logger/appenders.rb', line 195

def worker_thread?(thread = Thread.current)
  any? { |appender| appender.respond_to?(:worker_thread?) && appender.worker_thread?(thread) }
end