Friday, August 7, 2009

A log4j adapter for Rails

This current client application I'm working on is a mixed bag of Ruby and Java parts. All our existing logging for the older Java parts uses log4j and we wanted to unify our Rails logging with that. I spent a couple of hours putting together this adapter we now use. If you need something similar it should give you a good place to start.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Log4jAdapter
include ActiveSupport::BufferedLogger::Severity
L4JLevel = org.apache.log4j.Level

SEVERETIES = {
DEBUG => L4JLevel::DEBUG,
INFO => L4JLevel::INFO,
WARN => L4JLevel::WARN,
ERROR => L4JLevel::ERROR,
FATAL => L4JLevel::FATAL,
}
INVERSE = SEVERETIES.invert

def initialize
@logger = org.apache.log4j.Logger.getLogger('com.shc.mmh.Rails')
@root = org.apache.log4j.Logger.getRootLogger
end

def add(severity, message = nil, progname = nil, &block)
message = (message || (block && block.call) || progname).to_s
@logger.log(SEVERETIES[severity], message)
end

def level
INVERSE[@logger.getEffectiveLevel]
end

def level=(level)
raise "Invalid log level" unless SEVERETIES[level.to_i]
@root.setLevel(SEVERETIES[level.to_i])
end

def enabled_for?(severity)
@logger.isEnabledFor(SEVERETIES[severity])
end

#Lifted from BufferedLogger
for severity in ActiveSupport::BufferedLogger::Severity.constants
class_eval <<-EOT, __FILE__, __LINE__
def
#{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
add(
#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
end # end
#
def
#{severity.downcase}? # def debug?
enabled_for?(
#{severity}) # DEBUG >= @level
end # end

EOT

end

def method_missing(meth, *args)
puts "UNSUPPORTED METHOD CALLED: #{meth}"
end
end

No comments: