# frozen_string_literal: true require 'lograge' require 'logstash-logger' module LogToolbox class LogrageConfig attr_accessor :config LOGSTASH_URL = ENV['LOGSTASH_URL'] LOGSTASH_PORT = ENV['LOGSTASH_PORT'] LOGSTASH_PROTOCOL = ENV.fetch('LOGSTASH_PROTOCOL', 'udp') LOGSTASH_BUFFER_MAX_ITEMS = ENV.fetch('LOGSTASH_BUFFER_MAX_ITEMS', 50).to_i LOGSTASH_BUFFER_MAX_INTERVAL = ENV.fetch('LOGSTASH_BUFFER_MAX_INTERVAL', 5).to_i def self.configure Rails.application.configure do log_config = LogToolbox::LogrageConfig.new(config) log_config.configure_log_format if %w[development test].include?(ENV['RAILS_ENV']) log_config.configure_log_output_stdout else log_config.configure_log_output_logstash end end end def initialize(config) @config = config end def configure_log_output_logstash config.logstash.type = LOGSTASH_PROTOCOL config.logstash.host = LOGSTASH_URL config.logstash.port = LOGSTASH_PORT config.logstash.buffer_max_items = LOGSTASH_BUFFER_MAX_ITEMS config.logstash.buffer_max_interval = LOGSTASH_BUFFER_MAX_INTERVAL end def configure_log_output_stdout return unless ENV['RAILS_LOG_TO_STDOUT'].present? logger = ActiveSupport::Logger.new($stdout) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # rubocop:disable Metrics/AbcSize,Metrics/MethodLength def configure_log_format config.lograge.enabled = true config.lograge.base_controller_class = 'ActionController::API' config.lograge.formatter = Lograge::Formatters::Json.new config.lograge.custom_options = lambda do |event| { event_at: event.payload[:event_at], parameters: event.payload[:params].to_json, level: 'INFO', service_name: event.payload[:service_name] || LogUtil.system_service_name, version: event.payload[:version], origin_ipv4: event.payload[:origin_ipv4], destination_ipv4: event.payload[:destination_ipv4], username: wso2_user_name(event.payload[:headers][:HTTP_USER_IDENTIFIER]) } end end # rubocop:enable Metrics/AbcSize,Metrics/MethodLength def wso2_user_name(http_user_identifier) return nil unless http_user_identifier.is_a? String http_user_identifier ? JSON.parse(Base64.decode64(http_user_identifier))['user_name'] : nil end end end