class Fluent::Mixin::RewriteTagName::PlaceholderExpander

Attributes

Public Class Methods

new() click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 37
def initialize
  @tag = ''
  @placeholders = {}
end

Public Instance Methods

expand(str) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 42
def expand(str)
  str = str.gsub(/(\${(tag|hostname)}|__(TAG|HOSTNAME)__)/) do |name|
    $log.warn "RewriteTagNameMixin: unknown placeholder `#{name}` found" unless @placeholders.include?(name)
    @placeholders[name]
  end
  str = str.gsub(/__TAG_PARTS\[-?[0-9]+(?:\.\.\.?-?[0-9]+)?\]__|\$\{tag_parts\[-?[0-9]+(?:\.\.\.?-?[0-9]+)?\]\}/) do |tag_parts_offset|
    expand_tag_parts(tag_parts_offset)
  end
end
expand_tag_parts(tag_parts_offset) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 52
def expand_tag_parts(tag_parts_offset)
  begin
    position = /\[(?<first>-?[0-9]+)(?<range_part>(?<range_type>\.\.\.?)(?<last>-?[0-9]+))?\]/.match(tag_parts_offset)
    raise "failed to parse offset even though matching tag_parts" unless position
    tag_parts = @tag.split('.')
    if position[:range_part]
      extract_tag_part_range(tag_parts, position)
    else
      extract_tag_part_index(tag_parts, position)
    end
  rescue StandardError => e
    $log.warn "RewriteTagNameMixin: failed to expand tag_parts. :message=>#{e.message} tag:#{@tag} placeholder:#{tag_parts_matched}"
    nil
  end
end
extract_tag_part_index(tag_parts, position) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 68
def extract_tag_part_index(tag_parts, position)
  index = position[:first].to_i
  raise "missing placeholder." unless tag_parts[index]
  tag_parts[index]
end
extract_tag_part_range(tag_parts, position) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 74
def extract_tag_part_range(tag_parts, position)
  exclude_end = (position[:range_type] == '...')
  range = Range.new(position[:first].to_i, position[:last].to_i, exclude_end)
  raise "missing placeholder." unless tag_parts[range]
  tag_parts[range].join('.')
end
set_hostname(value) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 86
def set_hostname(value)
  set_placeholder('hostname', value)
end
set_tag(value) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 81
def set_tag(value)
  @tag = value
  set_placeholder('tag', value)
end

Private Instance Methods

set_placeholder(key, value) click to toggle source
# File lib/fluent/mixin/rewrite_tag_name.rb, line 91
def set_placeholder(key, value)
  @placeholders.store("${#{key.downcase}}", value)
  @placeholders.store("__#{key.upcase}__", value)
end