class LogStash::Filters::Xml

XML filter. Takes a field that contains XML and expands it into an actual datastructure.

Public Instance Methods

filter(event) click to toggle source
# File lib/logstash/filters/xml.rb, line 73
def filter(event)
  return unless filter?(event)
  matched = false

  @logger.debug("Running xml filter", :event => event)

  return unless event.include?(@source)

  value = event[@source]

  if value.is_a?(Array) && value.length > 1
    @logger.warn("XML filter only works on fields of length 1",
                 :source => @source, :value => value)
    return
  end

  # Do nothing with an empty string.
  return if value.strip.length == 0

  if @xpath
    begin
      doc = Nokogiri::XML(value)
    rescue => e
      event.tag("_xmlparsefailure")
      @logger.warn("Trouble parsing xml", :source => @source, :value => value,
                   :exception => e, :backtrace => e.backtrace)
      return
    end

    @xpath.each do |xpath_src, xpath_dest|
      nodeset = doc.xpath(xpath_src)

      # If asking xpath for a String, like "name(/*)", we get back a
      # String instead of a NodeSet.  We normalize that here.
      normalized_nodeset = nodeset.kind_of?(Nokogiri::XML::NodeSet) ? nodeset : [nodeset]

      normalized_nodeset.each do |value|
        # some XPath functions return empty arrays as string
        if value.is_a?(Array)
          return if value.length == 0
        end

        unless value.nil?
          matched = true
          event[xpath_dest] ||= []
          event[xpath_dest] << value.to_s
        end
      end # XPath.each
    end # @xpath.each
  end # if @xpath

  if @store_xml
    begin
      event[@target] = XmlSimple.xml_in(value)
      matched = true
    rescue => e
      event.tag("_xmlparsefailure")
      @logger.warn("Trouble parsing xml with XmlSimple", :source => @source,
                   :value => value, :exception => e, :backtrace => e.backtrace)
      return
    end
  end # if @store_xml

  filter_matched(event) if matched
  @logger.debug("Event after xml filter", :event => event)
end
register() click to toggle source
# File lib/logstash/filters/xml.rb, line 66
def register
  require "nokogiri"
  require "xmlsimple"

end