Reputation: 560
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.
Upvotes: 1
Views: 1194
Reputation: 4937
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:
2) Ruby Singleton class documentation
Upvotes: 1
Reputation: 2335
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.
Upvotes: 1