Custom Loggers

Enable log rotation within the rails application. Rails make use of ActiveSupport::Logger class to write log information. It is used to output message and has associated levels. You can then give the Logger a level, and only messages at that level or higher will be printed. They are:

UNKNOWN An unknown message that should always be logged.
FATAL An un-handleable error that results in a program crash.
ERROR A handleable error condition.
WARN A warning.
INFO Generic (useful) information about system operation.
DEBUG Low-level information for developers.

CREATE YOUR CUSTOM LOGGER

# lib/custom_logger.rb
class CustomLogger < Logger
  def format_message(severity, timestamp, progname, msg)
    "#{msg}\n"
  end
end
logfile = File.open(RAILS_ROOT + '/log/custom.log', 'a') #create log file
logfile.sync = true #automatically flushes data to file
CUSTOM_LOGGER = CustomLogger.new(logfile) #constant accessible anywhere
It creates a custom_logger.rb file. Here defines the format for log messages. The arguments are:
  • Severity of the log message
  • Time instance representing when the message was logged
  • progname configured or passed to the logger method
  • Object the user passed to the log message.

LOAD CUSTOMLOGGER FROM ENVIRONMENT

Then load that custom logger in development as:
#in any controller, view or model like,
CUSTOM_LOGGER.info("info from custom logger")
CUSTOM_LOGGER.add(Logger::FATAL) { 'Fatal error!' }
CUSTOM_LOGGER.fatal("Some arguments are not given.")
CUSTOM_LOGGER.error ("Argument #{@name} mismatch." )
CUSTOM_LOGGER.debug("This is a " + potentially + " expensive operation")
I hope this will help you to know about Custom Loggers.

References

]]>