简体   繁体   中英

log4j in a JRuby on Rails app - redirecting logs to a separate file

I want to get more granular logging in my JRuby on Rails app. I introduced log4j. I currently have a properties file that looks like the following:

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

#
log4j.logger.Rails=INFO, A

log4j.appender.A=org.apache.log4j.RollingFileAppender
log4j.appender.A.File=/usr/share/tomcat6/logs/production.log
log4j.appender.A.MaxFileSize=10000KB
log4j.appender.A.MaxBackupIndex=5
log4j.appender.A.layout=org.apache.log4j.PatternLayout
log4j.appender.A.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

To get Rails.logger to use this, I pop in the following initializer:

org.apache.log4j.PropertyConfigurator.configure("#{::Rails.root.to_s}/config/log4j.properties")

Now, I want to be able to also do something like:

Rails.logger.feature_1("Log to feature_1.log")
Rails.logger.feature_N("Log to feature_N.log")

What's the best way of accomplishing this so not everything goes to one log file?

Also just to note, I am using the adapter that was blogged about here: http://squaremasher.blogspot.com/2009/08/jruby-rails-and-log4j.html

First, you should define an appender/logger configuration for each "feature" you need in your log4j.properties file :

...
log4j.logger.Rails=INFO, A

log4j.appender.A=org.apache.log4j.RollingFileAppender
log4j.appender.A.File=/usr/share/tomcat6/logs/production.log

...
log4j.logger.feature_1=INFO, feature_1

log4j.appender.feature_1=org.apache.log4j.RollingFileAppender
log4j.appender.feature_1.File=/path/to/your/feature_1.log
...
log4j.logger.feature_N=INFO, feature_N

log4j.appender.feature_N=org.apache.log4j.RollingFileAppender
log4j.appender.feature_N.File=/path/to/your/feature_N.log

This way each logger will have it own severity filter and destination file.

Then instead of always using the same logger you may select it depending on the method you called on the Ruby side of the moon (from the example adapter you provided) :

class Log4jAdapter

  def method_missing(meth, *args)
    # Checking the method name matches feature_N
    if /\Afeature_(\d+)\z/ =~ method.to_s
      # Retrieve the appropriate logger => getLogger('feature_N')
      logger = org.apache.log4j.Logger.getLogger(method.to_s)
      # Log !
      logger.log *args
    else
        puts "UNSUPPORTED METHOD CALLED: #{meth}"
    end
  end

end

Untested but I think you'll get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM