Florent2
Florent2

Reputation: 3513

Error "undefined local variable or method `logger'" when using `logger.info` in a Sinatra application

I have the following Sinatra 1.2.1 application code:

# app.rb
require 'sinatra'

get '/' do
  logger.info "COUCOU"
  'Hello world!'
end

and start the server with ruby -rubygems app.rb. When I go to http://localhost:4567 I get the error:

NameError at /
undefined local variable or method `logger' for #<Sinatra::Application:0x00000100d91f88>
file: app.rb location: block in <main> line: 4

Do I need to add or configure something to enable logging in Sinatra? Reading the Sinatra README and documentation, it looks like logging is enabled by default for Sinatra::Application.

Upvotes: 7

Views: 7990

Answers (3)

Aleksandar Pavić
Aleksandar Pavić

Reputation: 3420

Logger is not defined, to overcome it you can just use

Rails.logger.info "COUCOU" 

or define it like this:

logger = Rails.logger.new
logger.info "COUCOU"

Upvotes: 2

Jo&#227;o Pereira
Jo&#227;o Pereira

Reputation: 571

The problem is in the not found write method, just extend the Logger class this way and everything should be ok:

class Logger
  # Make Rack::CommonLogger accept a Logger instance
  # without raising undefined method `write' for #<Logger:0x007fc12db61778>
  # makes a method alias using symbols

  alias :write :<<
end

Upvotes: 5

Michael Kohl
Michael Kohl

Reputation: 66837

You are probably missing a logger = Logger.new.

http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/

Upvotes: 3

Related Questions