Как добавить поле в кибане через logstash - PullRequest
2 голосов
/ 09 января 2020

Я использую python -logsta sh для записи в logsta sh. Он предлагает возможность добавлять дополнительные поля, но проблема в том, что все поля находятся под полем «сообщение».

Я должен признать, что это решение не работает для меня: Как добавить пользовательский поле для logstash / kibana?

Мой python сценарий выглядит следующим образом:

LOGGER = logging.getLogger('python-logstash-logger')
LOGGER.setLevel(logging.INFO)
#LOGGER.addHandler(logstash.LogstashHandler(127.0.0.1, 5000, version=1))
LOGGER.addHandler(logstash.TCPLogstashHandler('127.0.0.1', 5000, version=1))
LOGGER.error('python-logstash: test logstash error message.')
LOGGER.info('python-logstash: test logstash info message.')
LOGGER.warning('python-logstash: test logstash warning message.')

# add extra field to logstash message
extra = {
    'test_string': 'python version: ' + repr(sys.version_info),
    'test_boolean': True,
    'test_dict': {'a': 1, 'b': 'c'},
    'test_float': 1.23,
    'test_integer': 123,
    'test_list': [1, 2, '3'],
}

LOGGER.info("python-logstash: test extra fields", extra=extra)

И мой файл журнала logstath:

input {
  beats {
    port => 5044
  }
  stdin { codec => plain }
}

output {
  elasticsearch {
    hosts => ["http://localhost:9200"]
    index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
    #user => "elastic"
    #password => "changeme"
  }
}

Все Я хочу, чтобы создать мои пользовательские поля, например, 'test_string' из ключей в дополнительной переменной. Как я уже сказал, все эти дополнительные переменные попадают в поле «сообщение», а я не хочу, чтобы каждый ключ в этом диктофоне становился полем в кибане. Как выполнить sh это?

Плюс, я получаю следующую ошибку из logsta sh (я вижу это в моем PowerShell):

[ERROR][logstash.codecs.json     ][main] JSON parse error, original data now in message field {:error=>#<LogStash::Json::ParserError: Unrecognized token 'mestamp': was expecting ('true', 'false' or 'null')

Это, вероятно, из-за сломанного токена, который выглядит так:

outputFromKibana

Я знаю, что токен @version: 1, вероятно, исходит от моего logstashHandler, но где этот TIMESTAMP исходит и как исправить этот токен?

************************ ////// update //// ////// ******************************

Я думаю, что единственная причина, почему все Поля Land в поле 'message' - это сломанный токен. Как исправить этот токен "mestamp"? И откуда он? Я не установил его в своем коде python или logsta sh.

1 Ответ

0 голосов
/ 09 января 2020

Кажется, работает нормально, когда я использую плагин mutate. Вот мой logstash config file Дайте мне знать, если у вас все еще есть вопросы

 input {

    http {                                                                                                        

    }   

 }

  filter {
     mutate {
        add_field => { "test_string" => "Python version 1" }
     }
   }

output {
    stdout {
  #     codec => {rubydebug}
    }   
    elasticsearch {

      hosts=> ["localhost:9200"]
      index => "so-test1"
    }   
}

и вот что я вижу в моей Кибане

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "so-test1",
        "_type" : "_doc",
        "_id" : "XOUei28B--Dy_XuABlDq",
        "_score" : 1.0,
        "_source" : {
          "@version" : "1",
          "test_string" : "Python version 1",  **<== test string that I appended**
          "@timestamp" : "2020-01-09T16:23:17.734Z",
          "host" : "0:0:0:0:0:0:0:1",
          "message" : "hello",     **<=== message the I sent**
          "headers" : {
            "request_path" : "/",
            "postman_token" : "9e9e45a1-d6d2-445ca-9f8f-5eae9dd15320",
            "http_accept" : "*/*",
            "http_host" : "localhost:8080",
            "request_method" : "POST",
            "cache_control" : "no-cache",
            "content_type" : "text/plain",
            "content_length" : "5",
            "http_version" : "HTTP/1.1",
            "connection" : "keep-alive",
            "accept_encoding" : "gzip, deflate",
            "http_user_agent" : "PostmanRuntime/7.21.0"
          }
        }
      }
    ]
  }
}

и вот что я вижу на Logstash console

{
       "@version" => "1",
    "test_string" => "Python version 1",  **<== test_string that I added in mutate filter**
     "@timestamp" => 2020-01-09T16:23:17.734Z,
           "host" => "0:0:0:0:0:0:0:1",
        "message" => "hello",    **<=== the message that I sent through POSTMAN**
        "headers" => {
           "request_path" => "/",
          "postman_token" => "9e9e45a1-d6d2-445ca-9f8f-5eae9dd15320",
            "http_accept" => "*/*",
              "http_host" => "localhost:8080",
         "request_method" => "POST",
          "cache_control" => "no-cache",
           "content_type" => "text/plain",
         "content_length" => "5",
           "http_version" => "HTTP/1.1",
             "connection" => "keep-alive",
        "accept_encoding" => "gzip, deflate",
        "http_user_agent" => "PostmanRuntime/7.21.0"
    }
}
...