TunaSalad TunaSalad - 1 year ago 307
Python Question

How do I add a custom field to logstash/kibana?

I am using python-logstash in order to write to logstash. It offers the option to add extra fields but problem is that all fields are under the

field. What I want to accomplish is adding a new field at the higher level.

I found the option to do that from the
plugins) but this solution is not a scalable one (Would have to configure for every machine instance)

Something like:

logger.info('my message')

And in Kibana I will see:

'@timestamp': ...
'message': 'my message'
'new_field' : 'new_field_value'

How do I do that?


Answer Source

From reading the python-logstash documentation, they refer to "extra" fields and say they "add extra fields to logstash message", which seems like exactly what you want!

# 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'], 
test_logger.info('python-logstash: test extra fields', extra=extra)

And then ensure that you have the "json" codec in the logstash input block like this:

input {
  udp {
    port => 5959
    codec => json

EDIT: I tested this with the sample script and get the following Logstash output:

            "host" => "xxx",
            "path" => "pylog.py",
      "test_float" => 1.23,
            "type" => "logstash",
            "tags" => [],
       "test_list" => [
        [0] 1,
        [1] 2,
        [2] "3"
    "test_boolean" => true,
           "level" => "INFO",
      "stack_info" => nil,
         "message" => "python-logstash: test extra fields",
      "@timestamp" => "2016-09-25T15:23:58.259Z",
       "test_dict" => {
        "a" => 1,
        "b" => "c"
     "test_string" => "python version: sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)",
        "@version" => "1",
    "test_integer" => 123,
     "logger_name" => "python-logstash-logger"

All of the extra fields added show at the same level as the message field. They are not added to the 'message' inner-object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download