1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでLTSV形式でLogを出す

Last updated at Posted at 2016-10-09

Gemとかあるのかもしれないけど、とりあえず自分で作ったものを使ってる

module Utils
  class FormattedLogger
    class << self
      def create(path, taggers=nil)
        unless File.exist?(File.dirname(path))
          FileUtils.mkdir_p(File.dirname(path))
        end
        logger = Logger.new(path, taggers)
        logger.formatter = proc do |severity, datetime, progname, msg|
          log = []
          log << "pid:#{$PROCESS_ID}"
          log << "level:#{severity}"
          log << "datetime:#{datetime}"

          file_caller = caller.find { |item| item.include?("#{Rails.root}/app") }
          if file_caller.present?
            filename, line_num = file_caller.match(/(?<path>.*):(?<line_num>\d+)/).tap do |path_and_line_num|
              break [
                path_and_line_num['path'].gsub("#{Rails.root}", ''),
                path_and_line_num['line_num']
              ]
            end
            log << "filename:#{filename}"
            log << "line_num:#{line_num}"
          end
          case msg
          when Hash
            msg.each do |key, val|
              log << "#{key}:#{val}"
            end
          else
            msg_divided_uuid = msg.match(/^\[(.*)\](.*)/)
            if msg_divided_uuid
              log << "uuid:#{msg_divided_uuid[1]}"
              log << "message:#{msg_divided_uuid[2].strip}"
            else
              log << "message:#{msg}"
            end
          end
          "#{log.join("\t")}\n"
        end
        ActiveSupport::TaggedLogging.new(logger)
      rescue StandardError
        logger = ActiveSupport::TaggedLogging.new(ActiveSupport::BufferedLogger.new(STDERR))
        logger.level = ActiveSupport::BufferedLogger::WARN
        logger.warn(
          "Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " \
          'The log level has been raised to WARN and the output directed to STDERR until the problem is fixed.'
        )
        logger
      end
    end
  end
end

lib配下に置くと、 config/application.rb の読み込み中だとまだ読み込まれていないみたいなので、下記のような記載が必要

require File.expand_path('../boot', __FILE__)
$LOAD_PATH.push(File.join(File.dirname(__FILE__), "../lib")) ## 追加

require 'rails/all'
require 'utils/formatted_logger' ## 追加

module TestApp
  class Application < Rails::Application
    ## 追加する
    config.logger = Utils::FormattedLogger.create(config.paths['log'].first, 'weekly')
  end
end
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?