Last active
August 29, 2015 14:17
-
-
Save mosson/990cc8c484ba42d05093 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
require 'fluent-logger' | |
require 'active_support/core_ext' | |
module CreativeSurvey | |
class FluentLogger < ::Logger | |
attr_reader :config_file | |
def initialize(config_file = Rails.root.join('config', 'fluent-logger.yml.erb'), device = nil) | |
@config_file = config_file | |
super(device.nil? ? ProxyLogger.new(config['host'], config['port']) : device) | |
@formatter = FluentFormatter.new(config['tag']) | |
end | |
def config | |
@config ||= YAML.load(ERB.new(config_file.read).result)[Rails.env] | |
end | |
end | |
# Fluent::Logger::FluentLogger#write が private methodのため | |
class ProxyLogger | |
attr_reader :host, :port | |
def initialize(host = '0.0.0.0', port = 24224) | |
@host, @port = host, port | |
end | |
def fluent | |
@fluent ||= ::Fluent::Logger::FluentLogger.new( | |
nil, | |
host: host, | |
port: port | |
) | |
end | |
def write(msg) | |
fluent.send(:write, msg) | |
end | |
def close | |
fluent.close | |
end | |
end | |
class FluentFormatter < ::Logger::Formatter | |
attr_reader :tag | |
def initialize(tag) | |
@tag = tag | |
super() | |
end | |
def call(severity, timestamp, _progname, msg) | |
[tag, timestamp.to_i, message(severity, msg)] | |
end | |
def message(severity, msg) | |
msg if msg.is_a? Hash | |
{ # Rails.config.log_tags が設定されている場合はこのHashにmergeするといい | |
messages: msg, | |
level: severity || 'ANY' | |
} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment