# typed: true # Copyright (c) 2015 Sqreen. All Rights Reserved. # Please refer to our terms for more information: https://www.sqreen.com/terms.html require 'logger' require 'sqreen/log' require 'sqreen/formatter_with_tid' require 'sqreen/null_logger' # TODO: inherit from ::Logger module Sqreen # Wrapper class for sqreen logging class Logger SEVERITY_TO_METHOD = ::Logger::Severity.constants.each_with_object({}) do |s, h| h[::Logger::Severity.const_get(s)] = s.downcase end def initialize(desired_level, log_location, force_logger = nil) if force_logger @logger = force_logger else init_logger_output(log_location) end init_log_level(desired_level) enforce_log_format(@logger) create_error_logger end def debug? @logger.debug? end def info? @logger.info? end def warn? @logger.warn? end def error? @logger.error? end def fatal? @logger.fatal? end def debug(msg = nil, &block) @logger.debug(msg, &block) end def info(msg = nil, &block) @logger.info(msg, &block) end def warn(msg = nil, &block) @logger.warn(msg, &block) end def error(msg = nil, &block) @error_logger.error(msg, &block) @logger.error(msg, &block) end def unknown(msg = nil, &block) @logger.unknown(msg, &block) end def add(severity, msg = nil, &block) send(SEVERITY_TO_METHOD[severity], msg, &block) end protected def init_logger_output(path) path = File.expand_path(path) if File.writable?(path) || File.writable?(File.dirname(path)) @logger = ::Logger.new(path) else @logger = ::Logger.new(STDOUT) @logger.info("Cannot access #{path} for writing. Defaulting to stdout") end rescue StandardError => e @logger = ::Logger.new(STDOUT) @logger.error('Got error while trying to setting logger up, '\ "falling back to stdout #{e.inspect}") end def init_log_level(level) log_level = ::Logger.const_get(level) @logger.level = log_level Sqreen::PerformanceNotifications::Log.enable if level == 'DEBUG' return if level != 'DEBUG' && !Sqreen.config_get(:report_perf) Sqreen::PerformanceNotifications::LogPerformance.enable end def create_error_logger @error_logger = Kernel.const_defined?('MiniTest') ? NullLogger.instance : ::Logger.new(STDERR) enforce_log_format(@error_logger) end def enforce_log_format(logger) logger.formatter = Sqreen::FormatterWithTid.new end end end