1
0
mirror of https://github.com/meineerde/rackstash.git synced 2026-02-01 01:37:12 +00:00

Do not write empty lines to IO and File adapters

If a line is completely empty, it is not useful to log it at all since
it would be invisible on the created logstream anyway. If we get passed
an empty String from the encoder, we can thus silently ignore it.
This commit is contained in:
Holger Just 2017-10-19 23:04:48 +02:00
parent ca685bb13b
commit c1e3c99ab5
5 changed files with 26 additions and 6 deletions

View File

@ -96,16 +96,17 @@ module Rackstash
private private
# Helper method to ensure that a log line passed to {#write} is a string # Helper method to ensure that a log line passed to {#write} is either a
# that ends in a newline character by mutating the object is required. # String that ends in a newline character or is completely empty.
# #
# @param line [#to_s] a log line # @param line [#to_s] a log line
# @return [String] `line` with a trailing newline character (`"\n"`) # @return [String] `line` with a trailing newline character (`"\n"`)
# appended if necessary # appended if necessary
def normalize_line(line) def normalize_line(line)
line = line.to_s line = line.to_s
line = "#{line}\n" unless line.end_with?("\n".freeze) return line if line.empty? || line.end_with?("\n".freeze)
line
"#{line}\n"
end end
end end
end end

View File

@ -104,9 +104,12 @@ module Rackstash
# @param log [#to_s] the encoded log event # @param log [#to_s] the encoded log event
# @return [nil] # @return [nil]
def write_single(log) def write_single(log)
line = normalize_line(log)
return if line.empty?
@mutex.synchronize do @mutex.synchronize do
auto_reopen auto_reopen
@file.write normalize_line(log) @file.write(line)
end end
nil nil
end end

View File

@ -88,8 +88,11 @@ module Rackstash
# @param log [#to_s] the encoded log event # @param log [#to_s] the encoded log event
# @return [nil] # @return [nil]
def write_single(log) def write_single(log)
line = normalize_line(log)
return if line.empty?
@io.synchronize_for_rackstash do @io.synchronize_for_rackstash do
@io.write normalize_line(log) @io.write line
@io.flush if @flush_immediately @io.flush if @flush_immediately
end end
nil nil

View File

@ -92,6 +92,13 @@ describe Rackstash::Adapters::File do
expect(logfile.tap(&:rewind).read).to eql "a full line.\n" expect(logfile.tap(&:rewind).read).to eql "a full line.\n"
end end
it 'ignores empty log lines' do
adapter.write('')
adapter.write(nil)
expect(logfile.tap(&:rewind).read).to eql ''
end
context 'with auto_reopen: true' do context 'with auto_reopen: true' do
let(:adapter_args) { { auto_reopen: true } } let(:adapter_args) { { auto_reopen: true } }

View File

@ -77,5 +77,11 @@ describe Rackstash::Adapters::IO do
adapter.write('bar') adapter.write('bar')
end end
end end
it 'ignores empty log lines' do
expect(io).to_not receive(:write)
adapter.write('')
adapter.write(nil)
end
end end
end end