Rails logging is pretty good but sometimes you need to tweak it a bit. In the app I’m currently working on, clients frequently send JSON payloads of up to 100 kilobytes to a Rails app. Since Rails logs the request body, the log file was cluttered and quickly growing beyond what the operations people would be comfortable with. I also couldn’t filter it out with the
filter_parameters configuration, as it wasn’t a parameter but the body of the request.
I found out that it’s not easy to silence parameters logging specifically, as that occurs outside of the controller.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This will silence any logs produced by the
process_payload action, such as active record query logs. But I was still getting those request logs:
1 2 3
These logs are produced by a LogSubscriber which attaches itself to action controller. I haven’t found a way to unsubscribe or replace it for a specific controller action, so I had to find another way.
Then I found the silencer gem which allows you to completely silence logs for given URL patterns. That’s pretty nifty, but I didn’t want to disable my warning or error logs so I couldn’t use it.
The Final Solution
In the end, I combined a few things to solve my logging problem. This is an adapted version of the logger from the silencer gem (all credit to spagalloco) that will set the log level to
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
The idea is to replace the default Rack logger with this one, and to silence only the URL that will receive the large request body.
1 2 3 4 5 6 7 8 9 10 11
This solved the immediate problem of the main log file growing, and without suppressing warning and error logs. However, I had lost the ability to debug errors in the JSON payloads, so I decided to still log them but in a separate log file which I would rotate to avoid size issues.
As shown above, the basic Ruby logger will handle rotation quite nicely. Then all I had to do was to use that logger in my processing action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
The JSON payload is now confined to the separate log file, leaving the main log file uncluttered at the
INFO log level.