开发者

Use Log4r as logger in Sinatra App

I want to use log4r with log-levels info, warn and error in a Sinatra 1.3.1 app. The output should go to 开发者_运维知识库requests.log (http requests), error.log and sinatra.log (other outputs).

How do I go about configuring it?

I've just spent a lot of time googling related articles, but haven't found anything. Help is appreciated...


Write a middleware that replaces env['rack.errors'] and env['rack.logger'].


I assume you are using classic sinatra. ( only have 1 file named app.rb, and you run it with $ ruby app.rb)

  1. in app.rb:

    require 'sinatra'
    
    # load the lib/logger_tool.rb
    Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
    
    # define the logger as global variable.
    $logger = LoggerTool.get_logger log_file_postfix: ENV['market_id'], 
        name: Sinatra::Application.environment.to_s
    
    get '/' do
      $logger.info "-- in hihihi"
      'hihihi'
    end
    
  2. in lib/logger_file.rb

    require 'log4r'
    require 'log4r/yamlconfigurator'
    require 'log4r/outputter/datefileoutputter'
    
    class LoggerTool
      include Log4r
    
      def self.get_logger options
    
        log4r_config= YAML.load_file(File.join(File.dirname(__FILE__), '..', "config", "log4r.yml"))
        temp = log4r_config['log4r_config']
    
        # change the log filename to xx.log (must end with .log)
        # this is optional
        temp["outputters"][0]['filename'] = "my_log_#{options[:log_file_postfix]}.log"
    
        # in test environment, let's rename it as "test.log"
        if options[:name] == 'test'
          temp["outputters"][0]['filename'] = "test"
        end
    
        YamlConfigurator.decode_yaml(temp)
    
        return Log4r::Logger[options[:name]]
      end
    end
    
  3. in config/log4r.yml

    log4r_config:
      # define all loggers ...
      loggers:
        - name      : production
          level     : WARN
          trace     : 'false'
          outputters :
          - datefile
        - name      : development
          level     : DEBUG
          trace     : 'true'
          outputters :
          - datefile
        - name      : test
          level     : DEBUG
          trace     : 'true'
          outputters :
          - datefile
    
      outputters:
      - type: DateFileOutputter
        name: datefile
        dirname: "log"
        #filename: "my_app.log"   # here we comment it out. 
        formatter:
          date_pattern: '%H:%M:%S'
          pattern     : '%d %l: %m '
          type        : PatternFormatter
    
  4. run sinatra via $ ruby app.rb and visit http://localhost:4567/, you will find in your log folder a newly create log file out there.

    log/my_log_xx_2019_03_27.log

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜