简体   繁体   English

Logstash定制输入插件来调用Java类

[英]Logstash custom input plugin to call java class

I have written a custom filter plugin for logstash to call a java class. 我为logstash编写了一个自定义过滤器插件,以调用java类。

Requirement: 需求:

Input plugin: read from queue 输入插件:从队列中读取

Custom plugin: For each message in queue call the java class 自定义插件:对于队列中的每个消息,请调用java类

**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? 问题:有没有一种方法可以实例化Java类一次? 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. 对于我从队列中读取的每条消息,我都不想创建java类的新实例,而是在logstash启动期间实例化它,并对所有传入消息使用相同的对象。

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. 您可以在ruby类中创建一个实例变量来保存Java对象,并在ruby类的register方法中实例化该实例对象。 In the filter method, use the instance variable to access the java object. 在filter方法中,使用实例变量访问java对象。

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. 请记住,在变量名之前使用@使其成为Ruby中的实例变量。

An alternative would be to use the Ruby Singleton class; 一种替代方法是使用Ruby Singleton类。

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. 您可以在initialize方法中执行所需的操作,然后仅执行类的所有实例即可重复调用它,而无需每次都对其进行初始化。

More available at: 更多可用信息:

1) Singleton Pattern 1) 单例模式

2) Ruby Singleton class documentation 2) Ruby Singleton类文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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