2017-02-17 3 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) 

설명이 조각을 추가 할 수 있습니다 필요 : 파일을 만들려면 로깅 모듈에서 함수를 호출, 로깅 수준은 디버그입니다. 다음은

Logging.log("Message",:FATAL) 
을 다음과 같이 모든 루비 파일, 우리는이 기록을 사용할 수있는 모든 방법으로 다음
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 

모듈

에 대한 코드의 조각
관련 문제