Sha256: a32817950469d87ce2702af03fc469aa709aec6fa80485ccf5cbf3c363fd43dc

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

module Fluent
  module TextFormatter
    class SprintfFormatter < Formatter
      Plugin.register_formatter('sprintf', self)

      include Configurable
      include HandleTagAndTimeMixin

      config_param :sprintf_format, :string
      config_param :sprintf_blank_string, :string, :default => nil
      config_param :sprintf_blank_record_format, :string, :default => nil

      def initialize
        super
      end

      def configure(conf)
        super
        @time_format = @time_format || '%Y-%m-%d %H:%M:%S'
        r = /\$\{([^}]+)\}/
        @keys = @sprintf_format.scan(r).map{ |key| key.first }
        @sprintf_format = @sprintf_format.gsub(/\$\{([^}]+)\}/, '%s')
        if @sprintf_blank_record_format
          @sprintf_blank_record_keys = @sprintf_blank_record_format.scan(r).map{ |key| key.first }
          @sprintf_blank_record_format = @sprintf_blank_record_format.gsub(/\$\{([^}]+)\}/, '%s')
        end

        begin
          @sprintf_format % @keys
        rescue ArgumentError => e
          raise Fluent::ConfigError, "formatter_sprintf: @sprintf_format is can't include '%'"
        end
      end

      def format(tag, time, record)
        if record.empty? && @sprintf_blank_record_format
          return @sprintf_blank_record_format % get_values(@sprintf_blank_record_keys, tag, time, record)
        end
        @sprintf_format % get_values(@keys, tag, time, record)
      end

      def get_values(keys, tag, time, record)
        keys.map{ |key|
          if key == 'tag'
            tag
          elsif key == 'time'
            Time.at(time).strftime(@time_format)
          else
            record[key] || @sprintf_blank_string
          end
        }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fluent-plugin-formatter_sprintf-0.0.2 lib/fluent/plugin/formatter_sprintf.rb