Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added header option #9

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/logstash/outputs/csv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,28 @@ class LogStash::Outputs::CSV < LogStash::Outputs::File
# may not make the values safe in your spreadsheet application
config :spreadsheet_safe, :validate => :boolean, :default => true

# Optional headers to add to the CSV file once it's generated.
config :headers, :validate => :string

public
def register
super
@csv_options = Hash[@csv_options.map{|(k, v)|[k.to_sym, v]}]
@csv_options = Hash[@csv_options.map{|(k, v)|[k.to_sym, v]}]

if headers
@csv_options[:headers] = headers
end
end

public
def receive(event)

path = event.sprintf(@path)

@csv_options[:write_headers] = !File.exist?(path) || File.zero?(path)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will add the header before each record in the csv. Example
A,B,C
1,2,3
A,B,C
4,5,6

fd = open(path)

csv_values = @fields.map {|name| get_value(name, event)}
fd.write(csv_values.to_csv(@csv_options))

Expand Down
30 changes: 30 additions & 0 deletions spec/outputs/csv_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -315,4 +315,34 @@
end
end

describe "can turn on headers" do
tmpfile = Tempfile.new('logstash-spec-output-csv')
config <<-CONFIG
input {
generator {
add_field => ["foo","1+1", "baz", "=1+1"]
count => 2
}
}
output {
csv {
path => "#{tmpfile.path}"
spreadsheet_safe => false
fields => ["foo", "baz"]
headers => "header1,header2"
}
}
CONFIG

agent do
lines = CSV.read(tmpfile.path, :headers => true)
print lines
insist {lines.headers[0]} == "header1"
insist {lines.headers[1]} == "header2"
insist {lines.count} == 2
insist {lines[0][0]} == "1+1"
insist {lines[0][1]} == "=1+1"
end
end

end