I'm currently working on the GCP and deployed my rails app on the GCP instance.
I'm currently using https://github.com/brendeschuijmert/google-cloud-ruby/tree/master/google-cloud-logging for the compute engine.
When I use this on the rails application.
Rails.logger.info "Hello World" works well.
But logger.warn "Hola Mundo" is not working.
I want someone shade some light on this problem.
Thanks
If you're trying to call logger from outside of a controller/model or some other file that is a part of Rails' structure - you will have to explicitly create a logger for yourself with:
logger = Logger.new(STDOUT) # Or wherever you want to log to
However if Rails.logger is working, then you likely just need an alias like logger = Rails.logger to allow you to use logger.warn without the Rails namespace prefix. You're probably in a file that doesn't already have a helper that is aliasing that for you.
Some more digging in the API reveals that the logger stems from ActiveSupport::LogSubscriber - several classes like ActionController include child LogSubscribers that inherit from that module and hence have the logger method available to them. You can manually alias it to Rails.logger to have it work for you wherever you are trying to invoke it.
Source: https://api.rubyonrails.org/classes/ActiveSupport/LogSubscriber.html#method-c-logger
Related
I am using the Apartment gem for a multi tenant Rails 5.2 app. I'm not sure that this even matters for my question but just giving some context.
Is there a way to override the Rails logger and redirect every single log entry to a file based on the tenant (database) that is being used?
Thinking... is there a method I can monkeypatch in Logger that will change the file written to dynamically?
Example: I want every error message directed to a file for that day. So at the end of a week there will be 7 dynamically generated files for errors that occurred on each specific day.
Another example: Before you write any server log message check if it is before 1pm. If it is before 1pm write it to /log/before_1.log ... if it is after 1pm write it to /log/after_1.log
Silly examples... but I want that kind of dynamic control before any line of log is written.
Thank you!
Usually the logger is usually configured per server (or per environment really) while apartment sets tenants per request - which means that in practice its not really going to work that well.
You can set the logger at any point by assigning Rails.logger to a logger instance.
Rails.logger = Logger.new(Rails.root.join('log/foo.log'), File::APPEND)
# or for multiple loggers
Rails.logger.extend(Logger.new(Rails.root.join('log/foo.log'), File::APPEND))
However its not that simple - you can't just throw that into ApplicationController and think that everything is hunky-dory - it will be called way to late and most of the entries with important stuff like the request or any errors that pop up before the controller will end up in the default log.
What you could do is write a custom piece of middleware that switches out the log:
# app/middleware/tenant_logger.rb
class TenantLogger
def initialize app
#app = app
end
def call(env)
file_name = "#{Appartment::Tenant.current}.log"
Rails.logger = Logger.new(Rails.root.join('log', file_name), File::APPEND)
#app.call(env)
end
end
And mount it after the "elevator" in the middleware stack:
Rails.application.config.middleware.insert_after Apartment::Elevators::Subdomain, TenantLogger
However as this is pretty far down in the middleware stack you will still miss quite a lot of important info logged by the middleware such as Rails::Rack::Logger.
Using the tagged logger as suggested by the Rails guides with a single file is a much better solution.
I have some helper methods on my ActiveSupport::BufferedLogger such as displaying KeyValue pairs, it all works fine from rails s but fails in rails c
In rails s, I can see that my Logger extends BufferedLogger and that is the class I have chosen to MonkeyPatch, I have also tested this out with ActiveSupport::Logger as well.
I had thought that rails c ran through the same initializers that rails s used, am I wrong in thinking that?
Do I need to run some sort of initializer when starting rails c?
Location of my file is:
config/initializers/active_support_logger.rb
Error is here:
Sample Snippet listed here
class ActiveSupport::BufferedLogger
def kv(key, value)
info('%-50s %s' % ["#{key}: ".brown, value])
end
def line
info(##l.brown)
end
def block(message)
line
info(message)
line
end
end
I recommend subclassing ActiveSupport::Logger (or ActiveSupport::BufferedLogger if you really want though it's deprecated in Rails 4) instead of monkey-patching. Rails provides a configuration option to override the logger instance used by the app. This works in any context that loads the Rails environment, including the server and console.
There are a number of ways you can do this; a quick and dirty way to get you started is to just define the class and set the logger instance in an initializer that will get loaded during the initialization process of the Rails environment:
# config/initializers/my_logger.rb
class MyLogger < ::ActiveSupport::Logger
# additional methods and overrides
end
Rails.logger = MyLogger.new(Rails.root.join("log", "#{Rails.env}.log"))
For more info, check out the Rails guide to debugging applications: http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger
I have some Ruby code that I am testing stand alone before integrating into a Rails app. Because the final app. is in Rails I have numerous calls to Rails.logging.xxx that I want in there, but with these I can't run the stand alone app because it doesn't know about Rails.logging. How can I set it up so I can have these logging calls both in my CLI test app. and work in the final Rails deployment?
TY,
Fred
Why not just create a simple stub logger that is only available in the CLI version? For example:
class Rails
def self.logger
#logger ||= Logger.new('cli_logger.log')
end
end
Rails.logger.info("Spam")
Or perhaps more Rails-like:
class Rails
cattr_accessor :logger
end
Rails.logger = Logger.new('cli_logger.log')
Rails.logger.info("It works")
why you cant use the logger in your app?
just use it like an normal debugger?
see http://ruby.about.com/od/tasks/a/logger.htm
I have a Rails 3 application, call it "MyApp". In my config\environments\production.rb file I see such things as
MyApp::Application.configure do
config.log_level = :info
config.logger = Logger.new(config.paths.log.first, 'daily')
...or...
config.logger = Logger.new(Rails.root.join("log",Rails.env + ".log"),3,20*1024*1024)
So, questions are focusing on terminology and wtf they mean... (or point me to some site ,I have looked but not found, to explain how this works.)
MyApp is a module?
MyApp::Application is a ...? What, a module too?
MyApp::Application.configure is a method?
config is a variable? How do I see it in console?
config.logger is a ???
config.paths.log.first is a ...??
--in console I can see "MyApp::Application.configure.config.paths.log.first" but don't know what that means or how to extract info from it!?!
Is this too much for one question? :)
I have looked at the tutorial http://guides.rubyonrails.org/configuring.html but it jumps right into what things do.
A six sided question! Oh my. Let's ahem roll.1 Here's hoping I receive 6 times the upvotes for it then? :)
1. MyApp is a module?
Yes, it's a module. It acts as a "container" for all things pertaining to your application. For instance you could define a class like this:
module MyApp
class MyFunClass
def my_fun_method
end
end
end
Then if someone else has a MyFunClass, it won't interfere with your MyFunClass. It's just a nice way of separating out the code.
2. MyApp::Application is a ...? What, a module too?
MyApp::Application is actually a class, which inherits from Rails::Application. This does a quite a lot of things, including setting up the Rails.application object which is actually an instance of MyApp::Application that you can do all sorts of fun things on like making requests to your application (in a rails console or rails c session). This code for instance would make a dummy request to the root path of your application, returning a 3-sized Array which is just a plain Rack response:
Rails.application.call(Rack::MockRequest.env_for("/"))
You can also get the routes for your application by calling this:
Rails.application.routes
The main purpose of defining MyApp::Application is not these fun things that you'll probably never use, but rather so that you can define application-specific configuration inside config/application.rb. Things like what parameters are filtered, the time zone of the application or what directories should be autoloaded. These are all covered in the Configuration Guide for Rails.
3. MyApp::Application.configure is a method?
Indeed it is a method, and it allows you to add further configuration options to your application's configuration after config/application.rb has been loaded. You've probably seen this used in config/environments/development.rb or one of the other two files in that directory, but basically they all use the same options as shown in that Configuration Guide linked to earlier.
4. config is a variable? How do I see it in console?
The config "variable" is actually a method defined within the code used for Rails::Application and returns quite simply a configuration object which stores the configuration for the application.
To access it in the console, just use Rails.application.config. This will return quite a large Rails::Application::Configuration object for your viewing pleasure.
5. config.logger is a ???
The method you're referring to, I assume, comes from this line in config/environments/production.rb:
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
The method in this example is not config.logger, but rather config.logger=, which is referred to as a "setter" method in Ruby-land. The one without the equal sign is referred to as a "getter". This method sets up an alternative logger for the production environment in Rails, which then can be accessed by using Rails.logger within the console or the application itself.
This is useful if you want to output something to the logs, as you can simply call this code:
Rails.logger.info("DEBUG INFO GOES HERE")
6. config.paths.log.first is a ...?? --in console I can see "MyApp::Application.configure.config.paths.log.first" but don't know what that means or how to extract info from it!?!
Within a Rails application, you can modify the locations of certain directories. And so, this config.paths method is a way of keeping track of where these directories map to. In my entire Rails life I have never had to use or modify this variable and that can mean either one of two things:
It's not used often by Rails programmers, or;
I don't live a very varied life.
Interpret it as you will. My main point is that you're probably never going to use it either.
I hope these help you understand Rails a little more!
1 Terrible dice joke.
MyApp is a module, it's a namespace including an app you'll launch, see next line
MyApp::Application is a Class and you're running it's instances when running a Rails app
MyApp::Application.configure is a method. It passes all instructions to the class. See Ref.
config is a method or an instance variable (when set) which belongs through inheritance to Rails::Application::Configuration. See Ref.
You can see it in console doing: MyApp::Application.config
config.logger doesn't exist until you define it, so it's a Logger instance. See Ref.
config.paths.log is a Rails::Paths::Path
you can access it in console using: MyApp::Application.config.paths.log
What is the best/easiest way to configure logging for code kept in the lib directory?
There's two ways to go about it:
Assuming your library is self-contained and has a module, you can add a logger attribute to your module and use that everywhere in your library code.
module MyLibrary
mattr_accessor :logger
end
You then either use an initializer in config/initializers/, or an config.after_initialize block in config/environment.rb to initialize your logger, like so:
require 'mylibrary'
MyLibrary.logger = Rails.logger
This would still allow you to use your self-contained library from scripts outside of Rails. Which is nice, on occasion.
If using your library without Rails really doesn't make sense at all, then you can also just use Rails.logger directly.
In either case, you're dealing with a standard Ruby Logger. Also keep in mind that, in theory, the logger may be nil.
We can use Rails logger directly into the lib, see the following snippet.
require 'logger'
Rails.logger.info "Hay..!!! Im in lib"
Rails.logger.debug "Debugging this object from Lib #{object.inspect}"
Rails.logger.error "This is an error..."