异常日志插件

2023-07-16  本文已影响0人  纸短情长4
1.安装gem
# Gemfile文件增加
gem 'exception_notification'

# 安装gem
bundle install
2.生成配置文件
# 此命令生成初始化文件(config/ initializers/exception_notification.rb),您可以在其中自定义配置。
rails g exception_notification:install
3.配置
# config/initializers/exception_notification.rb
require 'exception_notification/rails'
# require 'exception_notification/sidekiq'
require 'exception_notifier/database_notifier'

ExceptionNotification.configure do |config|
  #config.ignored_exceptions += %w(ActionView::TemplateError ActionController::MissingFile)
  config.add_notifier :database, {}
end
4.异常日志记录
# coding: utf-8
# 异常通知
# lib/exception_notifier/database_notifier.rb
module ExceptionNotifier
  class DatabaseNotifier
    def initialize(_options)
      # do something with the options...
    end

    def call(exception, options = {})
      begin
        @ip              = (options[:env]['HTTP_X_REAL_IP'] || options[:env]['action_dispatch.remote_ip'].instance_variable_get(:@ip))
        @controller_info = options[:env]['action_dispatch.request.parameters']['controller']
        @action_info     = options[:env]['action_dispatch.request.parameters']['action']
        @params          = options[:env]['action_dispatch.request.parameters'].p2h
        @params.delete_if { |key, _value| ['authenticity_token', 'utf8', 'action', 'controller'].include?(key) }
      rescue
        nil
      end
      @title   = exception.message
      messages = []
      messages << exception.inspect
      unless exception.backtrace.blank?
        messages << "\n"
        messages << exception.backtrace[0, 100]
      end

      if Rails.env.production? 
        ExceptionLog.create(title:      @title,
                            body:       messages.join("\n"),
                            controller: @controller_info,
                            action:     @action_info,
                            params:     @params.to_json,
                            ip:         @ip,
                            local_ip:   $server_ip)
      else
        puts "\n======================"
        puts messages.join("\n")
        puts "======================\n"
      end
    end
  end
end
上一篇下一篇

猜你喜欢

热点阅读