Class: SemanticLogger::Appender::IO

Inherits:
Subscriber
  • Object
show all
Defined in:
lib/semantic_logger/appender/io.rb

Instance Attribute Summary

Attributes inherited from Subscriber

#application, #environment, #formatter, #host, #logger, #metrics

Instance Method Summary collapse

Methods inherited from Subscriber

#batch_by_default?, #close, #console_output?, #default_formatter, #level, #should_log?

Constructor Details

#initialize(io, **args) ⇒ IO

Create a Stream Logger appender instance.

Parameters io [IO] An IO stream to which to write the log messages to.

:level [:trace | :debug | :info | :warn | :error | :fatal] Override the log level for this appender. Default: SemanticLogger.default_level

:formatter: [Object|Proc] An instance of a class that implements #call, or a Proc to be used to format the output from this appender Default: Use the built-in formatter (See: #call)

:filter [Regexp|Proc] RegExp: Only include log messages where the class name matches the supplied regular expression. All other messages will be ignored. Proc: Only include log messages where the supplied Proc returns true The Proc must return true or false.

Example require "semantic_logger"

# Enable trace level logging
SemanticLogger.default_level = :info

# Log to screen
SemanticLogger.add_appender(io: $stdout, formatter: :color)

logger = SemanticLogger['test']
logger.info 'Hello World'


40
41
42
43
44
45
46
47
# File 'lib/semantic_logger/appender/io.rb', line 40

def initialize(io, **args, &)
  @io = io
  unless @io.respond_to?(:write)
    raise(ArgumentError, "SemanticLogging::Appender::IO io is not a valid IO instance: #{io.inspect}")
  end

  super(**args, &)
end

Instance Method Details

#console_streamObject



63
64
65
66
67
68
69
# File 'lib/semantic_logger/appender/io.rb', line 63

def console_stream
  if @io.equal?($stdout)
    :stdout
  elsif @io.equal?($stderr)
    :stderr
  end
end

#flushObject

Flush all pending logs to disk. Waits for all sent documents to be written to disk



59
60
61
# File 'lib/semantic_logger/appender/io.rb', line 59

def flush
  @io.flush if @io.respond_to?(:flush)
end

#log(log) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/semantic_logger/appender/io.rb', line 49

def log(log)
  # Since only one appender thread will be writing to the file at a time
  # it is not necessary to protect access to the file with a semaphore
  # Allow this logger to filter out log levels lower than it's own
  @io.write(formatter.call(log, self) << "\n")
  true
end