Possible Duplicate:
Get client’s IP address in Sinatra?
I'm using Sinatra with Apache and Passenger.
I'm currently using the following logger in my config.ru
:
LOGGER = Logger.new("logs/sinatra.log")
I can log things in my app using:
LOGGER.error "Log msg"
An example log entry looks like this:
E, [2013-01-18T19:43:41.857146 #19412] ERROR -- : Log msg
How can I put the IP of the current user into the log, so it might look like this:
E, [2013-01-18T19:43:41.857146 #19412] ERROR -- : <127.0.0.1> Log msg
I could write:
LOGGER.error "<#{request.ip}> Log msg"
But, I want to have it on every log message, so always prepending the IP manually seems to be the wrong way. How can the LOGGER
be configured to parse the request.ip
automatically and to put it into the log?
I tried it the following way as suggested in some answers:
configure.ru:
configure do
LOGGER = Logger.new("logs/sinatra.log")
original_formatter = Logger::Formatter.new
LOGGER.formatter = proc { |severity, datetime, progname, msg|
original_formatter.call(severity, datetime, progname, "#{ip} #{msg.dump}")
}
end
app.rb:
helpers do
def ip
request.ip
end
end
get '/' do
LOGGER.info 'test'
end
This is the result:
NameError: undefined local variable or method `ip' for #<Rack::Builder:0x00000001821c60>
Update Based on theTinMan's answer I came up with the following helper:
helpers do
def log(call,msg = '')
severity = Logger.const_get(call.upcase)
return if LOGGER.level > severity
msg = yield if block_given?
LOGGER.send(call, "<#{request.ip}> #{msg}")
end
end
So I can do this:
log :info, 'msg'
log(:debug) { very.expensive.operation }
This looks like the solution I wanted. Is there room for improvement?