开发者

What's the recommended way to write logs from a ruby script on Windows XP?

Too bad I don't have a serv开发者_如何学JAVAer but a XP to serve some scheduled ruby scripts. So, what's the recommended way (gem/plug-in?) to write logs on Windows XP from ruby scripts?


Use the Logger standard library class:

require 'logger'

logger = Logger.new 'my.log'
logger.info "Started."
foo = 42
logger.debug "foo is now #{foo}"
begin
  foo = 1/0
rescue Exception => ex
  logger.error "Caught exception: #{ex.inspect}"
end
logger.info "Finished."

Output to my.log:

# Logfile created on Tue May 18 14:55:35 +0200 2010 by logger.rb
I, [2010-05-18T14:55:35.021048 #8832]  INFO -- : Started.
D, [2010-05-18T14:55:35.021141 #8832] DEBUG -- : foo is now 42
E, [2010-05-18T14:55:35.021231 #8832] ERROR -- : Caught exception: #<ZeroDivisionError: divided by 0>
I, [2010-05-18T14:55:35.021283 #8832]  INFO -- : Finished.

You can change the formatting any way you like it by subclassing Logger then override the format_message method:

class MyLogger < Logger
  def format_message(severity, timestamp, progname, msg)
    sprintf "%s,%03d %7s: %s\n",
    timestamp.strftime("%Y-%m-%d %H:%M:%S"),
    (timestamp.usec / 1000).to_s,
    severity,
    msg
  end
end

logger = MyLogger.new 'my.log'
...

Output:

# Logfile created on Tue May 18 15:07:42 +0200 2010 by logger.rb
2010-05-18 15:07:42,980    INFO: Started.
2010-05-18 15:07:42,980   DEBUG: foo is now 42
2010-05-18 15:07:42,980   ERROR: Caught exception: #<ZeroDivisionError: divided by 0>
2010-05-18 15:07:42,980    INFO: Finished.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜