rails 项目增加日志功能(log) loggable controller operation_logs admin log

访问量: 2749

操作日志是几乎每一个项目所必须要有的

我本来希望把它做成一个rails plugin 或者gem, 但是时间有限...

下面是rails中的增加步骤:

commit 4a78a43cf7344586de5b7f026e3f522fbc61a027
Author: 申思维 <shensiwei@sina.com>
Date:   Sun Apr 10 17:15:06 2022 +0800

    增加了管理员操作日志

diff --git a/Gemfile b/Gemfile
index 9dda67a..988635e 100644
--- a/Gemfile
+++ b/Gemfile
@@ -25,6 +25,8 @@ gem 'turbolinks', '~> 5'
 # Reduces boot times through caching; required in config/boot.rb
 gem 'bootsnap', '>= 1.4.4', require: false

+gem 'kaminari'
+
 group :development do
   #gem 'listen', '>= 3.0.5', '< 3.2'
   gem 'capistrano', '2.12.0'
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 90877d0..238f392 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,3 +1,23 @@
 class ApplicationController < ActionController::Base
   before_action :authenticate_manager!
+  before_action :save_log
+
+  private
+  def save_log
+    controller = params[:controller]
+    action = params[:action]
+    request_type = restful_method(params)
+    OperationLog.create!(:action => action, :controller => controller,
+        :user_name => current_manager.try(:email),
+        :parameters =>  params.inspect,
+        :remote_ip=> request.remote_ip,
+        :restful_method => restful_method(params)
+    )
+  end
+
+  # return: get, post, put or delete
+  def restful_method(params)
+    return request.method.downcase
+    #params[:authenticity_token].blank? ? 'get' : ((params[:_method]) || 'post')
+  end
 end
diff --git a/app/controllers/operation_logs_controller.rb b/app/controllers/operation_logs_controller.rb
new file mode 100644
index 0000000..4261814
--- /dev/null
+++ b/app/controllers/operation_logs_controller.rb
@@ -0,0 +1,6 @@
+class OperationLogsController < ApplicationController
+  def index
+    @logs = OperationLog.order('created_at desc').page(params[:page] || 1).per(100)
+  end
+
+end
diff --git a/app/models/operation_log.rb b/app/models/operation_log.rb
new file mode 100644
index 0000000..9fb7111
--- /dev/null
+++ b/app/models/operation_log.rb
@@ -0,0 +1,2 @@
+class OperationLog < ActiveRecord::Base
+end
diff --git a/app/views/operation_logs/index.html.erb b/app/views/operation_logs/index.html.erb
new file mode 100644
index 0000000..93ccf8e
--- /dev/null
+++ b/app/views/operation_logs/index.html.erb
@@ -0,0 +1,44 @@
+<h3>操作日志</h3>
+<div class='alert alert-info'>
+  所有人的操作日志都在这里. 各种误操作都可以在这里看到 , 包括错误的密码尝试
+</div>
+<%= paginate @logs %>
+<table class='table table-hover table-striped'>
+  <tr>
+    <th>ID</th>
+    <th>controller</th>
+    <th>action</th>
+    <th style='width: 160px'>时间</th>
+    <th>用户名</th>
+    <th style='width: 150px'>IP</th>
+    <th style=''>详情</th>
+  </tr>
+  <% @logs.each do |log| %>
+  <tr>
+    <td><%= log.id %></td>
+    <td><%= log.controller %></td>
+    <td><%= log.action %></td>
+
+    <td style='width: 160px'>
+      <%= log.created_at.strftime '%Y-%m-%d %H:%M:%S' %>
+    </td>
+    <td>
+      <%= log.user_name %>
+    </td>
+    <td style='width: 150px'>
+      <%= log.remote_ip %>
+    </td>
+    <td><%= log.parameters %></td>
+  </tr>
+  <% end %>
+
+</table>
+<%= paginate @logs %>
+
+<style>
+.code {
+  white-space: pre-wrap;
+  word-wrap: break-word;
+}
+</style>
+
diff --git a/config/routes.rb b/config/routes.rb
index d7b6716..6e8a755 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -9,4 +9,6 @@ Rails.application.routes.draw do
   resources :invalid_domains, only: [:index]
   resources :claims, only: [:index]
   resources :domains, only: [:index]
+
+  resources :operation_logs
 end
diff --git a/db/migrate/20220410085316_create_logs.rb b/db/migrate/20220410085316_create_logs.rb
new file mode 100644
index 0000000..4ad4e86
--- /dev/null
+++ b/db/migrate/20220410085316_create_logs.rb
@@ -0,0 +1,13 @@
+class CreateLogs < ActiveRecord::Migration[6.1]
+  def change
+    create_table :operation_logs, :comment => '操作日志表' do |t|
+      t.string :controller
+      t.string :action
+      t.string :remote_ip, :comment => '远程ip'
+      t.string :restful_method, :comment => '请求的方法,  get/post...'
+      t.string :user_name, :comment => '当前用户'
+      t.text :parameters, :comment => '各种参数'
+      t.datetime :created_at, :comment => '创建时间'
+    end
+  end
+end

下面的是老的,就不用看了,有的地方需要修改. 而且不需要 lib, include 啥的.

上面这个最简单了. 

1. Gemfile中
gem 'kaminari'
2. config/routes.rb
  namespace "monitor" do
    resources "logs"
  end 
3. app/controllers/monitor/logs_controller.rb :
class Monitor::LogsController < ApplicationController
  def index
    @logs = OperationLog.order('created_at desc').page(params[:page]).per(100)
  end
end
4. app/views/monitor/logs/index.hml.erb:
<h3>操作日志</h3>
<%= paginate @logs %>
<table >
<tr>
<th>controller</th>
<th>action</th>
<th>时间</th>
<th>用户名</th>
<th>详情</th>
</tr>
<% @logs.each do |log| %>
<tr>
<td><%= log.controller %></td>
<td><%= log.action %></td>
<td><%= log.created_at.strftime '%y-%m-%d %H:%M:%S' %></td>
<td><%= log.user_name %></td>
<td><%= log.params %></td>
</tr>
<% end %>

</table>
<%= paginate @logs %>

5. lib/loggable_controller:

module LoggableController
  def save_log
    controller = params[:controller]
    action = params[:action]
    request_type = restful_method(params)
    OperationLog.create!(:action => action, :controller => controller,
        :user_name => current_user.try(:email),
        :parameters =>  params.inspect,
        :remote_ip=> request.remote_ip,
        :restful_method => restful_method(params)
    )   
  end 

  private

  # return: get, post, put or delete
  def restful_method(params)
    return request.method.downcase
    #params[:authenticity_token].blank? ? 'get' : ((params[:_method]) || 'post')
  end
end

6. 然后,在 app/controller/application_controller 中: 

class ApplicationController < ActionController::Base
  include LoggableController
  before_filter :save_log
end
7. 在 config/initializers/loggable_controller.rb中:
Dir[Rails.root + 'lib/loggable_controller.rb'].each do |file|
  require file
end

8 . 创建 logs表:

class CreateLogs < ActiveRecord::Migration
  def change
    create_table :logs do |t| 
      t.string :controller
      t.string :action
      t.string :user_name
      t.text :parameters
      t.datetime :created_at
    end 
  end 
end

9. 创建 app/models/log.rb

# -*- encoding : utf-8 -*-
class Log < ActiveRecord::Base
end

10. 创建 migration $ bundle exec rails g migration create_operation_logs

class CreasteOperationLogs < ActiveRecord::Migration
  def change
    create_table :operation_logs, :comment => '操作日志表' do |t|
      t.string :controller
      t.string :action
      t.string :remote_ip, :comment => '远程ip'
      t.string :restful_method, :comment => '请求的方法,  get/post...'
      t.string :user_name, :comment => '当前用户'
      t.text :parameters, :comment => '各种参数'
      t.datetime :created_at, :comment => '创建时间'
    end
  end
end

订阅/RSS Feed

Subscribe

分类/category