Skip to content

Instantly share code, notes, and snippets.

@djberg96
Created June 30, 2021 04:49
Show Gist options
  • Save djberg96/dc261ec8a2b296a9f3465f9c394c11b1 to your computer and use it in GitHub Desktop.
Save djberg96/dc261ec8a2b296a9f3465f9c394c11b1 to your computer and use it in GitHub Desktop.
# 1) Create lib/loggers/database_logger.rb using code below.
# 2) Create 'logs' table (and corresponding Log model) with timestamp, severity, and message columns (plus whatever else you want).
# 3) In configuration file of your choice (application, development, etc) first do 'require "loggers/database_logger"'
# 4) then set config.logger to Loggers::DatabaseLogger.new
module Loggers
class DatabaseLogger < ActiveSupport::Logger
# Set logdev to nil to prevent it from writing to a file.
def initialize(logdev = nil, *args)
super(logdev, *args)
end
# Redefine the add method from the core Logger class so that it
# writes to the database.
#
def add(severity, message = nil, _progname = nil, &block)
severity ||= UNKNOWN
if message.nil? && block_given?
message = yield
end
# Possibly return if severity doesn't match level
return unless message
# Prevent the Log.create call from logging itself, which
# otherwise causes an infinite loop.
silence do
::Log.create(
:message => message.strip,
:severity => map(severity),
:timestamp => Time.now,
)
end
end
# Use a nice string instead of a number
def map(severity)
case severity
when DEBUG
"DEBUG"
when INFO
"INFO"
when WARN
"WARN"
when ERROR
"ERROR"
when FATAL
"FATAL"
else
"UNKNOWN"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment