Reputation:
I'm using Rails 5 and need to create a custom Rails logger.
For instance in some places of the controllers I want to have this logging calls:
Rails.logger.info('Event happened',
{ event_id: '...', email: '...', ...}
)
And latter on in my log file I want to see something like this:
{
"level": "info",
"ts": 1507972311.8043,
"caller": "controller/api/v2/news.rb:101",
"msg": "Event happened",
"app": "My App",
"env": "production",
"context": {
"event_id": "1234567",
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe"
}
}
Is this possible? How to do this for all log levels (info/debug/error) at the same time?
Upvotes: 0
Views: 2008
Reputation: 121010
The best solution would be to declare your own Logger#formatter
:
Rails.logger.
instance_variable_get(:@logger).
instance_variable_get(:@log).
formatter = proc do |severity, datetime, progname, msg|
DO WHATEVER YOU WANT HERE
end
Upvotes: 0
Reputation: 8257
Create you own wrapper:
class LocalLogger
def self.log(*args)
new.log(*args)
end
def logger
Rails.logger
end
delegate :info, :debug, :warn, :error, to: :logger
def log(level: :info, payload)
send(level, payload.inspect)
end
end
LocalLogger.log level: :warn, {foo: bar}
Modify the log
method to behave as you want.
However, avoid the temptation to be too clever with this - the default logger behaviour is pretty good and will behave as most other devs expect it to.
Upvotes: 1