Too bad I don't have a server 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?
views:
23answers:
1
+2
A:
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.
Lars Haugseth
2010-05-18 12:52:01