Ruby-on-rails 如何在独立日志文件中记录 Rails 中的某些内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/337739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to log something in Rails in an independent log file?
提问by akshat
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.
在 Rails 中,我想在不同的日志文件中记录一些信息,而不是标准的 development.log 或 production.log。我想从模型类进行此日志记录。
回答by Thiago Arrais
You can create a Logger object yourself from inside any model. Just pass the file name to the constructor and use the object like the usual Rails logger:
您可以从任何模型内部自己创建 Logger 对象。只需将文件名传递给构造函数并像通常的 Rails 一样使用对象logger:
class User < ActiveRecord::Base
def my_logger
@@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
end
def before_save
my_logger.info("Creating user with name #{self.name}")
end
end
Here I used a class attribute to memoize the logger. This way it won't be created for every single User object that gets created, but you aren't required to do that. Remember also that you can inject the my_loggermethod directly into the ActiveRecord::Baseclass (or into some superclass of your own if you don't like to monkey patch too much) to share the code between your app's models.
在这里,我使用了一个类属性来记忆记录器。这样就不会为每个创建的 User 对象创建它,但您不需要这样做。还请记住,您可以将my_logger方法直接注入到ActiveRecord::Base类中(或者,如果您不喜欢过多地修补补丁,则可以注入到您自己的某个超类中)以在您的应用程序模型之间共享代码。
回答by lulalala
Update
更新
I made a gem based on the solution below, called multi_logger. Just do this in the initializer:
我根据下面的解决方案制作了一个 gem,称为multi_logger。只需在初始化程序中执行此操作:
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.
更完整的解决方案是将以下内容放在您的lib/或config/initializers/目录中。
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.
好处是您可以设置格式化程序来自动为日志添加时间戳或严重性的前缀。这可以从 Rails 的任何地方访问,并且通过使用单例模式看起来更整洁。
# 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
回答by Vaughn Draughon
A decent option that works for me is to just add a fairly plain class to your app/modelsfolder such as app/models/my_log.rb
对我有用的一个不错的选择是在您的app/models文件夹中添加一个相当简单的类,例如app/models/my_log.rb
class MyLog
def self.debug(message=nil)
@my_log ||= Logger.new("#{Rails.root}/log/my.log")
@my_log.debug(message) unless message.nil?
end
end
then in your controller, or really almost anywhere that you could reference a model's class from within your rails app, i.e. anywhere you could do Post.create(:title => "Hello world", :contents => "Lorum ipsum");or something similar you can log to your custom file like this
然后在你的控制器中,或者几乎任何你可以从你的 Rails 应用程序中引用模型类的地方,即你可以做的任何地方Post.create(:title => "Hello world", :contents => "Lorum ipsum");或类似的事情,你可以像这样登录到你的自定义文件
MyLog.debug "Hello world"
回答by Les Nightingill
Define a logger class in (say) app/models/special_log.rb:
在(比如说)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:
在(比如说)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")
回答by Dorian
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
回答by Tony
class Article < ActiveRecord::Base
LOGFILE = File.join(RAILS_ROOT, '/log/', "article_#{RAILS_ENV}.log")
def validate
log "was validated!"
end
def log(*args)
args.size == 1 ? (message = args; severity = :info) : (severity, message = args)
Article.logger severity, "Article##{self.id}: #{message}"
end
def self.logger(severity = nil, message = nil)
@article_logger ||= Article.open_log
if !severity.nil? && !message.nil? && @article_logger.respond_to?(severity)
@article_logger.send severity, "[#{Time.now.to_s(:db)}] [#{severity.to_s.capitalize}] #{message}\n"
end
message or @article_logger
end
def self.open_log
ActiveSupport::BufferedLogger.new(LOGFILE)
end
end
回答by hlcs
class Post < ActiveRecord::Base
def initialize(attributes)
super(attributes)
@logger = Logger.new("#{Rails.root}/log/post.log")
end
def logger
@logger
end
def some_method
logger.info('Test 1')
end
end
ps = Post.new
ps.some_method
ps.logger.info('Test 2')
Post.new.logger.info('Test 3')
回答by Kangur
I would suggest using Log4r gemfor custom logging. Quoting description from its page:
我建议使用Log4r gem进行自定义日志记录。从其页面引用描述:
Log4r is a comprehensive and flexible logging library written in Ruby for use in Ruby programs. It features a hierarchical logging system of any number of levels, custom level names, logger inheritance, multiple output destinations per log event, execution tracing, custom formatting, thread safteyness, XML and YAML configuration, and more.
Log4r 是一个全面而灵活的日志库,用 Ruby 编写,用于 Ruby 程序。它具有任意数量级别的分层日志系统、自定义级别名称、记录器继承、每个日志事件的多个输出目的地、执行跟踪、自定义格式、线程安全性、XML 和 YAML 配置等。
回答by olleolleolle
The Logging framework, with its deceptively simple name, has the sophistication you crave!
Logging 框架以其看似简单的名称,拥有您渴望的复杂功能!
Follow the very short instructions of logging-railsto get started filtering out noise, getting alerts, and choosing output in a fine-grained and high-level way.
按照logging-rails的非常简短的说明开始过滤噪音,获取警报,并以细粒度和高级的方式选择输出。
Pat yourself on the back when you are done. Log-rolling, daily. Worth it for that alone.
完成后拍拍自己的背。日志滚动,每天。仅此而已就值得了。

