Class: SemanticLogger::Appender::Http
- Inherits:
-
Subscriber
- Object
- Base
- Subscriber
- SemanticLogger::Appender::Http
- Defined in:
- lib/semantic_logger/appender/http.rb
Direct Known Subclasses
Defined Under Namespace
Classes: ResponseError
Constant Summary collapse
- MAX_LOGGED_RESPONSE_BODY =
Maximum number of bytes of an error response body to write to the internal logger.
512- URL_FORMAT_HINT =
Describes a valid url in the error raised for an invalid one.
"Should be similar to: 'http://hostname:port/path'".freeze
- NOT_SENT_ERRORS =
The errors raised when the appender cannot connect to the server, so that the request was never sent: the server's name does not resolve, it cannot be reached, or it does not accept the connection, refusing it or within the open_timeout. Once connected, an error such as a read timeout or a reset connection may come after the server took the request.
[ SocketError, Net::OpenTimeout, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::EADDRNOTAVAIL ].freeze
Constants inherited from Subscriber
Instance Attribute Summary collapse
-
#compress ⇒ Object
Returns the value of attribute compress.
-
#continue_timeout ⇒ Object
Returns the value of attribute continue_timeout.
-
#header ⇒ Object
Returns the value of attribute header.
-
#http ⇒ Object
readonly
Returns the value of attribute http.
-
#open_timeout ⇒ Object
Returns the value of attribute open_timeout.
-
#path ⇒ Object
readonly
Returns the value of attribute path.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
-
#proxy_url ⇒ Object
readonly
Returns the value of attribute proxy_url.
-
#query ⇒ Object
readonly
Returns the value of attribute query.
-
#read_timeout ⇒ Object
Returns the value of attribute read_timeout.
-
#server ⇒ Object
readonly
Returns the value of attribute server.
-
#ssl_options ⇒ Object
readonly
Returns the value of attribute ssl_options.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
-
#username ⇒ Object
Returns the value of attribute username.
Attributes inherited from Subscriber
#application, #environment, #formatter, #host, #logger, #metrics
Instance Method Summary collapse
-
#batch(logs) ⇒ Object
Forward a batch of log messages to the HTTP Server in a single request.
-
#batch_all_or_nothing? ⇒ Boolean
The whole batch is formatted into a single request before anything is sent, and the server answers for the request as a whole.
-
#batch_by_default? ⇒ Boolean
The HTTP appender supports batching, but only when explicitly requested via
batch: true, so that the default behaviour (one request per log message) is preserved. -
#batch_refusal ⇒ Object
The #batch above formats the whole batch with #format_batch, so it needs a formatter that can format a batch, such as the default one, rather than a formatter block.
-
#close ⇒ Object
Closes the connection, if it is open, such as when the appender is removed, or add_appender fails to add it.
-
#fails_any_batch?(exception) ⇒ Boolean
Whether the exception, a message error, would fail any batch, whatever entries it holds (see Subscriber#fails_any_batch?): the server rejected the request (see ResponseError#rejected?) other than for the entries it holds (see ResponseError#content_rejected?), such as for its credentials or its url, and would reject every part of the batch too.
-
#initialize(url:, compress: false, ssl: {}, username: nil, password: nil, header: {}, proxy_url: :ENV, open_timeout: 2.0, read_timeout: 1.0, continue_timeout: 1.0, **args) ⇒ Http
constructor
Create HTTP(S) log appender.
-
#inspect_details ⇒ Object
Only the redacted url, since the instance variables hold the password, the authorization headers, and any credential a subclass adds.
-
#log(log) ⇒ Object
Forward log messages to HTTP Server.
-
#message_error?(exception) ⇒ Boolean
Whether the exception, raised by #log or #batch, was caused by the entries sent, rather than by the destination (see Subscriber#message_error?).
-
#not_sent?(exception) ⇒ Boolean
Whether the request that raised the exception from #log or #batch was never sent, because the appender could not connect (see NOT_SENT_ERRORS), so that the server has not answered it (see Subscriber#not_sent?).
-
#redacted_url ⇒ Object
Returns [String] the scheme, host, and any non-default port of the url.
-
#reopen ⇒ Object
Closes the connection, if it is open, and starts a new one, such as after a log rotation, or a fork.
-
#wrote_nothing?(exception) ⇒ Boolean
Whether the request that raised the exception from #log or #batch stored none of its entries, and is worth sending again later (see Subscriber#wrote_nothing?): the server asked to send it again later (see ResponseError#retry_later?), or it was never sent (see #not_sent?).
Methods inherited from Subscriber
#console_output?, #console_stream, #flush, #inspect, #rejected_entry, #should_log?
Constructor Details
#initialize(url:, compress: false, ssl: {}, username: nil, password: nil, header: {}, proxy_url: :ENV, open_timeout: 2.0, read_timeout: 1.0, continue_timeout: 1.0, **args) ⇒ Http
Create HTTP(S) log appender
Parameters:
url: [String]
Valid URL to post to.
Example: http://example.com/some_path
To enable SSL include https in the URL.
Example: https://example.com/some_path
verify_mode will default: OpenSSL::SSL::VERIFY_PEER
A query string is kept and sent with every request that submits log data,
for the log servers that are configured through it.
Example: http://example.com/some_path?source=my_app
application: [String]
Name of this application to appear in log messages.
Default: SemanticLogger.application
host: [String]
Name of this host to appear in log messages.
Default: SemanticLogger.host
username: [String]
User name for basic Authentication.
Default: nil ( do not use basic auth )
password: [String]
Password for basic Authentication.
header: [Hash]
Custom HTTP headers to send with each request. Each one replaces the default header of the
same name, compared in any case, such as "content-type" for Content-Type. A header set later
through #header, or written to it directly by a subclass, is not compared in any case.
Default: {} ( do not send any custom headers)
Example: {"Authorization" => "Bearer BEARER_TOKEN"}
compress: [true|false]
Whether to compress the JSON string with GZip.
Default: false
ssl: [Hash]
Specific SSL options: For more details see NET::HTTP.start
ca_file, ca_path, cert, cert_store, ciphers, key, ssl_timeout,
ssl_version, verify_callback, verify_depth and verify_mode.
proxy_url: [String]
URL of proxy server to use for HTTP(s) connections. Should
include username and password if required.
Example: http://user@pass:example.com/some_path
To enable SSL include https in the URL.
Example: https://example.com/some_path
If this is set to :ENV, Net::HTTP will use the environment http_proxy*
variables if they are set. If set to nil then no proxy will be used,
even if the environment variables are set.
level: [:trace | :debug | :info | :warn | :error | :fatal]
Override the log level for this appender.
Default: none (:trace), so it writes every entry that a logger emits; each logger
filters by its own level.
formatter: [Object|Proc]
An instance of a class that implements #call, or a Proc to be used to format
the output from this appender
Default: SemanticLogger::Formatters::Json
filter: [Regexp|Proc]
RegExp: Only include log messages where the class name matches the supplied.
regular expression. All other messages will be ignored.
Proc: Only include log messages where the supplied Proc returns true
The Proc must return true or false.
open_timeout: [Float]
Default: 2.0
read_timeout: [Float]
Default: 1.0
continue_timeout: [Float]
Default: 1.0
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/semantic_logger/appender/http.rb', line 191 def initialize(url:, compress: false, ssl: {}, username: nil, password: nil, header: {}, proxy_url: :ENV, open_timeout: 2.0, read_timeout: 1.0, continue_timeout: 1.0, **args, &) @url = url @proxy_url = proxy_url # A copy, to which an https url adds use_ssl: and verify_mode: (see Subscriber#copy_options). @ssl_options = ssl && (ssl) @username = username @password = password @compress = compress @open_timeout = open_timeout @read_timeout = read_timeout @continue_timeout = continue_timeout # On Ruby v2.0 and greater, Net::HTTP.new already uses a persistent connection if the server allows it @header = { "Accept" => "application/json", "Content-Type" => "application/json", "Connection" => "keep-alive", "Keep-Alive" => "300" } header&.each { |name, value| replace_header(name, value) } replace_header("Content-Encoding", "gzip") if @compress uri = parse_url(@url) @server = uri.host # The url is left out of the message, since it can hold a user and password. raise(ArgumentError, "Invalid format for :url, it has no host. #{URL_FORMAT_HINT}") unless @server @port = uri.port @username = uri.user if !@username && uri.user @password = uri.password if !@password && uri.password @path = uri.path # Path cannot be empty @path = "/" if @path == "" # Query string of the url, applied to every request, see #uri_with_query. # Kept separate from the path, because subclasses build their own request paths # from it. For example Appender::ElasticsearchHttp appends the index name. @query = uri.query @query = nil if @query == "" if uri.scheme == "https" @ssl_options[:use_ssl] = true @ssl_options[:verify_mode] ||= OpenSSL::SSL::VERIFY_PEER @port ||= HTTP.https_default_port else @port ||= HTTP.http_default_port end @proxy_uri = Utils.parse_url(@proxy_url, option: ":proxy_url") if @proxy_url && @proxy_url != :ENV @http = nil super(**args, &) reopen end |
Instance Attribute Details
#compress ⇒ Object
Returns the value of attribute compress.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def compress @compress end |
#continue_timeout ⇒ Object
Returns the value of attribute continue_timeout.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def continue_timeout @continue_timeout end |
#header ⇒ Object
Returns the value of attribute header.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def header @header end |
#http ⇒ Object (readonly)
Returns the value of attribute http.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def http @http end |
#open_timeout ⇒ Object
Returns the value of attribute open_timeout.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def open_timeout @open_timeout end |
#path ⇒ Object (readonly)
Returns the value of attribute path.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def path @path end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def port @port end |
#proxy_url ⇒ Object (readonly)
Returns the value of attribute proxy_url.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def proxy_url @proxy_url end |
#query ⇒ Object (readonly)
Returns the value of attribute query.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def query @query end |
#read_timeout ⇒ Object
Returns the value of attribute read_timeout.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def read_timeout @read_timeout end |
#server ⇒ Object (readonly)
Returns the value of attribute server.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def server @server end |
#ssl_options ⇒ Object (readonly)
Returns the value of attribute ssl_options.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def @ssl_options end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
46 47 48 |
# File 'lib/semantic_logger/appender/http.rb', line 46 def url @url end |
#username ⇒ Object
Returns the value of attribute username.
44 45 46 |
# File 'lib/semantic_logger/appender/http.rb', line 44 def username @username end |
Instance Method Details
#batch(logs) ⇒ Object
Forward a batch of log messages to the HTTP Server in a single request.
Only used when the appender is created with batch: true.
291 292 293 294 295 |
# File 'lib/semantic_logger/appender/http.rb', line 291 def batch(logs) = format_batch(logs) logger.trace() post() end |
#batch_all_or_nothing? ⇒ Boolean
The whole batch is formatted into a single request before anything is sent, and the server answers for the request as a whole. So a batch that a format error or a rejected request fails (see #message_error?) is split up and sent again, to find the entries at fault.
308 309 310 |
# File 'lib/semantic_logger/appender/http.rb', line 308 def batch_all_or_nothing? true end |
#batch_by_default? ⇒ Boolean
The HTTP appender supports batching, but only when explicitly requested
via batch: true, so that the default behaviour (one request per log
message) is preserved.
300 301 302 |
# File 'lib/semantic_logger/appender/http.rb', line 300 def batch_by_default? false end |
#batch_refusal ⇒ Object
The #batch above formats the whole batch with #format_batch, so it needs a formatter that can format a batch, such as the default one, rather than a formatter block. See Subscriber#batch_refusal.
Answers only while that #batch is the one in use (see Subscriber#batch_defined_by?). A subclass that replaces it answers for its own, as Loki and Signalfx do, and is otherwise batched with any formatter, as before, such as one whose #batch formats each log message with #format_log. One whose #batch calls super, or that a prepended module wraps, still formats the whole batch with #format_batch, so it defines its own #batch_refusal, which returns #format_batch_refusal, as the Custom appenders section of docs/config.md shows.
322 323 324 |
# File 'lib/semantic_logger/appender/http.rb', line 322 def batch_refusal format_batch_refusal if batch_defined_by?(Http) end |
#close ⇒ Object
Closes the connection, if it is open, such as when the appender is removed, or add_appender fails to add it. The next request opens it again, see #process_request.
In a forked child that has not reopened, such as one that removes the appender before its reopen has run, it forgets the connection it inherited instead, without finishing it, since it belongs to the parent (see #reopen), and the next request starts a new one.
278 279 280 |
# File 'lib/semantic_logger/appender/http.rb', line 278 def close finish_connection end |
#fails_any_batch?(exception) ⇒ Boolean
Whether the exception, a message error, would fail any batch, whatever entries it holds (see Subscriber#fails_any_batch?): the server rejected the request (see ResponseError#rejected?) other than for the entries it holds (see ResponseError#content_rejected?), such as for its credentials or its url, and would reject every part of the batch too. So the batch is discarded at once, rather than split up. A batch that could not be formatted, or that the server rejected for its entries, is split up to find the entries at fault.
339 340 341 |
# File 'lib/semantic_logger/appender/http.rb', line 339 def fails_any_batch?(exception) exception.is_a?(ResponseError) && exception.rejected? && !exception.content_rejected? end |
#inspect_details ⇒ Object
Only the redacted url, since the instance variables hold the password, the authorization headers, and any credential a subclass adds. See Subscriber#inspect.
379 380 381 |
# File 'lib/semantic_logger/appender/http.rb', line 379 def inspect_details "url=#{redacted_url.inspect}" end |
#log(log) ⇒ Object
Forward log messages to HTTP Server
283 284 285 286 287 |
# File 'lib/semantic_logger/appender/http.rb', line 283 def log(log) = format_log(log) logger.trace() post() end |
#message_error?(exception) ⇒ Boolean
Whether the exception, raised by #log or #batch, was caused by the entries sent, rather than by the destination (see Subscriber#message_error?). That includes a request the server rejected (see ResponseError#rejected?), since sending it again cannot succeed.
329 330 331 |
# File 'lib/semantic_logger/appender/http.rb', line 329 def (exception) (exception.is_a?(ResponseError) && exception.rejected?) || super end |
#not_sent?(exception) ⇒ Boolean
Whether the request that raised the exception from #log or #batch was never sent, because the appender could not connect (see NOT_SENT_ERRORS), so that the server has not answered it (see Subscriber#not_sent?). An asynchronous appender then sends the entries again without counting it towards QueueProcessor::HeldWrite::MAX_RESENDS, so that an outage loses none of them until the worker thread gives up after async_max_retries. Decided from the class of the exception alone, as for #wrote_nothing?.
367 368 369 |
# File 'lib/semantic_logger/appender/http.rb', line 367 def not_sent?(exception) NOT_SENT_ERRORS.any? { |error_class| exception.is_a?(error_class) } end |
#redacted_url ⇒ Object
Returns [String] the scheme, host, and any non-default port of the url. Safe to log. See Utils.redacted_url.
373 374 375 |
# File 'lib/semantic_logger/appender/http.rb', line 373 def redacted_url @redacted_url ||= Utils.redacted_url(url) end |
#reopen ⇒ Object
Closes the connection, if it is open, and starts a new one, such as after a log rotation, or a fork. When starting it fails, such as while the server cannot be reached, it raises, and the next request starts it (see #process_request).
After a fork, the child first forgets the connection it inherited, without finishing it: it belongs to the parent. Finishing an https connection sends the server a TLS close_notify, which ends the connection for the parent too. Ruby closes the child's copy of the socket when it collects it, which leaves the parent's open. Net::HTTP keeps its socket to itself, so until then the child holds that copy open, and over plain http the server does not see the connection end when the parent closes it.
267 268 269 270 |
# File 'lib/semantic_logger/appender/http.rb', line 267 def reopen finish_connection build_http.start end |
#wrote_nothing?(exception) ⇒ Boolean
Whether the request that raised the exception from #log or #batch stored none of its entries, and is worth sending again later (see Subscriber#wrote_nothing?): the server asked to send it again later (see ResponseError#retry_later?), or it was never sent (see #not_sent?). So an asynchronous appender sends the entries again once it has backed off.
Decided from the class of the exception alone. Its cause, which Ruby sets to the error being handled when it was raised, such as a format error while a batch is split, says nothing about this request; #process_request raises the error of the request, not one from reconnecting.
A subclass whose #log or #batch sends more than one request must override this to return false: a failure of a later request would otherwise have the entries of the earlier ones, which the server stored, sent again.
355 356 357 358 359 |
# File 'lib/semantic_logger/appender/http.rb', line 355 def wrote_nothing?(exception) return exception.retry_later? if exception.is_a?(ResponseError) not_sent?(exception) end |