1.Gemfile增加

gem 'exception_notification'

2.新增 lib/exception_notifier/database_notifier.rb

# coding: utf-8
# 异常通知
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

3.生成默认配置文件rails g exception_notification:install或者直接新增 config/initializers/exception_notification.rb
4.创建异常信息存储表

   create_table :exception_logs do |t|
      t.text     "title",      limit: 2147483647, comment: "错误标题"
      t.text     "body",       limit: 2147483647, comment: "错误体"
      t.string   "controller",                    comment: "控制器名"
      t.string   "action",                        comment: "行为器名"
      t.text     "params",                        comment: "参数名字"
      t.string   "ip",                            comment: "IP"
      t.string   "local_ip",                      comment: "本地ip"
      t.timestamps
    end

5.创建对应 Model 及 Controller View即可。

0条评论 顺序楼层
请先登录再回复