2017-02-17 11 views
0

私はいくつかのモジュールに分割した大きなmain関数を持つスクリプトを開発しています。 私が必要とするのは、すべてのログ機能にアクセスすることです。つまり、ログファイルを1回だけ開く必要があり、アクセスを共有する必要があります。共通モジュールを定義する方法他のモジュールと共有するモジュール

これは私が持っているものである:ここでは

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) 
を次のように、私たちは、このログを使用することができます
関連する問題