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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With