-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Logging from Classes and Modules doesn't work as expected. #1246
Comments
Can you show more code that clarifies what's in your modules and how you're including them in the main application? |
Edit: shortcut to the actual Ruby code: Here's the file that runs: https://github.com/Joshfindit/Sinatra-unexpected-logging-example/blob/master/SinatraApp/notesapp_sinatra.rb |
There's a lot of code here, would it be possible for you to distill it into a smaller test case? |
The essence is this:
|
Rack loggers are really only available in the request scope of the application, and Sinatra's Sinatra's DSL and method delegation make it look like magic, but you have to remember that there is always a class (Sinatra::Application, or a subclass of Sinatra::Application or Sinatra::Base) behind the scenes holding the methods and behavior that make up a Sinatra application. Consider this simple example: class Foo
def one; 1 end
end
class Bar
def two
one + one
end
end
Bar.new.two Would you expect this to work? No, I hope not, because we haven't told Bar how to access You have a few options on how to proceed here. Probably the easiest and most common solution would be to create a separate logger to use in your models and wherever else. You can keep a handle to the logging object in a global or a constant, or use some dependency injection scheme. Then you have the option of either using that logger in your Sinatra application for requests and/or other messages or accepting Sinatra's default behavior. |
Thank you for this comprehensive response. Are there any straightforward examples that flesh out the different levels of Sinatra's scopes? Having whipped up a number of simple applications without any show-stoppers, it's just a matter of wrapping my head around this. The documentation looks good, but packed. |
None that I know of. The documentation is the best resource. Yes, it is packed, but your understanding will deepen each time you read through it as you learn Sinatra. |
Starting first with a classic application, and splitting the models/libs in to folders that are included/loaded.
When specifying the logger in the main file:
Calling
logger.debug
from a module or class returnsNameError: undefined local variable or method `logger' for <Object or Module>
The text was updated successfully, but these errors were encountered: