Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

ruby - Rails: Logging for code in the lib directory?

What is the best/easiest way to configure logging for code kept in the lib directory?

question from:https://stackoverflow.com/questions/2980500/rails-logging-for-code-in-the-lib-directory

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's two ways to go about it:

  • Assuming your library is self-contained and has a module, you can add a logger attribute to your module and use that everywhere in your library code.

    module MyLibrary
      mattr_accessor :logger
    end
    

    You then either use an initializer in config/initializers/, or an config.after_initialize block in config/environment.rb to initialize your logger, like so:

    require 'mylibrary'
    MyLibrary.logger = Rails.logger
    

    This would still allow you to use your self-contained library from scripts outside of Rails. Which is nice, on occasion.

  • If using your library without Rails really doesn't make sense at all, then you can also just use Rails.logger directly.

In either case, you're dealing with a standard Ruby Logger. Also keep in mind that, in theory, the logger may be nil.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...