Rails에서 무언가를 독립적 인 로그 파일로 기록하는 방법은 무엇입니까?
레일에서는 표준 development.log 또는 production.log가 아닌 다른 로그 파일에 일부 정보를 기록하려고합니다. 모델 클래스 에서이 로깅을 수행하고 싶습니다.
모든 모델 내에서 직접 Logger 객체를 만들 수 있습니다. 파일 이름을 생성자에 전달하고 일반적인 Rails와 같은 객체를 사용하십시오 logger
.
class User < ActiveRecord::Base
def my_logger
@@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
end
def before_save
my_logger.info("Creating user with name #{self.name}")
end
end
여기에서는 클래스 속성을 사용하여 로거를 메모했습니다. 이 방법으로 생성되는 모든 단일 User 객체에 대해 생성되지는 않지만 반드시 그렇게 할 필요는 없습니다. 또한 앱 모델간에 코드를 공유 하기 위해 my_logger
메소드를 ActiveRecord::Base
클래스에 직접 주입 하거나 너무 많이 패치하고 싶지 않은 경우 자체 슈퍼 클래스에 주입 할 수 있습니다 .
최신 정보
아래의 솔루션을 기반으로 multi_logger 라는 보석을 만들었습니다 . 초기화 프로그램 에서이 작업을 수행하십시오.
MultiLogger.add_logger('post')
전화
Rails.logger.post.error('hi')
# or call logger.post.error('hi') if it is accessible.
그리고 당신은 끝났습니다.
직접 코딩하려면 아래를 참조하십시오.
보다 완벽한 해결책은 다음을 귀하 lib/
또는 config/initializers/
디렉토리 에 두는 것 입니다.
타임 스탬프 또는 심각도를 로그에 자동으로 지정하도록 포맷터를 설정할 수 있다는 이점이 있습니다. Rails의 어느 곳에서나 액세스 할 수 있으며 싱글 톤 패턴을 사용하여 깔끔하게 보입니다.
# Custom Post logger
require 'singleton'
class PostLogger < Logger
include Singleton
def initialize
super(Rails.root.join('log/post_error.log'))
self.formatter = formatter()
self
end
# Optional, but good for prefixing timestamps automatically
def formatter
Proc.new{|severity, time, progname, msg|
formatted_severity = sprintf("%-5s",severity.to_s)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
"[#{formatted_severity} #{formatted_time} #{$$}] #{msg.to_s.strip}\n"
}
end
class << self
delegate :error, :debug, :fatal, :info, :warn, :add, :log, :to => :instance
end
end
PostLogger.error('hi')
# [ERROR 2012-09-12 10:40:15] hi
나에게 맞는 괜찮은 옵션은 app/models
폴더에 상당히 평범한 클래스를 추가하는 것입니다.app/models/my_log.rb
class MyLog
def self.debug(message=nil)
@my_log ||= Logger.new("#{Rails.root}/log/my.log")
@my_log.debug(message) unless message.nil?
end
end
그런 다음 컨트롤러에서 또는 거의 모든 곳에서 Rails 앱 내에서 모델 클래스를 참조 할 수있는 거의 모든 곳, 예를 들어 수행 할 수있는 곳 Post.create(:title => "Hello world", :contents => "Lorum ipsum");
또는 이와 유사한 것으로 사용자 정의 파일에 로그 할 수 있습니다
MyLog.debug "Hello world"
Define a logger class in (say) app/models/special_log.rb:
class SpecialLog
LogFile = Rails.root.join('log', 'special.log')
class << self
cattr_accessor :logger
delegate :debug, :info, :warn, :error, :fatal, :to => :logger
end
end
initialize the logger in (say) config/initializers/special_log.rb:
SpecialLog.logger = Logger.new(SpecialLog::LogFile)
SpecialLog.logger.level = 'debug' # could be debug, info, warn, error or fatal
Anywhere in your app, you can log with:
SpecialLog.debug("something went wrong")
# or
SpecialLog.info("life is good")
Here is my custom logger:
class DebugLog
def self.debug(message=nil)
return unless Rails.env.development? and message.present?
@logger ||= Logger.new(File.join(Rails.root, 'log', 'debug.log'))
@logger.debug(message)
end
end
class Article < ActiveRecord::Base
LOGFILE = File.join(RAILS_ROOT, '/log/', "article_#{RAILS_ENV}.log")
def validate
log "was validated!"
end
def log(*args)
args.size == 1 ? (message = args; severity = :info) : (severity, message = args)
Article.logger severity, "Article##{self.id}: #{message}"
end
def self.logger(severity = nil, message = nil)
@article_logger ||= Article.open_log
if !severity.nil? && !message.nil? && @article_logger.respond_to?(severity)
@article_logger.send severity, "[#{Time.now.to_s(:db)}] [#{severity.to_s.capitalize}] #{message}\n"
end
message or @article_logger
end
def self.open_log
ActiveSupport::BufferedLogger.new(LOGFILE)
end
end
I would suggest using Log4r gem for custom logging. Quoting description from its page:
Log4r is a comprehensive and flexible logging library written in Ruby for use in Ruby programs. It features a hierarchical logging system of any number of levels, custom level names, logger inheritance, multiple output destinations per log event, execution tracing, custom formatting, thread safteyness, XML and YAML configuration, and more.
class Post < ActiveRecord::Base
def initialize(attributes)
super(attributes)
@logger = Logger.new("#{Rails.root}/log/post.log")
end
def logger
@logger
end
def some_method
logger.info('Test 1')
end
end
ps = Post.new
ps.some_method
ps.logger.info('Test 2')
Post.new.logger.info('Test 3')
The Logging framework, with its deceptively simple name, has the sophistication you crave!
Follow the very short instructions of logging-rails to get started filtering out noise, getting alerts, and choosing output in a fine-grained and high-level way.
Pat yourself on the back when you are done. Log-rolling, daily. Worth it for that alone.
참고URL : https://stackoverflow.com/questions/337739/how-to-log-something-in-rails-in-an-independent-log-file
'IT' 카테고리의 다른 글
특정 https 원격에 대한 특정 자체 서명 서버 인증서를 수락하도록 Git 구성 (0) | 2020.06.15 |
---|---|
내용과 정확히 일치하는 요소를 선택하십시오. (0) | 2020.06.15 |
Chrome 확장 프로그램 : 콘텐츠 스크립트에서 localStorage에 액세스 (0) | 2020.06.15 |
ECMAScript 6에는 추상 클래스에 대한 규칙이 있습니까? (0) | 2020.06.15 |
마우스 "클릭"과 "끌기"를 구별하는 방법 (0) | 2020.06.15 |