Class: Google::Cloud::Logging::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/logging/middleware.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, logger: nil) ⇒ Google::Cloud::Logging::Middleware

Create a new AppEngine logging Middleware.

Parameters:

  • app

    Rack application

  • logger (Google::Cloud::Logging::Logger)

    A logger to be used by this middleware. The middleware will be interacting with the logger to track Stackdriver request trace ID. It also properly sets env["rack.logger"] to this assigned logger for accessing.



37
38
39
40
# File 'lib/google/cloud/logging/middleware.rb', line 37

def initialize app, logger: nil
  @app = app
  @logger = logger
end

Instance Attribute Details

#loggerObject (readonly)

The Google::Cloud::Logging::Logger instance



22
23
24
# File 'lib/google/cloud/logging/middleware.rb', line 22

def logger
  @logger
end

Instance Method Details

#call(env) ⇒ Object

Rack middleware entry point. In most Rack based frameworks, a request is served by one thread. So entry point, we associate the GCP request trace_id with the current thread's object_id in logger. All the logs written by logger beyond this point will carry this request's trace_id. Untrack the trace_id with this thread upon exiting.

Parameters:

  • env (Hash)

    Rack environment hash

Returns:

  • The response from downstream Rack app



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/google/cloud/logging/middleware.rb', line 53

def call env
  env["rack.logger"] = logger
  trace_id = extract_trace_id(env)
  logger.add_trace_id trace_id

  begin
    @app.call env
  ensure
    logger.delete_trace_id
  end
end

#extract_trace_id(env) ⇒ String

Extract the trace_id from HTTP request header HTTP_X_CLOUD_TRACE_CONTEXT.

Returns:

  • (String)

    The trace_id or nil if trace_id is empty.



70
71
72
73
74
# File 'lib/google/cloud/logging/middleware.rb', line 70

def extract_trace_id env
  trace_context = env["HTTP_X_CLOUD_TRACE_CONTEXT"].to_s
  return nil if trace_context.empty?
  trace_context.sub(%r{/.*}, "")
end