Logging in Sinatra?

前端 未结 4 1624
囚心锁ツ
囚心锁ツ 2020-12-02 10:49

I\'m having trouble figuring out how to log messages with Sinatra. I\'m not looking to log requests, but rather custom messages at certain points in my app. For example, whe

4条回答
  •  日久生厌
    2020-12-02 11:02

    Here's another solution:

    module MySinatraAppLogger
      extend ActiveSupport::Concern
    
      class << self
        def logger_instance
          @logger_instance ||= ::Logger.new(log_file).tap do |logger|
            ::Logger.class_eval { alias :write :'<<' }
            logger.level = ::Logger::INFO
          end
        end
    
        def log_file
          @log_file ||= File.new("#{MySinatraApp.settings.root}/log/#{MySinatraApp.settings.environment}.log", 'a+').tap do |log_file|
            log_file.sync = true
          end
        end
      end
    
      included do
        configure do
          enable :logging
          use Rack::CommonLogger, MySinatraAppLogger.logger_instance
        end
    
        before { env["rack.errors"] = MySinatraAppLogger.log_file }
      end
    
      def logger
        MySinatraAppLogger.logger_instance
      end
    end
    
    class MySinatraApp < Sinatra::Base
      include MySinatraAppLogger
      get '/' do
        logger.info params.inspect
      end
    end
    

    Of course, you can do it without ActiveSupport::Concern by putting the configure and before blocks straight into MySinatraApp, but what I like about this approach is that it's very clean--all logging configuration is totally abstracted out of the main app class.

    It's also very easy to spot where you can change it. For instance, the SO asked about making it log to console in development. It's pretty obvious here that all you need to do is a little if-then logic in the log_file method.

提交回复
热议问题