Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the standard Ruby logger be configured to flush after every message?

Tags:

Is it possible for the standard Ruby logger (i.e. ::Logger) to auto-flush after each write?

Update: I am setting a custom log formatter, as per How to get timestamps in your ruby on rails logs:

class Foo
  def initialize(params = {})
    @logger = Logger.new $stdout
    @logger.formatter = LogFormatter.new
    @logger.level = params.include?(:log) ? params[:log] : Logger::INFO
    # ...
  end

  class LogFormatter < Logger::Formatter
    def call(severity, time, progname, message)
      timestamp = time.iso8601
      log_msg = "#{timestamp}#{" [#{severity}]" if %w{ERROR WARN}.include? severity} "
      if message.is_a? Exception
        log_msg += "#{message.message}"
        log_msg += ": #{message.backtrace.join "\n#{timestamp}  "}" unless message.backtrace.blank?
      else
        log_msg += message
      end

      "#{log_msg}\n"
    end
  end
end

I tried to use the suggestion from idlefingers as follows:

  def initialize(params = {})
    Rails.logger.auto_flushing = 1
    @logger = Logger.new $stdout
    @logger.formatter = LogFormatter.new
    @logger.level = params.include?(:log) ? params[:log] : Logger::INFO
  end

But no dice. Neither does @logger.auto_flushing = 1 work for me. What am I doing wrong?

Update: It turns out that ActiveSupport's ::Logger simply wraps the standard Ruby ::Logger. So my question turns out to be about Ruby and not Rails, after all.

like image 383
Josh Glover Avatar asked Mar 21 '11 17:03

Josh Glover


People also ask

Where are Ruby logs stored?

In a Rails app, logs are stored under the /log folder. In development mode, the development. log file is used & you see log output on the terminal you're running rails server on.

What is logger in Ruby?

Logger is a simple but powerful logging utility to output messages in your Ruby program. Logger has the following features: Print messages to different levels such as info and error. Auto-rolling of log files. Setting the format of log messages.

How do I create a log file in Ruby?

Since the logger library comes with Ruby, there's no need to install any gems or other libraries. To begin using the logger library, simply require 'logger' and create a new Logger object. Any messages written to the Logger object will be written to the log file.


1 Answers

Turns out it was just a matter of turning on the sync attribute of the underlying IO object:

  def initialize(params = {})
    $stdout.sync = true unless RAILS_ENV == 'production'
    @logger = Logger.new $stdout
    @logger.formatter = LogFormatter.new
    @logger.level = params.include?(:log) ? params[:log] : Logger::INFO
  end
like image 134
Josh Glover Avatar answered Sep 17 '22 15:09

Josh Glover