ruby-on-rails 使用rails标记的日志记录,我如何记录消息的日志级别?

dba5bblo  于 5个月前  发布在  Ruby
关注(0)|答案(3)|浏览(80)

我的rails logger配置当前记录当前时间和UUID,如下所示:

config.logger = ActiveSupport::TaggedLogging.new(Logger.new("#{Rails.root}/log/#{ENV['RAILS_ENV']}.log", 'daily'))
config.log_tags = [Proc.new {Time.now.strftime('%Y-%m-%d %H:%M:%S.%L')}, :uuid]

字符串
有没有办法也记录当前消息的日志级别?
也就是说,如果我调用logger.debug,标签[DEBUG]将被添加到消息中。

jfgube3f

jfgube3f1#

Railscasts展示了如何通过覆盖SimpleFormatter#call方法来覆盖日志记录器以输出日志消息的严重性:

class Logger::SimpleFormatter
  def call(severity, time, progname, msg)
    "[#{severity}] #{msg}\n"
  end
end

字符串
详情请参见http://railscasts.com/episodes/56-the-logger-revised

apeeds0o

apeeds0o2#

我们不能改变来自数据库过程的消息,但我们只能通过显示时间和改变它的颜色和严重性来改变日志的外观。
使用以下代码更新日志。将下面的代码粘贴到需要在config/initilizers创建的新文件中。

class ActiveSupport::Logger::SimpleFormatter
SEVERITY_TO_TAG_MAP     = {'DEBUG'=>'meh', 'INFO'=>'fyi', 'WARN'=>'hmm', 'ERROR'=>'wtf', 'FATAL'=>'omg', 'UNKNOWN'=>'???'}
SEVERITY_TO_COLOR_MAP   = {'DEBUG'=>'0;37', 'INFO'=>'32', 'WARN'=>'33', 'ERROR'=>'31', 'FATAL'=>'31', 'UNKNOWN'=>'37'}
USE_HUMOROUS_SEVERITIES = true

def call(severity, time, progname, msg)
  if USE_HUMOROUS_SEVERITIES
    formatted_severity = sprintf("%-3s",SEVERITY_TO_TAG_MAP[severity])
  else
    formatted_severity = sprintf("%-5s",severity)
  end

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

  "\033[0;37m#{formatted_time}\033[0m [\033[#{color}m#{formatted_severity}\033[0m] #{msg.strip} (pid:#{$$})\n"
end

字符串

wh6knrhe

wh6knrhe3#

我把MyApp::Application.config.log_level添加到日志标记中,它对我很有效。

config.log_tags = [Proc.new {Time.now.strftime('%Y-%m-%d %H:%M:%S.%L')}, :uuid, Proc.new {MyApp::Application.config.log_level}]

字符串

相关问题