简体   繁体   中英

How do add class name and method to rails logger

I have a rails app I want to add a custom log formatter to. In the logs, I want to dynamically show the class where code was called and the method that called it. I don't see a straightforward way to do this in the Rails Logger docs . Currently, in the initialize method of classes in my app I'm doing @logger = self.progname to get the class and @logger.level("#{__callee__}: some message" to get the method.

I can write a custom logging class and assign it to config.log_formatter in .../config/environments/production.rb which is fine. How can I add a formatter that will dynamically tell me what class and what method I'm in when I log stuff?

I would assume that the class will be reflected by the self object, although this could be tricky. I think typically you want the class of self, for an instance method, but for a singleton (class) method you want that self .

So you might use

self.kind_of?(Class) ? self.name : self.class.name

Looks like you are already using __callee__ to get the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM