-
Notifications
You must be signed in to change notification settings - Fork 321
Logging and Instrumentation
zp yuan edited this page Nov 15, 2022
·
6 revisions
To write requests and responses to a logger, use
the Logging feature:
logger = Logger.new(STDOUT)
http = HTTP.use(logging: {logger: logger})
http.get("https://httpbin.org/get")
# I, [2018-08-16T16:33:58.261195 #1538] INFO -- : > GET https://httpbin.org/get
# I, [2018-08-16T16:33:58.487195 #1538] INFO -- : < 200 OK
Logging at the DEBUG level will log the full request & response headers and bodies.
To enable it for all requests by default use default_options
HTTP.default_options = HTTP::Options.new(features: {
logging: {
logger: Logger.new(STDOUT)
}
})
For more advanced logging, or instrumentation in general, use
the Instrumentation feature. It expects an ActiveSupport::Notifications-compatible instrumenter.
ActiveSupport::Notifications.subscribe('start_request.http') do |name, start, finish, id, payload|
pp :name => name, :start => start.to_f, :finish => finish.to_f, :id => id, :payload => payload
end
http = HTTP.use(instrumentation: { instrumenter: ActiveSupport::Notifications.instrumenter })
http.get("https://httpbin.org/get")
# => {name: .., start: .., finish: .., id: .., payload: ..}
You can customize the "namespace" used by the instrumenter:
HTTP.use(instrumentation: { instrumenter: ActiveSupport::Notifications.instrumenter, namespace: "my_http" })
# Will emits a "request.my_http" event on requests.
http.rb also supports defining custom features.
In order to register your own custom feature implementation, implement HTTP::Feature
, and then register it with the HTTP library:
HTTP::Options.register_feature(:my_feature, MyFeature)
You can then use it on a client via:
http = HTTP.use(:my_feature)