2013-07-03

code memo : Ruby Logger

### require libs
require 'logger'
require 'ostruct'

### define Logger
class Logger
  def format_message(level, time, progname, msg)
    #\e[0m = reset color(text) , \e[0;32m = Yellow(text)
    "\e[0;33m#{level} #{time.strftime("%Y-%m-%d %H:%M:%S.%2N")}-- #{msg}\e[0m\n"
  end
end

class MultiLogger
  def initialize(*targets)
    @targets = targets
  end
  def write(*args)
    @targets.each {|t| t.write(*args)}
  end
  def close
    @targets.each(&:close)
  end
end

### make Log var
begin
  show_log = true ##fix it
  Log = OpenStruct.new
  Log.recoder = [:err , :succ] ##fix it
  Log.recoder.each do |name|
    if show_log
      Log.send("#{name}=" , Logger.new(MultiLogger.new(STDOUT,File.open("log/#{name}.log" , 'a'))))
    else
      Log.send("#{name}=" , Logger.new(File.open("log/#{name}.log" , 'a')))
    end
    Log.send(name).datetime_format = '%Y-%m-%d %H:%M:%S'
  end
rescue Exception => e
  puts e.backtrace.unshift(e.message).join("\n  ==> ")
  abort("Can't open logger , maybe Permission denied")
end


### use
begin
  Log.succ.info('!!okay!!')
  something_error
rescue Exception => e
  Log.err.error(e.backtrace.unshift(e.message).join("\n  ==> "))
end


### vv output like vv

INFO 2013-07-03 11:37:28.20-- !!okay!!
ERROR 2013-07-03 11:37:29.96-- no implicit conversion of nil into String
  ==> …trace
  ==> …trace
  ==> …trace

沒有留言:

張貼留言