Stream_logger is a project mainly written in Ruby, based on the MIT license.
A lightweight library that logs to any stream, like stdout.
StreamLogger is a lightweight library that logs to any stream, like stdout
.
Logging to a stream is much more powerful than logging to a file.
require "stream_logger"
logger = StreamLogger.new(STDOUT)
logger.level = :debug # Default is :info
logger.debug "It works!"
Simple enough! Let's look at a more interesting example.
The logify!
command is great for rake tasks and background daemons.
It lets you access the logger from any class or module
and
it automatically logs statements like puts
and print
.
require "stream_logger"
StreamLogger.logify!
# Note: You do not need to set logger.
logger.warn "This is pretty awesome"
puts "This gets logged, too"
To revert back to normal, use:
StreamLogger.unlogify!
The default format looks like:
2011-09-20T02:43:43-0700 INFO : I'm informative
2011-09-20T02:43:44-0700 WARN : You've been warned
2011-09-20T02:43:44-0700 ERROR : Oh no!
You can change the format with:
logger.format do |level, message|
"%s %s %s %5s : %s" % [$0, Process.pid, Time.now, level, message]
end
For your convenience, StreamLogger comes with the syslog format.
logger.format = StreamLogger::SYSLOG_FORMAT
To turn logging off, use:
logger.level = :off
If you have logging code that takes a while to run, you can defer execution.
The code below won't execute unless logger.level = :debug
.
This can save a lot of time in a production environment when the log level is set lower.
logger.debug { sleep(5); "This code takes a while to run" }
Note: This is only faster for slow log messages. In most cases, use the regular method.
Let's assume your program is executed with the command mydaemon
and logs to stdout
.
mydaemon
mydaemon >> log/mydaemon.log
mydaemon | tee -a log/mydaemon.log
mydaemon | logger
mydaemon > /dev/tcp/127.0.0.1/8000
mydaemon > /dev/udp/127.0.0.1/514