Module: ActFluentLoggerRails::Logger

Defined in:
lib/act-fluent-logger-rails/logger.rb

Constant Summary collapse

SEV_LABEL =

Severity label for logging. (max 5 char)

%w(DEBUG INFO WARN ERROR FATAL ANY)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.new(config_file: Rails.root.join("config", "fluent-logger.yml"), log_tags: {}, settings: {}, flush_immediately: false) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/act-fluent-logger-rails/logger.rb', line 14

def self.new(config_file: Rails.root.join("config", "fluent-logger.yml"),
             log_tags: {},
             settings: {},
             flush_immediately: false)
  Rails.application.config.log_tags = log_tags.values
  if Rails.application.config.respond_to?(:action_cable)
    Rails.application.config.action_cable.log_tags = log_tags.values.map do |x|
      case
      when x.respond_to?(:call)
        x
      when x.is_a?(Symbol)
        -> (request) { request.send(x) }
      else
        -> (request) { x }
      end
    end
  end
  if (0 == settings.length)
    fluent_config = if ENV["FLUENTD_URL"]
                      self.parse_url(ENV["FLUENTD_URL"])
                    else
                      YAML.load(ERB.new(config_file.read).result)[Rails.env]
                    end
    settings = {
      tag:  fluent_config['tag'],
      host: fluent_config['fluent_host'],
      port: fluent_config['fluent_port'],
      nanosecond_precision: fluent_config['nanosecond_precision'],
      messages_type: fluent_config['messages_type'],
      severity_key: fluent_config['severity_key'],
      tls_options: fluent_config['tls_options']&.transform_keys { |k| k.to_sym }
    }
  end

  settings[:flush_immediately] ||= flush_immediately

  level = SEV_LABEL.index(Rails.application.config.log_level.to_s.upcase)
  logger = ActFluentLoggerRails::FluentLogger.new(settings, level, log_tags)
  logger = ActiveSupport::TaggedLogging.new(logger)
  logger.extend self
end

.parse_url(fluentd_url) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/act-fluent-logger-rails/logger.rb', line 56

def self.parse_url(fluentd_url)
  uri = URI.parse fluentd_url
  params = CGI.parse uri.query

  {
    fluent_host: uri.host,
    fluent_port: uri.port,
    tag: uri.path[1..-1],
    nanosecond_precision: params['nanosecond_precision'].try(:first),
    messages_type: params['messages_type'].try(:first),
    severity_key: params['severity_key'].try(:first),
  }.stringify_keys
end

Instance Method Details

#tagged(*tags) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/act-fluent-logger-rails/logger.rb', line 70

def tagged(*tags)
  @tags_thread_key ||= "fluentd_tagged_logging_tags:#{object_id}".freeze
  Thread.current[@tags_thread_key] = tags.flatten
  yield self
ensure
  flush
end