Sha256: 57026b0001e31308d22146de938495761638baa7000b9085873492b210b65445

Contents?: true

Size: 1.77 KB

Versions: 3

Compression:

Stored size: 1.77 KB

Contents

module Ecoportal
  module API
    class Logger
      TIMESTAMP_PATTERN  = "%Y-%m-%dT%H:%M:%S"
      STDOUT_FORMAT_PROC = proc do |severity, datetime, progname, msg|
        prefix = "%5s > " % severity
        msg.lines.map.with_index do |line, idx|
          if idx.zero?
            prefix + line.chomp
          else
            " "*prefix.length + line.chomp
          end
        end.join("\n")+"\n"
      end
      FILE_FORMAT_PROC = proc do |severity, datetime, progname, msg|
        prefix = "%5s(%s) > " % [severity, datetime.strftime(TIMESTAMP_PATTERN)]
        msg.lines.map.with_index do |line, idx|
          if idx.zero?
            prefix + line.chomp
          else
            " "*prefix.length + line.chomp
          end
        end.join("\n")+"\n"
      end

      attr_reader :console, :file

      def initialize(
        console_level: ::Logger::INFO,
        file_level:   ::Logger::DEBUG,
        output_file:  File.join(Dir.getwd, "API_Log-#{Time.now.strftime(TIMESTAMP_PATTERN)}.txt")
      )
        @console = make_stdout_logger(console_level)
        @file    = make_file_logger(file_level, output_file)
      end

      %w(unknown fatal error warn info debug).each do |type|
        define_method(type) do |&block|
          @console.send(type, &block)
          @file&.send(type, &block)
        end
      end

      private

      def make_stdout_logger(level)
        ::Logger.new(STDOUT).tap do |logger|
          logger.formatter = STDOUT_FORMAT_PROC
          logger.level     = level
        end
      end

      def make_file_logger(level, output_file)
        return unless output_file
        ::Logger.new(File.open(output_file, "a")).tap do |logger|
          logger.formatter = FILE_FORMAT_PROC
          logger.level     = level
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ecoportal-api-0.3.5 lib/ecoportal/api/logger.rb
ecoportal-api-0.3.4 lib/ecoportal/api/logger.rb
ecoportal-api-0.3.3 lib/ecoportal/api/logger.rb