Active Support Log Subscriber
ActiveSupport::LogSubscriber
是一個用於使用 ActiveSupport::Notifications
的物件設定,其唯一目的是記錄通知事件。日誌訂閱者會根據其指定的命名空間將通知事件派送至已註冊的物件。
其中一個範例是 ActiveRecord 日誌訂閱者,其負責記錄查詢
module ActiveRecord
class LogSubscriber < ActiveSupport::LogSubscriber
attach_to :active_record
def sql(event)
info "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
end
end
end
ActiveRecord::LogSubscriber.logger
也必須設定,不過會在 Rails 環境中自動指定。
設定完成後,每當公開發布 "sql.active_record"
通知事件時,它會適當地將事件 (ActiveSupport::Notifications::Event
) 派送至 sql
方法。
由於是 ActiveSupport::Notifications
的消費者,ActiveSupport::LogSubscriber
公開了一個簡單的介面,可檢查有監測碼是否引发例外。在發生錯誤時通常會記錄一則不同的訊息,這可以在延伸上一個範例時達成
module ActiveRecord
class LogSubscriber < ActiveSupport::LogSubscriber
def sql(event)
exception = event.payload[:exception]
if exception
exception_object = event.payload[:exception_object]
error "[ERROR] #{event.payload[:name]}: #{exception.join(', ')} " \
"(#{exception_object.backtrace.first})"
else
# standard logger code
end
end
end
end
ActiveSupport::LogSubscriber
也有一些處理日誌記錄的輔助程式。例如,ActiveSupport::LogSubscriber.flush_all!
會確保所有日誌已沖刷,而它會在完成請求後 Rails::Rack::Logger
中呼叫。
- C
- F
- L
- N
- P
- S
常數
BLACK | = | "\e[30m" |
ANSI 序列顏色 |
||
BLUE | = | "\e[34m" |
CYAN | = | "\e[36m" |
GREEN | = | "\e[32m" |
LEVEL_CHECKS | = | { debug: -> (logger) { !logger.debug? }, info: -> (logger) { !logger.info? }, error: -> (logger) { !logger.error? }, } |
MAGENTA | = | "\e[35m" |
MODES | = | { clear: 0, bold: 1, italic: 3, underline: 4, } |
ANSI 序列模式 |
||
RED | = | "\e[31m" |
WHITE | = | "\e[37m" |
YELLOW | = | "\e[33m" |
屬性
[W] | logger |
類別公開方法
flush_all!() 連結
沖刷所有 log_subscribers
的記錄器。
log_subscribers() 連結
logger() 連結
new() 連結
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 133 def initialize super @event_levels = {} end
執行個體公有方法
call(event) 連結
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 146 def call(event) super if logger rescue => e log_exception(event.name, e) end
logger() 連結
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 138 def logger LogSubscriber.logger end
publish_event(event) 連結
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 152 def publish_event(event) super if logger rescue => e log_exception(event.name, e) end
silenced?(event) 連結
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 142 def silenced?(event) logger.nil? || @event_levels[event]&.call(logger) end
執行個體私有方法
color(text, color, mode_options = {}) 連結
使用符號或定義好的常數來設定顏色。透過指定粗體、斜體或底線選項來設定模式。受到 Highline 啟發,這個方法會自動清除回傳 字串
結尾的格式。
來源:顯示 | 在 GitHub 上
# File activesupport/lib/active_support/log_subscriber.rb, line 172 def color(text, color, mode_options = {}) # :doc: return text unless colorize_logging color = self.class.const_get(color.upcase) if color.is_a?(Symbol) mode = mode_from(mode_options) clear = "\e[#{MODES[:clear]}m" "#{mode}#{color}#{text}#{clear}" end