# frozen_string_literal: true
require "time"
require "logger"
require "json"

module Labkit
  module Logging
    class JsonLogger < ::Logger
      def self.log_level(fallback: ::Logger::DEBUG)
        ENV.fetch("GITLAB_LOG_LEVEL", fallback)
      end

      def initialize(path, level: JsonLogger.log_level)
        super
      end

      def format_message(severity, timestamp, progname, message)
        data = default_attributes
        data[:severity] = severity
        data[:time] = timestamp.utc.iso8601(3)
        data[Labkit::Correlation::CorrelationId::LOG_KEY] = Labkit::Correlation::CorrelationId.current_id

        case message
        when String
          data[:message] = message
        when Hash
          data.merge!(message)
        end

        dump_json(data) << "\n"
      end

      private

      def default_attributes
        {}
      end

      def dump_json(data)
        JSON.generate(data)
      end
    end
  end
end
