Thursday, 12 September 2013

Rails logger formatting - insert method name calling logger method

Rails logger formatting - insert method name calling logger method

I want to insert name of the method calling the logger methods into my log
files. Not the whole stack trace, but the class, method and/or line number
would be great.
In any method, one can use caller to get an array of strings, each of
which contains the file, line number and method name. I've come up with a
pretty awful kludge using regexes and Enumerable#find to try to return the
first non-logger stack frame. I guess it works, but if the locations of
the logging Ruby files change in a different version or Rails, or I name
my files something to do with logs, it will break. Same with if I take a
given index from the top of the stack (I did this at first, then
refactored one thing and naturally it gave me the wrong frame).
Note that I'm not looking to just log the controller or action, as those
can be retrieved easily. Mostly this is for stuff in the lib/ directory.
Isn't there an easy way to do this? I don't want to have to pass in
__method__ every time I make a logging statement.

No comments:

Post a Comment