Class: Cloudreach::Logger

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudreach-logger.rb

Overview

this class is just a factory that produces instances of Ruby’s own Logger class

Constant Summary collapse

@@log_levels =
{
  :debug => ::Logger::DEBUG,
  :info  => ::Logger::INFO,
  :warn  => ::Logger::WARN,
  :error => ::Logger::ERROR,
  :fatal => ::Logger::FATAL
}

Class Method Summary collapse

Class Method Details

.create(logfile: nil, level: :debug, stdout: false, name: nil) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/cloudreach-logger.rb', line 49

def self.create(logfile: nil, level: :debug, stdout: false, name: nil)
  if name == nil
    # default to using folder name as name
    name = ENV['PWD']
    name = name.slice(name.rindex('/')+1, name.length)
  end

  if logfile == nil
    env = ENV['RUBY_ENV'] || ENV['RACK_ENV'] || 'development'
    logfile = "log/#{env}.log"
  end

  if !logfile && !stdout
    raise ArgumentError, "You aren't going to log anything. What?"
  end

  if logfile
    file = File.open(logfile, 'a')
    file.sync = true
  end

  if logfile && stdout
    file = MultiIO.new(file, STDOUT)
  elsif !logfile && stdout
    file = STDOUT
  end

  logger = ::Logger.new(file)
  logger.level = @@log_levels[level]
  logger.formatter = lambda { |severity, timestamp, progname, msg|
    if msg.is_a? Hash
      pairs = splunkify(msg)
    else
      pairs = "line=#{sanitize(msg)}"
    end

    if logger._pairs
      pairs = "#{splunkify(logger._pairs)}, #{pairs}"
    end

    "[#{timestamp.strftime("%Y-%m-%d %H:%M:%S")}] service_name=#{sanitize(name)}, severity=#{severity}, #{pairs}\n"
  }

  logger.set(instance_id: ENV['CLOUDREACH_INSTANCE_ID']) if ENV['CLOUDREACH_INSTANCE_ID']
  logger.set(container_id: ENV['CLOUDREACH_CONTAINER_ID']) if ENV['CLOUDREACH_CONTAINER_ID']

  logger
end