如何定义在其他模块之间共享的公共模块日志

时间:2017-02-17 08:18:29

标签: ruby logging module

我正在开发一个具有大型主要功能的脚本,我将其分成几个模块。 我需要的是从所有这些文件中访问日志功能,这意味着日志文件只需打开一次,并且共享访问权限。

这就是我所拥有的:

require 'module_1'
require 'module_2'
require 'module_3'

module Main
 Module_1.Function_startup()
 Module_2.Function_configuration()
 Module_3.Function_self_test()
end

这是我需要在所有其他模块中使用的记录器的脏模块。 理想情况下,我想将其称为“logger.error”,其中“logger”返回记录器的实例,“error”是rlogger上的函数调用rlogger.error。

require 'logger'

module Logging
  @rlogger = nil

    def init_logger
      if @rlogger.nil?
        puts "initializing logger"
        file_path = File.join(File.dirname(__FILE__), 'checker.log')
        open_mode = File::TRUNC # or File::APPEND
        file = File.open(file_path, File::WRONLY | open_mode)

        @rlogger = Logger.new(file)
        @rlogger.datetime_format = "%Y-%m-%d %H:%M:%S"

        @rlogger.formatter = proc do |severity, datetime, progname, msg|
          con_msg = ""
          if msg.match("ERROR:")
            con_msg = msg.color(:red)
          elsif msg.match("OK!")
            con_msg = msg.color(:green)
          else
            con_msg = msg
          end
          puts ">>>#{con_msg}"
          # notice that the colors introduce extra non-printable characters
          # which are not nice in the log file.
          "#{datetime}: #{msg}\n"
        end

        # Here is the first log entry
        @rlogger.info('Initialize') {"#{Time.new.strftime("%H-%M-%S")}: Checker v#{@version}"}
      end
    end

    # returns the logger
    def logger
      if @rlogger.nil?
        puts "requesting nil rlogger"
      end
      @rlogger
    end
  end
end

1 个答案:

答案 0 :(得分:0)

在要求之后,你可以添加这段代码

$FILE_LOG = Logging.create_log(File.expand_path('LoggingFile.log'), Logger::DEBUG)

以上行的说明:它在Logging Module中调用一个函数,创建File,Logging Level of debug。

以下是Module

的代码段
module Logging
  def self.create_log(output_location level)
    log = Logger.new(output_location, 'weekly').tap do |l|
      next unless l

      l.level = level

      l.progname = File.basename($0)

      l.datetime_format = DateTime.iso8601

      l.formatter = proc { |severity, datetime, progname, msg| "#{severity}: #{datetime} - (#{progname}) : #{msg}\n" }
    end

    log.level = level if level < log.level
    log
  end


  def self.log(msg, level)
    # Here I am just logging only FATAL and DEBUG, similarly you can add in different level of logs
    if level == :FATAL
      $FILE_LOG.fatal(msg)
    elsif level == :DEBUG
      $FILE_LOG.debug(msg)
    end
  end
end

然后在每个方法的每个Ruby文件中,我们都可以使用此日志记录,如下所示

Logging.log("Message",:FATAL)
相关问题