Rails Log level

Rails default log level is debug . This means that all the log messages will be written to the log files including the debugging log messages and the SQL queries used for the web request. However, this should not be the case for production environments. Changing the log level to info in the production environment will help to reduce the amount of generated logs. To activate this, the following line needs to add to the config/environments/production.rb configuration file:

With this change, we can configure the Rails application log level using the environment variable LOG_LEVEL . The default log level is still debug for the production environment, however, it’s not hardcoded anymore.

Integrate Lograge with Rails

Lograge is a Ruby gem that provides an easy and intuitive way for rewriting rails multiline logs info as single log lines.

Integrating Lograge with Rails applications is a straightforward process. There are a number of changes needed to integrate and customize rails log messages with Lograge.

Add Lograge gem to application dependencies: This can be done by adding the following line to the rails application Gemfile then executing bundle install :

Enable configuring Lograge support: Instead of hardcoded the switch to Lograge, we are going to make Lograge support configurable. To do this, add the following lines to the application configuration file, under the path config/applicaion.rb :

LOGRAGE : This environment variable will be used to switch on and off the Lograge support.

: This environment variable will be used to switch on and off the Lograge support. Add custom variables: By default Lograge messages do not include the host and the IP of the request. However, it’s possible to integrate these variables and other variables in the log messages produced by the Lograge gem. Adding the function below to the Rails ApplicationController in app/controllers/application_aontroller.rb will add four variables ( host , remote_ip , IP , and x_forwarded_for ) to the Lograge log event:

Create Lograge initializers: To finalize Lograge integration we need to create an initializer for Lograge and configure it with the needed configuration item. The initializer should be created under the path config/initializers in the root directory of the Rails application. The following snippet can be used as the default configurations for Lograge:

The initializer file starts by enabling the Lograge library (this depends on the environment variable we introduced above). Then it defines the base controllers integrated with Lograge. Finally, it defines the attributes that need to be included in the log messages.

The default Lograge log format is the key-value format, However, Lograge supports other formats such as JSON and Logstash. The complete list of supported log formats can be found on the Lograge repo.

After applying the above configurations and starting the rails application, rails logs will look like this: