#csv #go #export-to-csv #fluentd
#csv #Вперед #экспорт в csv #fluentd
Вопрос:
Я использую fluentd для сбора журналов в формате CSV из приложения golang.
Это файл fluentd conf
<source>
@type forward
@id app_logs
@label @mainstream
port 24224
</source>
<label @mainstream>
<match **>
@type file
@id v6_logs
<format>
@type csv
fields log_version,day_time,event_id,request_id,app_id,app_version,account_id,country_id,server_name,remote_ip,process_id,thread_id,item_id,message,parameters
force_quotes false
</format>
path /fluentd/log/app.log
append true
</match>
</label>
Я использую клиент Fluent golang для записи журналов из приложения https://github.com/fluent/fluent-logger-golang
logger, _ := fluent.New(fluent.Config{FluentPort: 24224, FluentHost: "fluentd"})
defer logger.Close()
tag := "web"
var data = map[string]interface{}{
"log_version": 6,
"day_time": time.Now().UTC().String(),
"event_id": 1700,
"request_id": "54321",
"account_id": 12345,
"server_name": hostname,
"process_id": os.Getpid(),
"message": "Test Message(param1; param2)",
"parameters": "value1, value2",
}
error := logger.Post(tag, data)
Вывод получается следующим образом.
6,2020-09-23 23:48:44.5731073 0000 UTC,1700,54321,,,123467,,cabf36399a5c,,1,,,Test Message(param1; param2),"value1,value2"
Как я могу удалить кавычки вокруг «value1, value2» (чтобы они отображались как отдельные поля).
Комментарии:
1.
"parameters": []string{"value1", "value2"},
Достигается ли ваш результат?2. @Crowman Я попробовал, и он печатает так 6,2020-09-24 00:37:11.9161664 0000 UTC,1700,54321,,,123467,, 23741f966459,,1,,,Тестовое сообщение(param1; param2),»[«»значение1″», «»значение2″»]»
3. Тогда лучшим вариантом может быть перечисление двух ваших параметров по отдельности.
4. Идея здесь в том, что параметры имеют переменное количество значений, разделенных запятой в одной строке. Есть ли какой-либо другой способ добиться этого во fluentd?
Ответ №1:
Я добился этого, написав пользовательский плагин форматирования CSV на ruby, следуя инструкциям здесь https://docs .fluentd.org/v/0.12/developer/plugin-development и поместите файл в путь /etc/fluent/plugin/
require 'fluent/plugin/formatter'
module Fluent::Plugin
class MyCSVFormatter < Formatter
# Register MyCSVFormatter as 'my_csv'.
Fluent::Plugin.register_formatter('my_csv', self)
config_param :csv_fields, :array, value_type: :string
# This method does further processing. Configuration parameters can be
# accessed either via `conf` hash or member variables.
def configure(conf)
super
end
# This is the method that formats the data output.
def format(tag, time, record)
values = []
# Look up each required field and collect them from the record
@csv_fields.each do |field|
if field == "parameters"
parametervalues = []
parametervalues = record[field].split(",").map(amp;:strip)
values.push(*parametervalues)
next
end
v = record[field]
values << v.to_s
end
# Output by joining the fields with a comma
values.join(',') "n"
end
end
end
Обновлен файл fluentd conf для использования пользовательского формата, подобного этому
<label @mainstream>
<match **>
@type file
@id v6_logs
<format>
@type my_csv
csv_fields log_version,day_time,event_id,request_id,app_id,app_version,account_id,country_id,server_name,remote_ip,process_id,thread_id,item_id,message,parameters
</format>
path /fluentd/log/app.log
append true
</match>
</label>
Это дает желаемый результат
6,2020-09-24 06:27:52.1826684 0000 UTC,1700,54321,,,123467,,hostname,,1,,,Test Message(param1; param2),value1,value2