Adding Log model for database-based log messages
This commit is contained in:
parent
e1bef18152
commit
ac3d52a66e
4 changed files with 61 additions and 0 deletions
27
app/models/log.rb
Normal file
27
app/models/log.rb
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
require 'pry'
|
||||||
|
|
||||||
|
class Log < ActiveRecord::Base
|
||||||
|
validates :message, presence: true
|
||||||
|
|
||||||
|
validates :section, presence: true
|
||||||
|
validates :section, inclusion: { in: ['importer', 'upload', 'frontend'] }
|
||||||
|
|
||||||
|
validates :level, presence: true
|
||||||
|
validates :level, inclusion: { in: ['info', 'error'] }
|
||||||
|
|
||||||
|
def self.log(message, section='frontend', level='info')
|
||||||
|
log = Log.new
|
||||||
|
|
||||||
|
ip_address = request.remote_ip if defined? request
|
||||||
|
token = session[:token] if defined? session
|
||||||
|
|
||||||
|
log.message = message
|
||||||
|
log.section = section
|
||||||
|
log.level = level
|
||||||
|
log.ip_address = ip_address
|
||||||
|
log.token = token
|
||||||
|
logger.error "Could not log to database - validation errors: #{log.errors.to_a}" unless log.valid?
|
||||||
|
log.save
|
||||||
|
log
|
||||||
|
end
|
||||||
|
end
|
||||||
13
db/migrate/20150426141106_create_logs.rb
Normal file
13
db/migrate/20150426141106_create_logs.rb
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
class CreateLogs < ActiveRecord::Migration
|
||||||
|
def change
|
||||||
|
create_table :logs do |t|
|
||||||
|
t.string :message # text message
|
||||||
|
t.string :level # 'info' or 'warning'
|
||||||
|
t.string :section # 'importer' or 'upload'
|
||||||
|
t.string :token # cookie session token to track users (if available)
|
||||||
|
t.inet :ip_address # IP address of the user (if available)
|
||||||
|
|
||||||
|
t.timestamps null: false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
12
test/fixtures/logs.yml
vendored
Normal file
12
test/fixtures/logs.yml
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
# Read about fixtures at
|
||||||
|
# http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
|
||||||
|
|
||||||
|
one:
|
||||||
|
message: Import of DEB archive successful.
|
||||||
|
level: info
|
||||||
|
section: importer
|
||||||
|
|
||||||
|
two:
|
||||||
|
message: Upload of package failed.
|
||||||
|
level: error
|
||||||
|
section: upload
|
||||||
9
test/models/log_test.rb
Normal file
9
test/models/log_test.rb
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
require "test_helper"
|
||||||
|
|
||||||
|
class LogTest < ActiveSupport::TestCase
|
||||||
|
|
||||||
|
def log
|
||||||
|
@log ||= Log.new
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
Loading…
Add table
Add a link
Reference in a new issue