呵呵...... log4r的的思想來源於著名的「Log4j的」,這是我最喜歡的記錄在我的java編程的生活。 但是log4r的文檔真的很差,對新手來說真的很難。讓我展示我的解決方案:
Step1。創建log4r配置文件:(文件名:config/log4r.yml)
log4r_config:
# define all loggers ...
loggers:
- name : production
level : WARN
trace : 'false'
outputters :
- datefile
- name : development
level : DEBUG
trace : 'true'
outputters :
- datefile
# define all outputters (incl. formatters)
outputters:
- type: DateFileOutputter
name: datefile
dirname: "log"
# notice the file extension is needed!
# if you want the file is named by the process, just comment it,
# then it will automatically get the same name with its process,
# e.g. rails_2017-05-03.log
filename: "my_app.log"
formatter:
date_pattern: '%H:%M:%S'
pattern : '%d %l: %m '
type : PatternFormatter
step2。修改config/application.rb
require 'rails/all'
# add these line for log4r
require 'log4r'
require 'log4r/yamlconfigurator'
require 'log4r/outputter/datefileoutputter'
include Log4r
Bundler.require(:default, Rails.env) if defined?(Bundler)
module Zurich
class Application < Rails::Application
#...
# assign log4r's logger as rails' logger.
log4r_config= YAML.load_file(File.join(File.dirname(__FILE__),"log4r.yml"))
YamlConfigurator.decode_yaml(log4r_config['log4r_config'])
config.logger = Log4r::Logger[Rails.env]
end
end
step3。將此行添加到您的Gemfile中。
# which is the latest version and support "datefileoutputter"
gem 'log4r', '1.1.9'
(如果你使用Rails 4+,還有第四步:這個文件添加到配置/初始化文件夾
# config/initializers/log4r_patch_for_rails4.rb
class Log4r::Logger
def formatter()
end
end
)
它的完成。現在,「CD」到你的Rails應用程序文件夾,運行「捆綁」安裝log4r的,然後在「軌道的」, 你會發現在「/登錄」文件夾這樣的日誌文件:
May 9 17:05 rails_2011-05-09.log
May 10 13:42 rails_2011-05-10.log
和日誌內容(我最喜歡的格式):
$ tail log/rails_2011-05-10.log
Started GET "/????_settings/19/edit" for 127.0.0.1 at ...
13:42:11 INFO: Processing by ????SettingsController ...
13:42:11 INFO: Parameters: {"id"=>"19"}
13:42:12 DEBUG: ????Setting Load (0.0ms) SELECT "d ...
13:42:12 INFO: Completed 200 OK in 750ms
我的環境:
- OS:在XP
- 紅寶石1.8.7(2011-02-18 PATCHLEVEL運行的cygwin 334)[I386-的mingw32]
- 導軌:3.0.5
- 寶石:1.6.0
有任何問題,請讓我知道了〜:-)
參考:https://stackoverflow.com/a/20154414/445908
你爲什麼要這麼做? – jvatic 2011-04-16 01:17:21
允許使用時間戳記進行可定製的應用程序日誌記錄,基於時間的日誌文件輪換,上下文級別日誌分隔。這些是我想要的一些功能。 – user553620 2011-04-20 04:25:47
我解決了這個異常 - 在Rails 3中,Rails.root的值不是一個字符串對象。將變量定義更改爲Rails.root.to_s修復了上述錯誤。希望這可以幫助某人。 – user553620 2011-04-20 04:27:37