I'm having trouble figuring out how to log messages with Sinatra. I'm not looking to log requests, but rather custom messages at certain points in my app. For example, when fetching a URL I would like to log "Fetching #{url}"
.
Here's what I'd like:
- The ability to specify log levels (ex:
logger.info("Fetching #{url}")
) - In development and testing environments, the messages would be written to the console.
- In production, only write out messages matching the current log level.
I'm guessing this can easily be done in config.ru
, but I'm not 100% sure which setting I want to enable, and if I have to manually create a Logger
object myself (and furthermore, which class of Logger
to use: Logger
, Rack::Logger
, or Rack::CommonLogger
).
(I know there are similar questions on StackOverflow, but none seem to directly answer my question. If you can point me to an existing question, I will mark this one as a duplicate).
Sinatra 1.3 will ship with such a logger object, exactly usable as above. You can use edge Sinatra as described in "The Bleeding Edge". Won't be that long until we'll release 1.3, I guess.
To use it with Sinatra 1.2, do something like this:
If you are using something like unicorn logging or other middleware that tails IO streams, you can easily set up a logger to STDOUT or STDERR
this allows you to intercept messages at application scope, rather than just having access to logger as request helper
I personally log in Sinatra via:
Here's another solution:
Of course, you can do it without ActiveSupport::Concern by putting the
configure
andbefore
blocks straight into MySinatraApp, but what I like about this approach is that it's very clean--all logging configuration is totally abstracted out of the main app class.It's also very easy to spot where you can change it. For instance, the SO asked about making it log to console in development. It's pretty obvious here that all you need to do is a little if-then logic in the
log_file
method.