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