Logging

In the request scope, the logger helper exposes a Logger instance:

get '/' do
  logger.info "loading data"
  # ...
end
  1. This logger will automatically take your Rack handler’s logging settings into account
  2. If logging is disabled, this method will return a dummy object, so you do not have to worry in your routes and filters about it

Note that logging is only enabled for Sinatra::Application by default, so if you inherit from , you probably want to enable it yourself:

class MyApp < Sinatra::Base
  configure :production, :development do
    enable :logging
  end
end
  1. To avoid any logging middleware to be set up, set the logging setting to nil
  2. However, keep in mind that logger will in that case return nil
  3. A common use case is when you want to set your own logger. Sinatra will use whatever it will find in env['rack.logger']

Logging a stdout y a un fichero

Véase Rack::CommonLogger en Sinatra Recipes.

Sinatra has logging support, but it's nearly impossible to log to a file and to the stdout (like Rails does).

However, there is a little trick you can use to log to stdout and to a file:

require 'sinatra'

configure do
  # logging is enabled by default in classic style applications,
  # so `enable :logging` is not needed
  file = File.new("#{settings.root}/log/#{settings.environment}.log", 'a+')
  file.sync = true
  use Rack::CommonLogger, file
end

get '/' do
  'Hello World'
end
You can use the same configuration for modular style applications, but you have to enable :logging first:

require 'sinatra/base'

class SomeApp < Sinatra::Base
  configure do
    enable :logging
    file = File.new("#{settings.root}/log/#{settings.environment}.log", 'a+')
    file.sync = true
    use Rack::CommonLogger, file
  end

  get '/' do
    'Hello World'
  end

  run!
end

Ejecución

~/sinatra/sinatra-logging]$ tree
.
|-- app.rb
`-- log

1 directory, 1 file
[~/sinatra/sinatra-logging]$ ruby app.rb 
== Sinatra/1.4.4 has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.6.1 codename Death Proof)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop
Consola después de visitar la página:
127.0.0.1 - - [19/Nov/2013 14:53:06] "GET / HTTP/1.1" 200 11 0.0041

Fichero después de visitar la página:

[~/sinatra/sinatra-logging]$ cat log/development.log 
127.0.0.1 - - [19/Nov/2013 14:53:06] "GET / HTTP/1.1" 200 11 0.0038

Véase

  1. el código en GitHub de Rack::CommonLogger
  2. Logging in Sinatra. StackOverflow. Destination is set by changing env['rack.errors']. Konstantin Haase May 13 '11 at 21:18'



Subsecciones
Casiano Rodriguez León 2015-06-18