Parent

RBatch::Log

About RBatch::Log

Use Auto Logging block, RBatch automatically write to logfile.

Log file default location is “../log/YYYYMMDD_HHMMSS_${PROG_NAME}.log” .

If exception occuerd, then RBatch write stack trace to logfile.

Sample

script : ./bin/sample1.rb

 require 'rbatch'
 
 RBatch::Log.new(){ |log|  # Logging block
   log.info "info string"
   log.error "error string"
   raise "exception"
 }

logfile : ./log/20121020_005953_sample1.log

 [2012-10-20 00:59:53 +900] [INFO ] info string
 [2012-10-20 00:59:53 +900] [ERROR] error string
 [2012-10-20 00:59:53 +900] [FATAL] Caught exception; existing 1
 [2012-10-20 00:59:53 +900] [FATAL] exception (RuntimeError)
     [backtrace] test.rb:6:in `block in <main>'
     [backtrace] /usr/local/lib/ruby192/lib/ruby/gems/1.9.1/gems/rbatch-1.0.0/lib/rbatch/auto_logger.rb:37:in `initialize'
     [backtrace] test.rb:3:in `new'
     [backtrace] test.rb:3:in `<main>'

Public Class Methods

new(opt = nil) click to toggle source

Auto Logging Block.

Params

opt = Option hash object. Hash keys is follows.

  • :name (String) = log file name. Default is “_

  • :dir (String) = log direcotry path. Default is “../log“

  • :level (String) = log level. [“debug”|“info”|“warn”|“error”|“fatal”] . Default is “info”.

  • :append (Boolean) = appned to log or not(=overwrite). Default is ture.

  • :stdout (Boolean) = print string both logfile and STDOUT. Default is false.

  • :quiet (Boolean) = run quiet mode. print STDOUT nothing. Default is true.

Block params

log = Instance of Logger

Sample

 RBatch::Log.new({:dir => "/tmp", :level => "info"}){ |log|
   log.info "info string"
 }
     # File lib/rbatch/log.rb, line 96
 96:     def initialize(opt = nil)
 97:       # parse option
 98:       @opt = @@def_opt.clone
 99:       @@def_opt.each_key do |key|
100:         if opt != nil  && opt[key] != nil
101:           # use argument
102:           @opt[key] = opt[key]
103:         elsif RBatch.rbatch_config != nil            && RBatch.rbatch_config["log_" + key.to_s] != nil
104:           # use config
105:           @opt[key] = RBatch.rbatch_config["log_" + key.to_s]
106:         else
107:           # use default
108:         end
109:       end
110:       puts "option = " + @opt.to_s if @@verbose
111:       # determine log file name
112:       @prog_base = Pathname(File.basename(RBatch.program_name)).sub_ext("").to_s
113:       @file_name = @opt[:name].clone
114:       @file_name.gsub!("<date>", Time.now.strftime("%Y%m%d"))
115:       @file_name.gsub!("<time>", Time.now.strftime("%H%M%S"))
116:       @file_name.gsub!("<prog>", @prog_base)
117:       path = File.join(@opt[:dir],@file_name)
118:       # create Logger instance
119:       begin
120:         if @opt[:append] && File.exist?(path)
121:           @log = Logger.new(open(path,"a"))
122:         else
123:           @log = Logger.new(open(path,"w"))
124:         end
125:       rescue Errno::ENOENT => e
126:         STDERR.puts "RBatch ERROR: Can not open log file  - #{path}" if ! @opt[:quiet]
127:         raise e
128:       end
129:       # set logger option
130:       formatter = proc do |severity, datetime, progname, msg|
131:         head = "[#{datetime}] [" + sprintf("%-5s",severity) +"]"
132:         if msg.is_a? Exception
133:           "#{head} #{msg}\n" + msg.backtrace.map{|s| "    [backtrace] #{s}"}.join("\n") + "\n"
134:         else
135:           "#{head} #{msg}\n"
136:         end
137:       end
138:       @log.formatter = @opt[:formatter] if @opt[:formatter]
139:       @log.level = @@log_level_map[@opt[:level]]
140:       @log.formatter = formatter
141:       if @opt[:stdout]
142:         # ccreate Logger instance for STDOUT
143:         @stdout_log = Logger.new(STDOUT)
144:         @stdout_log.formatter = @opt[:formatter] if @opt[:formatter]
145:         @stdout_log.level = @@log_level_map[@opt[:level]]
146:         @stdout_log.formatter = formatter
147:       end
148:       puts "Log file: " + path if ! @opt[:quiet]
149:       # delete old log
150:       self.delete_old_log(@opt[:delete_old_log_date]) if @opt[:delete_old_log]
151:       # Start logging
152:       self.info("Start Logging. (PID=#{$$.to_s})") if ! @opt[:quiet]
153:       if block_given?
154:         begin
155:           yield self
156:         rescue => e
157:           self.fatal(e)
158:           self.fatal("Caught exception. Exit 1")
159:           exit 1
160:         ensure
161:           self.close
162:         end
163:       end
164:     end
verbose() click to toggle source

Get verbose mode flag.

    # File lib/rbatch/log.rb, line 74
74:     def Log.verbose ; @@verbose ; end
verbose=(bol) click to toggle source

Set verbose mode flag.

    # File lib/rbatch/log.rb, line 71
71:     def Log.verbose=(bol); @@verbose = bol ; end

Public Instance Methods

close() click to toggle source
     # File lib/rbatch/log.rb, line 194
194:     def close
195:       @stdout_log.close if @opt[:stdout]
196:       @log.close
197:     end
debug(a) click to toggle source
     # File lib/rbatch/log.rb, line 189
189:     def debug(a)
190:       @stdout_log.debug(a) if @opt[:stdout]
191:       @log.debug(a)
192:     end
delete_old_log(date = 7) click to toggle source

Delete old log files. If @opt[:name] is not include “”, then do nothing.

Params

  • date (Integer): The day of leaving log files

     # File lib/rbatch/log.rb, line 205
205:     def delete_old_log(date = 7)
206:       if Dir.exists?(@opt[:dir]) && @opt[:name].include?("<date>")
207:         Dir::foreach(@opt[:dir]) do |file|
208:           r = Regexp.new("^"                           + @opt[:name].gsub("<prog>",@prog_base)                            .gsub("<time>","[0-2][0-9][0-5][0-9][0-5][0-9]")                            .gsub("<date>","([0-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])")                          + "$")
209:           if r =~ file && Date.strptime($1,"%Y%m%d") <= Date.today - date
210:             puts "Delete old log file: " + File.join(@opt[:dir] , file) if ! @opt[:quiet]
211:             File::delete(File.join(@opt[:dir]  , file))
212:           end
213:         end
214:       end
215:     end
error(a) click to toggle source
     # File lib/rbatch/log.rb, line 173
173:     def error(a)
174:       @stdout_log.error(a) if @opt[:stdout]
175:       @log.error(a)
176:       send_mail(a) if @opt[:send_mail]
177:     end
fatal(a) click to toggle source
     # File lib/rbatch/log.rb, line 167
167:     def fatal(a)
168:       @stdout_log.fatal(a) if @opt[:stdout]
169:       @log.fatal(a)
170:       send_mail(a) if @opt[:send_mail]
171:     end
info(a) click to toggle source
     # File lib/rbatch/log.rb, line 184
184:     def info(a)
185:       @stdout_log.info(a) if @opt[:stdout]
186:       @log.info(a)
187:     end
opt() click to toggle source

Get Option

    # File lib/rbatch/log.rb, line 77
77:     def opt; @opt ; end
warn(a) click to toggle source
     # File lib/rbatch/log.rb, line 179
179:     def warn(a)
180:       @stdout_log.warn(a) if @opt[:stdout]
181:       @log.warn(a)
182:     end

Private Instance Methods

send_mail(msg) click to toggle source

send mail

     # File lib/rbatch/log.rb, line 224
224:     def send_mail(msg)
225:       body = From: <#{@opt[:mail_from]}>To: <#{@opt[:mail_to]}>Subject: [RBatch] #{RBatch.program_name} has errorDate: #{Time::now.strftime("%a, %d %b %Y %X %z")}Mime-Version: 1.0Content-Type: text/plain; charset=ISO-2022-JPContent-Transfer-Encoding: 7bit#{msg}
226:       Net::SMTP.start(@opt[:mail_server_host],@opt[:mail_server_port] ) {|smtp|
227:         smtp.send_mail(body,@opt[:mail_from],@opt[:mail_to])
228:       }
229:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.