module Eco module API module Common module Session class Logger DEFAULT_TIMESTAMP_PATTERN = '%Y-%m-%dT%H:%M:%S' def initialize(console_level: nil, file_level: ::Logger::DEBUG, log_file: nil, timestamp_console: false, enviro: nil) raise "Required Environment object (enviro:). Given: #{enviro}" if enviro && !enviro.is_a?(Eco::API::Common::Session::Environment) @enviro = enviro timestamp_console = fetch_timestamp_console(timestamp_console) @console_logger = ::Logger.new(STDOUT).tap do |_logger| _logger.formatter = proc do |severity, datetime, progname, msg| str_timestamp = timestamp_console ? "#{datetime.strftime(DEFAULT_TIMESTAMP_PATTERN)} >" : "" "#{severity.to_s[0]}: #{str_timestamp} #{msg}\n" end _logger.level = fetch_console_level(console_level) end if log_file = fetch_log_file(log_file) @file_logger = ::Logger.new(log_file).tap do |_logger| _logger.formatter = proc do |severity, datetime, progname, msg| "#{severity.to_s[0]}: #{datetime.strftime(DEFAULT_TIMESTAMP_PATTERN)} > #{msg}\n" end _logger.level = fetch_file_level(file_level) end end end def debug(*args, &block) log(:debug, *args, &block) end def info(*args, &block) log(:info, *args, &block) end def warn(*args, &block) return log(:warn, *args, &block) end def error(*args, &block) return log(:error, *args, &block) end def fatal(*args, &block) return log(:fatal, *args, &block) end def unkown(msg, &block) return log(:unkown, *args, &block) end def << (msg) @console_logger << msg unless !@console_logger @file_logger << msg unless !@file_logger end def close() @console_logger.close unless !@console_logger @file_logger.close unless !@file_logger end def add(*args) @console_logger.add(*args) unless !@console_logger @file_logger.add(*args) unless !@file_logger end private def log(level, *args, &block) @console_logger.send(level, *args, &block) unless !@console_logger @file_logger.send(level, *args, &block) unless !@file_logger end def config @enviro.config || {} end def fetch_timestamp_console(value) value || config.logger.timestamp_console end def fetch_console_level(value) value || config.logger.console_level || ::Logger::INFO end def fetch_file_level(value) value || config.logger.file_level || ::Logger::DEBUG end def fetch_log_file(log_file) if log_file ||= config.logger.file log_file = @enviro.file_manager.dir.file(log_file) if @enviro FileManager.create_directory(log_file, includes_file: true) end log_file end end end end end end