Sha256: 08df3efa7232b846e6dabefbf622c4e81efca7333b62657bba87a1bd3907762e

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module RubyForGrafanaLoki
  LOGS_TYPE = %w(ERROR WARN FATAL INFO DEBUG).freeze

  class Client
    include RubyForGrafanaLoki::Request

    attr_accessor :job_name
    attr_accessor :host_name
    attr_accessor :source_name

    def initialize(log_file_path, allowed_logs_type = LOGS_TYPE)
      @log_file_path = log_file_path
      @allowed_logs_type = allowed_logs_type
      @job_name = "job name"
      @host_name = "host name"
      @source_name = "source name"
    end

    def send_all_logs
      File.open(@log_file_path, 'r') do |file|
        file.each_line do |line|
          send_log(line) if match_logs_type?(line)
        end
      end
    end

    def send_log(log_message)
      curr_datetime = Time.now.to_i * 1_000_000_000

      msg = "On server #{@host_name} detected error"

      payload = {
        'streams' => [
          {
            'stream' => {
              'source' => @source_name,
              'job' => @job_name,
              'host' => @host_name
            },
            'values' => [[curr_datetime.to_s, log_message]],
            'entries' => [
              {
                'ts' => curr_datetime,
                'line' => "[WARN] " + msg
              }
            ]
          }
        ]
      }

      json_payload = JSON.generate(payload)
      uri = '/loki/api/v1/push'

      post(uri, json_payload)
    end

    def match_logs_type?(log_line)
      type = log_line.match(/(ERROR|WARN|FATAL|INFO|DEBUG)/)&.to_s

      @allowed_logs_type.include?(type)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruby_for_grafana_loki-0.0.6 lib/ruby_for_grafana_loki/client.rb