如何在请求范围之外访问Sinatra的记录器 [英] How do I access Sinatra's Logger outside the Request Scope

查看:47
本文介绍了如何在请求范围之外访问Sinatra的记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Sinatra的记录器仅在请求处理程序中可用(请参见 https://github.com/sinatra/sinatra#logging ),但是如果我想在其他地方使用记录器,例如在辅助方法或configure挂钩中怎么办?可以通过其他方式使用Sinatra记录器吗?

It seems that Sinatra's logger is only available inside request handlers (See https://github.com/sinatra/sinatra#logging), but what if I want to use a logger in other places, for example in helper methods or in the configure hook? Is the Sinatra logger available through other means?

推荐答案

文档提供有关范围的一些示例,但是您可以在helper块中定义的方法中看到logger助手,因为该助手块具有Application范围.在configure内它不可用,但是我倾向于做的是无论如何都要在rackup文件中将自己的日志设置为常量或类实例变量,然后在configure(以及其他任何位置)中可用.仅作为一个应用程序的示例:

The docs give some examples on scope, but you can see the logger helper within methods defined in the helper block, as the helper block has Application scope. Within configure it's not available, but what I tend to do is set up my own logging anyway, within the rackup file as a constant or class instance variable, and then it's available within configure (and anywhere else). As an example for just a single application:

require 'sinatra'
require 'logger'

configure do
  set :logging, nil
  logger = Logger.new STDOUT
  logger.level = Logger::INFO
  logger.datetime_format = '%a %d-%m-%Y %H%M '
  set :logger, logger
end

helpers do
  def check
    settings.logger.info "I'm inside a helper"
    # if you were using Sinatra's logger, you could just call
    # logger.info "I'm inside a helper"
    # and it would work, but only if you've not done the stuff above
    # in the configure block
  end
end

get "/" do
  check # this would work for the way above, or with the Sinatra logger
  "Hello, World!"
end

get "/another" do
  settings.logger.info "Using the settings helper this time" # this only works
  # when you've defined your own logger
  "Hello again"
end


作为更好的全局"类实例变量的示例:


An example as a class instance variable as a better "global":

class MyLogger
  def self.logger
    if @_logger.nil?
      @_logger = Logger.new STDOUT
      @_logger.level = Logger::INFO
      @_logger.datetime_format = '%a %d-%m-%Y %H%M '
    end
    @_logger
  end
end

,然后在需要的地方使用:

and then use wherever needed:

configure do
  set :logging, nil
  logger = MyLogger.logger
  set :logger, logger
end

或在班上:

class AnotherClass

  def some_method
    MyLogger.logger.warn "I'm in some method"
  end


Sinatra(自1.3版开始)还带有记录日志的助手这是用于登录到STDOUT的食谱以及您可能也会发现有用的文件.


Sinatra also comes (since 1.3) with a helper for logging, and here is a recipe for logging to STDOUT and a file that you may find useful too.

这篇关于如何在请求范围之外访问Sinatra的记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆