How to log something in Rails in an independent lo

2019-01-09 23:06发布

In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.

9条回答
2楼-- · 2019-01-10 00:04

Update

I made a gem based on the solution below, called multi_logger. Just do this in the initializer:

MultiLogger.add_logger('post')

and call

Rails.logger.post.error('hi')
# or call logger.post.error('hi') if it is accessible.

and you are done.

If you want to code it yourself, see below:


A more complete solution would be to place the following in your lib/ or config/initializers/ directory.

The benefit is that you can setup formatter to prefix timestamps or severity to the logs automatically. This is accessible from anywhere in Rails, and looks neater by using the singleton pattern.

# Custom Post logger
require 'singleton'
class PostLogger < Logger
  include Singleton

  def initialize
    super(Rails.root.join('log/post_error.log'))
    self.formatter = formatter()
    self
  end

  # Optional, but good for prefixing timestamps automatically
  def formatter
    Proc.new{|severity, time, progname, msg|
      formatted_severity = sprintf("%-5s",severity.to_s)
      formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
      "[#{formatted_severity} #{formatted_time} #{$$}] #{msg.to_s.strip}\n"
    }
  end

  class << self
    delegate :error, :debug, :fatal, :info, :warn, :add, :log, :to => :instance
  end
end

PostLogger.error('hi')
# [ERROR 2012-09-12 10:40:15] hi
查看更多
Juvenile、少年°
3楼-- · 2019-01-10 00:05

Define a logger class in (say) app/models/special_log.rb:

class SpecialLog
  LogFile = Rails.root.join('log', 'special.log')
  class << self
    cattr_accessor :logger
    delegate :debug, :info, :warn, :error, :fatal, :to => :logger
  end
end

initialize the logger in (say) config/initializers/special_log.rb:

SpecialLog.logger = Logger.new(SpecialLog::LogFile)
SpecialLog.logger.level = 'debug' # could be debug, info, warn, error or fatal

Anywhere in your app, you can log with:

SpecialLog.debug("something went wrong")
# or
SpecialLog.info("life is good")
查看更多
成全新的幸福
4楼-- · 2019-01-10 00:08

Here is my custom logger:

class DebugLog
  def self.debug(message=nil)
    return unless Rails.env.development? and message.present?
    @logger ||= Logger.new(File.join(Rails.root, 'log', 'debug.log'))
    @logger.debug(message) 
  end
end
查看更多
登录 后发表回答