Class: Google::Cloud::Logging::Logger

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

Overview

Logger

An API-compatible replacement for ruby's Logger that logs to the Stackdriver Logging Service.

Examples:

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

resource = logging.resource "gae_app",
                            module_id: "1",
                            version_id: "20150925t173233"

logger = logging.logger "my_app_log", resource, env: :production
logger.info "Job started."

Provide a hash to write a JSON payload to the log:

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

resource = logging.resource "gae_app",
                            module_id: "1",
                            version_id: "20150925t173233"

logger = logging.logger "my_app_log", resource, env: :production

payload = { "stats" => { "a" => 8, "b" => 12.5} }
logger.info payload

Defined Under Namespace

Classes: RequestInfo

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(writer, log_name, resource, labels = nil) ⇒ Google::Cloud::Logging::Logger

Create a new Logger instance.

Examples:

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

writer = logging.async_writer max_queue_size: 1000

resource = logging.resource "gae_app", labels: {
                              "module_id" => "1",
                              "version_id" => "20150925t173233"
                            }

logger = Google::Cloud::Logging::Logger.new writer,
                                            "my_app_log",
                                            resource,
                                            env: :production
logger.info "Job started."

Parameters:

  • writer (#write_entries)

    The object that will transmit log entries. Generally, to create a logger that blocks on transmitting log entries, pass the Project; otherwise, to create a logger that transmits log entries in the background, pass an AsyncWriter. You may also pass any other object that responds to #write_entries.

  • log_name (String)

    A log resource name to be associated with the written log entries.

  • resource (Google::Cloud::Logging::Resource)

    The monitored resource to be associated with written log entries.

  • labels (Hash) (defaults to: nil)

    A set of user-defined data to be associated with written log entries.



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/google/cloud/logging/logger.rb', line 163

def initialize writer, log_name, resource, labels = nil
  @writer = writer
  @log_name = log_name
  @resource = resource
  @labels = labels || {}
  @level = 0 # DEBUG is the default behavior
  @request_info = {}
  @closed = false
  # Unused, but present for API compatibility
  @formatter = ::Logger::Formatter.new
  @datetime_format = ""
  @silencer = true

  # The writer is usually a Project or AsyncWriter.
  logging = @writer.respond_to?(:logging) ? @writer.logging : @writer
  @project = logging.project if logging.respond_to? :project
end

Instance Attribute Details

#datetime_formatObject

This logger does not use a formatter, but it implements this attribute for API compatibility with the standard Logger.



103
104
105
# File 'lib/google/cloud/logging/logger.rb', line 103

def datetime_format
  @datetime_format
end

#formatterObject

This logger does not use a formatter, but it provides a default Logger::Formatter for API compatibility with the standard Logger.



98
99
100
# File 'lib/google/cloud/logging/logger.rb', line 98

def formatter
  @formatter
end

#labelsObject (readonly)

The Google Cloud labels to write the log entry with.



82
83
84
# File 'lib/google/cloud/logging/logger.rb', line 82

def labels
  @labels
end

#levelObject Also known as: sev_threshold, local_level

The logging severity threshold (e.g. Logger::INFO)



86
87
88
# File 'lib/google/cloud/logging/logger.rb', line 86

def level
  @level
end

#log_nameObject (readonly) Also known as: progname

The Google Cloud log_name to write the log entry with.



73
74
75
# File 'lib/google/cloud/logging/logger.rb', line 73

def log_name
  @log_name
end

#projectObject

The project ID this logger is sending data to. If set, this value is used to set the trace field of log entries.



108
109
110
# File 'lib/google/cloud/logging/logger.rb', line 108

def project
  @project
end

#resourceObject (readonly)

The Google Cloud resource to write the log entry with.



78
79
80
# File 'lib/google/cloud/logging/logger.rb', line 78

def resource
  @resource
end

#silencerObject

Boolean flag that indicates whether this logger can be silenced or not.



93
94
95
# File 'lib/google/cloud/logging/logger.rb', line 93

def silencer
  @silencer
end

#writerObject (readonly)

The Google Cloud writer object that calls to #write_entries are made on. Either an AsyncWriter or Project object.



69
70
71
# File 'lib/google/cloud/logging/logger.rb', line 69

def writer
  @writer
end

Instance Method Details

#<<(msg) ⇒ Object

Logs the given message at UNKNOWN severity.

Parameters:

  • msg (String)

    The log entry payload as a string.



327
328
329
330
# File 'lib/google/cloud/logging/logger.rb', line 327

def << msg
  unknown msg
  self
end

#add(severity, message = nil, progname = nil) { ... } ⇒ Object Also known as: log

Log a message if the given severity is high enough. This is the generic logging method. Users will be more inclined to use #debug, #info, #warn, #error, and #fatal.

Parameters:

  • severity (Integer, String, Symbol)

    the integer code for or the name of the severity level

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/google/cloud/logging/logger.rb', line 304

def add severity, message = nil, progname = nil
  severity = derive_severity(severity) || ::Logger::UNKNOWN
  return true if severity < @level

  if message.nil?
    if block_given?
      message = yield
    else
      message = progname
      # progname = nil # TODO: Figure out what to do with the progname
    end
  end

  write_entry severity, message unless @closed
  true
end

#add_request_info(info: nil, env: nil, trace_id: nil, log_name: nil) ⇒ Object

Associate request data with the current Thread. You may provide either the individual pieces of data (trace ID, log name) or a populated RequestInfo object.

Parameters:

  • info (RequestInfo)

    Info about the current request. Optional. If not present, a new RequestInfo is created using the remaining parameters.

  • trace_id (String, nil)

    The trace ID, or nil if no trace ID should be logged.

  • log_name (String, nil)

    The log name to use, or nil to use this logger's default.

  • env (Hash, nil)

    The request's Rack environment or nil if not available.



449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/google/cloud/logging/logger.rb', line 449

def add_request_info info: nil,
                     env: nil,
                     trace_id: nil,
                     log_name: nil
  info ||= RequestInfo.new trace_id, log_name, env
  @request_info[current_thread_id] = info

  # Start removing old entries if hash gets too large.
  # This should never happen, because middleware should automatically
  # remove entries when a request is finished
  @request_info.shift while @request_info.size > 10_000

  info
end

#add_trace_id(trace_id) ⇒ Object

Deprecated.

Use add_request_info

Track a given trace_id by associating it with the current Thread



430
431
432
# File 'lib/google/cloud/logging/logger.rb', line 430

def add_trace_id trace_id
  add_request_id trace_id: trace_id
end

#closeObject

Close the logging "device". This effectively disables logging from this logger; any further log messages will be silently ignored. The logger may be re-enabled by calling #reopen.



407
408
409
410
# File 'lib/google/cloud/logging/logger.rb', line 407

def close
  @closed = true
  self
end

#debug(message = nil) { ... } ⇒ Object

Log a DEBUG entry.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



191
192
193
194
195
196
197
# File 'lib/google/cloud/logging/logger.rb', line 191

def debug message = nil, &block
  if block_given?
    add ::Logger::DEBUG, nil, message, &block
  else
    add ::Logger::DEBUG, message
  end
end

#debug?Boolean

Returns true if the current severity level allows for sending DEBUG messages.

Returns:

  • (Boolean)


335
336
337
# File 'lib/google/cloud/logging/logger.rb', line 335

def debug?
  @level <= ::Logger::DEBUG
end

#delete_request_infoRequestInfo Also known as: delete_trace_id

Untrack the RequestInfo that's associated with current Thread

Returns:



479
480
481
# File 'lib/google/cloud/logging/logger.rb', line 479

def delete_request_info
  @request_info.delete current_thread_id
end

#error(message = nil) { ... } ⇒ Object

Log an ERROR entry.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



245
246
247
248
249
250
251
# File 'lib/google/cloud/logging/logger.rb', line 245

def error message = nil, &block
  if block_given?
    add ::Logger::ERROR, nil, message, &block
  else
    add ::Logger::ERROR, message
  end
end

#error?Boolean

Returns true if the current severity level allows for sending ERROR messages.

Returns:

  • (Boolean)


356
357
358
# File 'lib/google/cloud/logging/logger.rb', line 356

def error?
  @level <= ::Logger::ERROR
end

#fatal(message = nil) { ... } ⇒ Object

Log a FATAL entry.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



263
264
265
266
267
268
269
# File 'lib/google/cloud/logging/logger.rb', line 263

def fatal message = nil, &block
  if block_given?
    add ::Logger::FATAL, nil, message, &block
  else
    add ::Logger::FATAL, message
  end
end

#fatal?Boolean

Returns true if the current severity level allows for sending FATAL messages.

Returns:

  • (Boolean)


363
364
365
# File 'lib/google/cloud/logging/logger.rb', line 363

def fatal?
  @level <= ::Logger::FATAL
end

#flushObject

No-op method. Created to match the spec of ActiveSupport::Logger#flush method when used in Rails application.



490
491
492
# File 'lib/google/cloud/logging/logger.rb', line 490

def flush
  self
end

#info(message = nil) { ... } ⇒ Object

Log an INFO entry.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



209
210
211
212
213
214
215
# File 'lib/google/cloud/logging/logger.rb', line 209

def info message = nil, &block
  if block_given?
    add ::Logger::INFO, nil, message, &block
  else
    add ::Logger::INFO, message
  end
end

#info?Boolean

Returns true if the current severity level allows for sending INFO messages.

Returns:

  • (Boolean)


342
343
344
# File 'lib/google/cloud/logging/logger.rb', line 342

def info?
  @level <= ::Logger::INFO
end

#progname=(name) ⇒ Object

This logger treats progname as an alias for log_name.



112
113
114
# File 'lib/google/cloud/logging/logger.rb', line 112

def progname= name
  @log_name = name
end

#reopen(_logdev = nil) ⇒ Object

Re-enable logging if the logger has been closed.

Note that this method accepts a "logdev" argument for compatibility with the standard Ruby Logger class; however, this argument is ignored because this logger does not use a log device.



419
420
421
422
# File 'lib/google/cloud/logging/logger.rb', line 419

def reopen _logdev = nil
  @closed = false
  self
end

#request_infoRequestInfo?

Get the request data for the current Thread

Returns:

  • (RequestInfo, nil)

    The request data for the current thread, or nil if there is no data set.



470
471
472
# File 'lib/google/cloud/logging/logger.rb', line 470

def request_info
  @request_info[current_thread_id]
end

#silence(temp_level = ::Logger::ERROR) ⇒ Object

Filter out low severity messages within block.

Examples:

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

resource = logging.resource "gae_app",
                            module_id: "1",
                            version_id: "20150925t173233"

logger = logging.logger "my_app_log", resource, env: :production

logger.silence do
  logger.info "Info message"   # No log entry written
  logger.error "Error message" # Log entry written
end

Parameters:

  • temp_level (Integer) (defaults to: ::Logger::ERROR)

    Severity threshold to filter within the block. Messages with lower severity will be blocked. Default ::Logger::ERROR



516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/google/cloud/logging/logger.rb', line 516

def silence temp_level = ::Logger::ERROR
  if silencer
    begin
      old_level = level
      self.level = temp_level

      yield self
    ensure
      self.level = old_level
    end
  else
    yield self
  end
end

#trace_idsObject

Deprecated.

Use request_info

A Hash of Thread IDs to Stackdriver request trace ID. The Stackdriver trace ID is a shared request identifier across all Stackdriver services.



123
124
125
# File 'lib/google/cloud/logging/logger.rb', line 123

def trace_ids
  @request_info.inject({}) { |r, (k, v)| r[k] = v.trace_id }
end

#unknown(message = nil) { ... } ⇒ Object

Log an UNKNOWN entry. This will be printed no matter what the logger's current severity level is.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



282
283
284
285
286
287
288
# File 'lib/google/cloud/logging/logger.rb', line 282

def unknown message = nil, &block
  if block_given?
    add ::Logger::UNKNOWN, nil, message, &block
  else
    add ::Logger::UNKNOWN, message
  end
end

#unknown?Boolean

Returns true if the current severity level allows for sending UNKNOWN messages.

Returns:

  • (Boolean)


370
371
372
# File 'lib/google/cloud/logging/logger.rb', line 370

def unknown?
  @level <= ::Logger::UNKNOWN
end

#warn(message = nil) { ... } ⇒ Object

Log a WARN entry.

Parameters:

  • message (String, Hash) (defaults to: nil)

    The log entry payload, represented as either a string, a hash (JSON), or a hash (protocol buffer).

Yields:

  • Evaluates to the message to log. This is not evaluated unless the logger's level is sufficient to log the message. This allows you to create potentially expensive logging messages that are only called when the logger is configured to show them.



227
228
229
230
231
232
233
# File 'lib/google/cloud/logging/logger.rb', line 227

def warn message = nil, &block
  if block_given?
    add ::Logger::WARN, nil, message, &block
  else
    add ::Logger::WARN, message
  end
end

#warn?Boolean

Returns true if the current severity level allows for sending WARN messages.

Returns:

  • (Boolean)


349
350
351
# File 'lib/google/cloud/logging/logger.rb', line 349

def warn?
  @level <= ::Logger::WARN
end