简体   繁体   中英

Logstash custom input plugin to call java class

I have written a custom filter plugin for logstash to call a java class.

Requirement:

Input plugin: read from queue

Custom plugin: For each message in queue call the java class

**Code:**

# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "java"
require "test.jar"

class LogStash::Filters::Example < LogStash::Filters::Base

  config_name "example"

  public
  def register
  end # def register

  public
  def filter(event)
      object = Java::Com.test.Test.new
      a = object.readMessage(event.get("message"))
      event.set("message",a)

    filter_matched(event)
  end # def filter

end # class LogStash::Filters::Example

Problem: Is there a way that I can instantiate the java class just once? For every message that i read from the queue i do not want to create a new instance of the java class, but rather instantiate it during logstash startup and use the same object for all incoming messages.

Yes. It is pretty easy to do that. You can create an instance variable in your ruby class to hold the Java object and instantiate that in the register method of your ruby class. In the filter method, use the instance variable to access the java object.

Below code should work for you.

# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "java"
require "test.jar"

class LogStash::Filters::Example < LogStash::Filters::Base

  config_name "example"

  public
  def register
    @object = Java::Com.test.Test.new
  end # def register

  public
  def filter(event)
      a = @object.readMessage(event.get("message"))
      event.set("message",a)
    filter_matched(event)
  end # def filter
end # class LogStash::Filters::Example

Remember to use @ before the variable name to make it an instance variable in Ruby.

An alternative would be to use the Ruby Singleton class;

require 'singleton'

class Logger
  include Singleton

  def initialize
    @log = File.open("log.txt", "a")
  end

  def log(msg)
    @log.puts(msg)
  end
end

Logger.instance.log('message 2')

You can do what you need in the initialize method, and then just all the instance of your class to call it repeatedly without initializing it every time.

More available at:

1) Singleton Pattern

2) Ruby Singleton class documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM