2017-01-04 1 views
0

У меня есть файл, содержащий объекты json, разделенные линией, а также данные не json (stderr stacktraces).отправлять последовательные недопустимые строки json между действительными линиями json в одном сообщении filebeat

{"timestamp": "20170104T17:10:39", "retry": 0, "level": "info", "event": "failed to download"} 
{"timestamp": "20170104T17:10:40", "retry": 1, "level": "info", "event": "failed to download"} 
{"timestamp": "20170104T17:10:41", "retry": 2, "level": "info", "event": "failed to download"} 
Traceback (most recent call last): 
    File "a.py", line 12, in <module> 
    foo() 
    File "a.py", line 10, in foo 
    bar() 
    File "a.py", line 4, in bar 
    raise Exception("This was unexpected") 
Exception: This was unexpected 
{"timestamp": "20170104T17:10:42", "retry": 3, "level": "info", "event": "failed to download"} 
{"timestamp": "20170104T17:10:43", "retry": 4, "level": "info", "event": "failed to download"} 

Используя следующий конфиг, я в состоянии получить действительные линии JSon правильно, но инвалид JSON посылается individualy (построчно).

filebeat.yml

filebeat.prospectors: 
    - input_type: log 
    document_type: mytype 
    json: 
     message_key: event 
     add_error_key: true 
    paths: 
     - /tmp/*.log 

output: 
    console: 
    pretty: true 

    file: 
    path: "/tmp/filebeat" 
    filename: filebeat 

выход:

{ 
    "@timestamp": "2017-01-04T12:03:36.659Z", 
    "beat": { 
    "hostname": "...", "name": "...", "version": "5.1.1" 
    }, 
    "input_type": "log", 
    "json": { 
    "event": "failed to download", 
    "level": "info", 
    "retry": 2, 
    "timestamp": "20170104T17:10:41" 
    }, 
    "offset": 285, 
    "source": "/tmp/test.log", 
    "type": "mytype" 
} 
{ 
    "@timestamp": "2017-01-04T12:03:36.659Z", 
    "beat": { 
    "hostname": "...", "name": "...", "version": "5.1.1" 
    }, 
    "input_type": "log", 
    "json": { 
    "event": "Traceback (most recent call last):", 
    "json_error": "Error decoding JSON: invalid character 'T' looking for beginning of value" 
    }, 
    "offset": 320, 
    "source": "/tmp/test.log", 
    "type": "mytype" 
} 

Я хочу клуб всех не JSon линии, пока новый JSon линии в одно сообщение.

Используя многострочный, я попытался следующий

filebeat.prospectors: 
    - input_type: log 
    document_type: mytype 
    json: 
     message_key: event 
     add_error_key: true 
    paths: 
     - /tmp/*.log 
    multiline: 
     pattern: '^{' 
     negate: true 
     match: after 

output: 
    console: 
    pretty: true 

    file: 
    path: "/tmp/filebeat" 
    filename: filebeat 

Но не кажется, что это будет работать. Выполнение многострочных правил по значениям event ключа, которое было указано в json.message_key.

Из docs here я понимаю, почему это происходит json.message_key -

JSON ключ, на котором, чтобы применить фильтрацию линий и многострочных параметров. Этот ключ должен быть верхнего уровня, и его значение должно быть строковым, в противном случае оно игнорируется. Если текстовый ключ не определен, нельзя использовать фильтрацию линий и многострочных функций.

Есть ли какой-либо другой способ объединения последовательных строк un json в одно сообщение?

Я хочу, чтобы вся трассировка стека была захвачена до того, как она отправит ее в logstash.

ответ

1

Filebeat применяет многострочный группировку после того, как в JSON синтаксического анализа таким образом, многострочный шаблон не может быть основан на символы, которые составляют объект JSON (например, {).

В Filebeat существует другой способ разбора JSON таким образом, что синтаксический анализ JSON происходит после многострочной группировки, поэтому ваш шаблон может включать в себя символы объекта JSON. Вам нужно Filebeat 5.2 (скоро будет выпущено), потому что поле target было добавлено в процессор decode_json_fields, так что вы можете указать, где будут декодированные json-поля в событие.

filebeat.prospectors: 
- paths: [input.txt] 
    multiline: 
    pattern: '^({|Traceback)' 
    negate: true 
    match: after 

processors: 
- decode_json_fields: 
    when.regexp: 
     message: '^{' 
    fields: message 
    target: 
- drop_fields: 
    when.regexp: 
     message: '^{' 
    fields: message 

Я проверил многострочный шаблон here используя площадку Golang.

Filebeat производит следующий вывод (используя строки журнала, которые вы указали выше в качестве ввода). (Я использовал сборку из ведущей ветки.)

{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"event":"failed to download","input_type":"log","level":"info","offset":95,"retry":0,"source":"input.txt","timestamp":"20170104T17:10:39","type":"log"} 
{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"event":"failed to download","input_type":"log","level":"info","offset":190,"retry":1,"source":"input.txt","timestamp":"20170104T17:10:40","type":"log"} 
{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"event":"failed to download","input_type":"log","level":"info","offset":285,"retry":2,"source":"input.txt","timestamp":"20170104T17:10:41","type":"log"} 
{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"input_type":"log","message":"Traceback (most recent call last):\n File \"a.py\", line 12, in \u003cmodule\u003e\n foo()\n File \"a.py\", line 10, in foo\n bar()\n File \"a.py\", line 4, in bar\n raise Exception(\"This was unexpected\")\nException: This was unexpected","offset":511,"source":"input.txt","type":"log"} 
{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"event":"failed to download","input_type":"log","level":"info","offset":606,"retry":3,"source":"input.txt","timestamp":"20170104T17:10:42","type":"log"} 
{"@timestamp":"2017-01-05T20:34:18.862Z","beat":{"hostname":"host.example.com","name":"host.example.com","version":"5.2.0-SNAPSHOT"},"event":"failed to download","input_type":"log","level":"info","offset":702,"retry":4,"source":"input.txt","timestamp":"20170104T17:10:43","type":"log"} 
Смежные вопросы