Log4r

Log4r is an extensive logging library for ruby that's much more flexible and powerful than the standard logger library that is include in ruby.

Simple logging example:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'log4r'
 
include Log4r
 
# create and configure a logger
log = Logger.new("my_log")
log.outputters = FileOutputter.new("f1", :filename => "./my_log.log")
 
# log some messages
log.debug("this is just a debug message")
log.info("this is more important")
log.warn("somethings wrong")
log.error("you are in trouble")
log.fatal("hasta la vista, baby")

Using custom formats:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'log4r'
#require 'log4r/configurator'
 
include Log4r
 
log = Logger.new("my_formatlog")
pf = PatternFormatter.new(:pattern => "%d %l %m")
fo = FileOutputter.new("f2", :filename => "./my_formatlog.log", :formatter => pf)
 
log.outputters = fo
log.level = WARN
log.info("info message")
log.warn("warning message")

Using a config file:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'log4r'
require 'log4r/configurator'
 
include Log4r
 
# configure logging
Configurator['logpath'] = './logs'
#Configurator.load_xml_file('log4r_config.xml')
Configurator.load_xml_file('log4r_config2.xml')
 
log = Logger["MainLogger"]
log.warn("warning")
log.debug("debug")

using the following config file

<!--
Log Configuration
-->
 
<log4r_config>
 
  <pre_config>
    <custom_levels>DEBUG, INFO, WARN, ERROR, FATAL</custom_levels>
    <global level="ALL"/>
  </pre_config>
 
    <!-- Outputters -->
    <outputter name="console" type="StdoutOutputter" level="DEBUG" >
        <formatter type="Log4r::PatternFormatter">
            <pattern>=>[%5l %d] %C: %M [%t]</pattern>
        </formatter>
    </outputter>
 
    <outputter name="file_outputter" type="FileOutputter">
        <filename>log/my_configfile.log</filename>
        <formatter type="Log4r::PatternFormatter">
            <pattern>=>[%5l %d] %C: %M [%t]</pattern>
        </formatter>
    </outputter>
 
    <!-- Loggers -->
    <logger name="MainLogger"
                level="ALL" additive="false" trace="true">
        <outputter>console</outputter>
        <outputter>file_outputter</outputter>
    </logger>
 
    <logger name="AnotherLogger"
                level="ALL" additive="false" trace="true">
        <outputter>console</outputter>
        <outputter>file_outputter</outputter>
    </logger>
 
</log4r_config>
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.