在日志消息之前添加当前时间 [英] Add current time before log message

查看:70
本文介绍了在日志消息之前添加当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅通过将这段代码添加到config/environment.rb中,就为我的应用程序创建了一个名为CRON_LOG的自定义记录器

I created a custom logger for my application, called CRON_LOG, just by adding this piece of code to config/environment.rb

CRON_LOG = Logger.new("#{Rails.root}/log/cron.log")
CRON_LOG.level = Logger::INFO

然后,当我想记录一些内容时,只需执行以下操作即可:

And then, when I want to log something, just do that:

CRON_LOG.info "something"

它工作正常,但是我想在每条日志消息之前添加当前时间戳.当然,我可以只将Time.now添加到我的日志消息中,但是我想知道是否有一种方法可以将其默认添加到每条日志消息中.我该怎么办?

It works fine, but I'd like to add the current timestamp before each log message. Of course I can just add Time.now to my log message, but I'd like to know if there is a way to add it as default to every log message. How can I do that ?

谢谢.

推荐答案

制作SysLog格式的记录器的最简单方法是直接分配格式器:

The easiest way to make a SysLog-formatted logger is to assign a formatter directly:

logger = Logger.new Rails.root.join('path', 'to', 'log')
logger.formatter = Logger::Formatter.new
logger.info 'Hello, world!'
# Writes:
#
#   I, [2011-06-02T20:02:34.579501 #15444]  INFO -- : Hello, world!

这篇关于在日志消息之前添加当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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