Sha256: d56805581eba9e71db03fb870cd3ba5550fd1b99df9fccd35319fe573bbc4ffa

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

module RubyForGrafanaLoki
  LOGS_TYPE = %w(ERROR WARN FATAL INFO DEBUG).freeze
  class Client
    include RubyForGrafanaLoki::Request

    def initialize(log_file_path, allowed_logs_type = LOGS_TYPE)
      @log_file_path = log_file_path
      @allowed_logs_type = allowed_logs_type
    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

      host = "somehost"
      msg = "On server #{host} detected error"

      payload = {
        "streams" => [
          {
            "stream" => {
              "source" => "Name-of-your-source",
              "job" => "name-of-your-job",
              "host" => host
            },
            "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

    private

    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.4 lib/ruby_for_grafana_loki/client.rb