2017-02-17 111 views
0

我正在开发一个大的主要功能,我分成了几个模块的脚本。 我需要的是可以从所有日志访问日志功能,这意味着日志文件只能打开一次,并且共享访问。如何定义一个共享的模块日志共享模块

这是我有:

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 

回答

0

需要的只是以后您可以添加代码这块

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

上面一行的说明:这是调用日志模块的功能,创建文件,日志记录级别为调试。

以下是模块

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) 
使用该记录的代码段