ruby-on-rails 在Rails4.2和lograge中,如何在每个日志行之前启用日期/时间?

eqfvzcg8  于 2023-05-08  发布在  Ruby
关注(0)|答案(4)|浏览(101)

我使用gem“Lograge”0.3.6和Rails 4.2。我在我的config/environments/development.rb文件中配置了这个

config.lograge.enabled = true
  config.lograge.formatter = CustomLogstash.new

但是,我注意到log/development.log文件中的输出并不包含每行前面的日期/时间。如何配置lograge(或者只是我的Rails日志记录器)?)在文件的每一行前面加上日期和时间?

suzh9iv8

suzh9iv81#

根据document,lograge gem提供了以下日志格式化程序。

Lograge::Formatters::Lines.new  # need to install "lines" gem
Lograge::Formatters::Cee.new
Lograge::Formatters::Graylog2.new
Lograge::Formatters::KeyValue.new  # default lograge format
Lograge::Formatters::Json.new
Lograge::Formatters::Logstash.new  # need to install "logstash-event" gem 
Lograge::Formatters::LTSV.new
Lograge::Formatters::Raw.new       # Returns a ruby hash object

默认情况下,lograge gem使用Lograge::Formatters::KeyValue.new作为日志。
您可以通过使用CustomLogStash类进行一些更改来定制它并使其通用。

class CustomLogStash < Lograge::Formatters::KeyValue
  def call(data)
    # I'm using timestamp key here, you can choose whatever you want.
    data_hash = { timestamp: Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%3N")}.merge!(data)
    super(data_hash)
  end
end

同样,您可以使用任何Lograge::Formatters类并将自定义格式应用于日志。
现在将下面的代码添加到config/initializers/lograge.rb文件中。

Rails.application.configure do
  config.lograge.enabled = true
  config.lograge.formatter = CustomLogStash.new
end

现在重新启动服务器并在浏览器中加载页面。您将看到类似下面的日志:

timestamp=2021-11-21T17:14:10.726 method=GET path=/categories format=html controller=categories action=index status=200 duration=259.11 view=244.91 db=2.60

已编辑

如果您正在查找类似x1c 0d1x的日志
那么你不需要任何宝石。您可以通过在首选的开发/生产/测试环境中添加以下行来实现此目的

config.log_level = :debug
config.log_formatter = ::Logger::Formatter.new

如果您想在所有环境中应用此功能,请将上面的行添加到config/application.rb文件中。

js5cn81o

js5cn81o2#

如果有帮助的话,你可以在配置中添加以下内容吗?

config.lograge.formatter = ->(data) { data.reverse_merge({time: Time.now}) }# data is a ruby hash.

它会给予你如下的输出

{:time=>2021-11-16 12:26:24.65362 +0000, :method=>"GET", :path=>"/", :format=>:html, :controller=>"Controller", :action=>"index", :status=>200, :duration=>393.41, :view=>85.55, :db=>1.38}
mpgws1up

mpgws1up3#

是否可以粘贴CustomLogstash类的内容?从docs来看,该类应该响应call方法,返回Hash
这对我很有效:

class CustomLogstash
  def call(data)
    { time: Time.now, controller: data[:controller] } # this can be anything as long it is Hash, eg. data.merge(time: Time.now)

  end
end

上面的示例输出:

{:time=>"2021-11-18T20:31:41.486+01:00", :controller=>"calendar_events"}
svmlkihl

svmlkihl4#

根据logrageofficial documentation,您可以使用custom_options

编辑1:custom_options使用time: Time.nowtime:event.time

Rails.application.configure do
  config.lograge.enabled = true
  config.lograge.formatter = Lograge::Formatters::Logstash.new

  # add time to lograge
  config.lograge.custom_options = lambda do |event|
    { time: Time.now } #or use time:event.time 
  end
end

注意:使用logstash输出时,需要添加额外的gem logstash-event。您可以简单地将其添加到Gemfile中,如下所示

gem "logstash-event"

编辑2:根据评论更新custom_options使用:time => event.time

#config/environments/production.rb
MyApp::Application.configure do
  config.lograge.enabled = true

  # add time to lograge
  config.lograge.custom_options = lambda do |event|
    {:time => event.time}
  end
end

以下自定义选项,该选项是使用**time: event.time.to_s(:db)**记录的lograge issue to ensure both日期和时间中的修复

config.lograge.custom_options = lambda do |event|
      unwanted_keys = %w[format action controller utf8]
      params = event.payload[:params].reject { |key,_| unwanted_keys.include? key }
      {time: event.time.to_s(:db), user: event.payload[:user], params: params}
    end

或者您可以使用此Custom logger

# Define a setter to pass in a custom log formatter

class ActiveSupport::BufferedLogger

  def formatter=(formatter)

    @log.formatter = formatter

  end

end


# Defines a custom log format (time, severity, message, PID, backtrace)... all with color!

class Formatter

  SEVERITY_TO_TAG   = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}

  SEVERITY_TO_COLOR = {'DEBUG'=>'37',  'INFO'=>'32',  'WARN'=>'33',  'ERROR'=>'31',  'FATAL'=>'31',  'UNKNOWN'=>'37'}

  HUMOR_FOR_ENV     = {development: true, test: true, production: false}

  DEPTH_FOR_ENV     = {development: 3,    test: 3,    production: 1}

  EXCLUSION_REGEX   = /log|active_support|active_record/


  def humorous?

    return @is_humorous if defined? @is_humorous

    @is_humorous = HUMOR_FOR_ENV[ Rails.env.to_sym ]

  end


  def depth

    @depth ||= DEPTH_FOR_ENV[ Rails.env.to_sym ]

  end


  def call(severity, time, progname, msg)

    t     = time.strftime("%Y-%m-%d %H:%M:%S.") << time.usec.to_s[0..2].rjust(3)

    color = SEVERITY_TO_COLOR[severity]

    sev   = humorous? ? "%-3s" % SEVERITY_TO_TAG[severity] # pad to at least 3 characters

                      : "%-5s" % severity                  # pad to at least 5 characters


    # 2013-05-01 19:16:00.785 [omg] oh noes! (pid:30976) (admin/user.rb:45:in `block (4 levels) in <top (required)>') <- `call' <- `content_for' <- `block (2 levels) in row' <- `block in build_tag'

    "\033[0;37m#{t}\033[0m [\033[#{color}m#{sev}\033[0m] #{msg.strip} (pid:#{$$}) #{whodunit}\033[0m\n"

  end


  def whodunit

    latest, *others = caller.select{ |a| a !~ EXCLUSION_REGEX }[0, depth]

    latest = latest[/(lib|app)\/(.*)/,-1] || latest

    string = ""

    string << "\033[36m(#{latest})"

    string << "\033[35m <- " + others.map{ |s| s[/`.*/] }.join(' <- ') if others.any?

    string

  end


end


Rails.logger.formatter = Formatter.new

对于Rails4.2,不要忘记添加ActiveSupport::TaggedLogging,以便能够像调用默认的rails logger一样调用自定义logger
ActiveSupport::TaggedLogging用于 Package 任何标准日志记录器示例,以便向日志语句添加“标记”。在这种情况下,一个“标记”通常描述一个子域,默认的Rails.logger使用它来允许您用子域、请求id等标记日志语句。在多用户、多示例生产应用程序中。

include 
ActiveSupport::TaggedLogging::Formatter

Formatter类。

相关问题