public
Last active

Custom logger file in Rails

  • Download Gist
custom_logger.rb
Ruby
1 2 3 4 5 6 7 8 9 10
# lib/custom_logger.rb
class CustomLogger < Logger
def format_message(severity, timestamp, progname, msg)
"#{timestamp.to_formatted_s(:db)} #{severity} #{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
development.rb
Ruby
1 2
# in development.rb
require "custom_logger"
top_controller.rb
Ruby
1 2 3 4
# in controller files
CUSTOM_LOGGER.info("info from custom logger")
CUSTOM_LOGGER.debug("debug from custom logger")
CUSTOM_LOGGER.error("error from custom logger")

thanks helped me a lot.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.