logging

package
v0.33.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2018 License: Apache-2.0 Imports: 23 Imported by: 842

Documentation

Overview

Package logging contains a Stackdriver Logging client suitable for writing logs. For reading logs, and working with sinks, metrics and monitored resources, see package cloud.google.com/go/logging/logadmin.

This client uses Logging API v2. See https://cloud.google.com/logging/docs/api/v2/ for an introduction to the API.

Note: This package is in beta. Some backwards-incompatible changes may occur.

Creating a Client

Use a Client to interact with the Stackdriver Logging API.

// Create a Client
ctx := context.Background()
client, err := logging.NewClient(ctx, "my-project")
if err != nil {
	// TODO: Handle error.
}

Basic Usage

For most use cases, you'll want to add log entries to a buffer to be periodically flushed (automatically and asynchronously) to the Stackdriver Logging service.

// Initialize a logger
lg := client.Logger("my-log")

// Add entry to log buffer
lg.Log(logging.Entry{Payload: "something happened!"})

Closing your Client

You should call Client.Close before your program exits to flush any buffered log entries to the Stackdriver Logging service.

// Close the client when finished.
err = client.Close()
if err != nil {
	// TODO: Handle error.
}

Synchronous Logging

For critical errors, you may want to send your log entries immediately. LogSync is slow and will block until the log entry has been sent, so it is not recommended for normal use.

lg.LogSync(ctx, logging.Entry{Payload: "ALERT! Something critical happened!"})

Payloads

An entry payload can be a string, as in the examples above. It can also be any value that can be marshaled to a JSON object, like a map[string]interface{} or a struct:

type MyEntry struct {
	Name  string
	Count int
}
lg.Log(logging.Entry{Payload: MyEntry{Name: "Bob", Count: 3}})

If you have a []byte of JSON, wrap it in json.RawMessage:

j := []byte(`{"Name": "Bob", "Count": 3}`)
lg.Log(logging.Entry{Payload: json.RawMessage(j)})

The Standard Logger Interface

You may want use a standard log.Logger in your program.

// stdlg implements log.Logger
stdlg := lg.StandardLogger(logging.Info)
stdlg.Println("some info")

Log Levels

An Entry may have one of a number of severity levels associated with it.

logging.Entry{
	Payload: "something terrible happened!",
	Severity: logging.Critical,
}

Viewing Logs

You can view Stackdriver logs for projects at https://console.cloud.google.com/logs/viewer. Use the dropdown at the top left. When running from a Google Cloud Platform VM, select "GCE VM Instance". Otherwise, select "Google Project" and then the project ID. Logs for organizations, folders and billing accounts can be viewed on the command line with the "gcloud logging read" command.

Grouping Logs by Request

To group all the log entries written during a single HTTP request, create two Loggers, a "parent" and a "child," with different log IDs. Both should be in the same project, and have the same MonitoredResouce type and labels.

- Parent entries must have HTTPRequest.Request populated. (Strictly speaking, only the URL is necessary.)

- A child entry's timestamp must be within the time interval covered by the parent request (i.e., older than parent.Timestamp, and newer than parent.Timestamp - parent.HTTPRequest.Latency, assuming the parent timestamp marks the end of the request.

- The trace field must be populated in all of the entries and match exactly.

You should observe the child log entries grouped under the parent on the console. The parent entry will not inherit the severity of its children; you must update the parent severity yourself.

Index

Examples

Constants

View Source
const (
	// ReadScope is the scope for reading from the logging service.
	ReadScope = "https://www.googleapis.com/auth/logging.read"

	// WriteScope is the scope for writing to the logging service.
	WriteScope = "https://www.googleapis.com/auth/logging.write"

	// AdminScope is the scope for administrative actions on the logging service.
	AdminScope = "https://www.googleapis.com/auth/logging.admin"
)
View Source
const (

	// DefaultDelayThreshold is the default value for the DelayThreshold LoggerOption.
	DefaultDelayThreshold = time.Second

	// DefaultEntryCountThreshold is the default value for the EntryCountThreshold LoggerOption.
	DefaultEntryCountThreshold = 1000

	// DefaultEntryByteThreshold is the default value for the EntryByteThreshold LoggerOption.
	DefaultEntryByteThreshold = 1 << 20 // 1MiB

	// DefaultBufferedByteLimit is the default value for the BufferedByteLimit LoggerOption.
	DefaultBufferedByteLimit = 1 << 30 // 1GiB

)
View Source
const (
	// Default means the log entry has no assigned severity level.
	Default = Severity(logtypepb.LogSeverity_DEFAULT)
	// Debug means debug or trace information.
	Debug = Severity(logtypepb.LogSeverity_DEBUG)
	// Info means routine information, such as ongoing status or performance.
	Info = Severity(logtypepb.LogSeverity_INFO)
	// Notice means normal but significant events, such as start up, shut down, or configuration.
	Notice = Severity(logtypepb.LogSeverity_NOTICE)
	// Warning means events that might cause problems.
	Warning = Severity(logtypepb.LogSeverity_WARNING)
	// Error means events that are likely to cause problems.
	Error = Severity(logtypepb.LogSeverity_ERROR)
	// Critical means events that cause more severe problems or brief outages.
	Critical = Severity(logtypepb.LogSeverity_CRITICAL)
	// Alert means a person must take an action immediately.
	Alert = Severity(logtypepb.LogSeverity_ALERT)
	// Emergency means one or more systems are unusable.
	Emergency = Severity(logtypepb.LogSeverity_EMERGENCY)
)

Variables

View Source
var ErrOverflow = bundler.ErrOverflow

ErrOverflow signals that the number of buffered entries for a Logger exceeds its BufferLimit.

View Source
var ErrOversizedEntry = bundler.ErrOversizedItem

ErrOversizedEntry signals that an entry's size exceeds the maximum number of bytes that will be sent in a single call to the logging service.

Functions

This section is empty.

Types

type Client

type Client struct {

	// OnError is called when an error occurs in a call to Log or Flush. The
	// error may be due to an invalid Entry, an overflow because BufferLimit
	// was reached (in which case the error will be ErrOverflow) or an error
	// communicating with the logging service. OnError is called with errors
	// from all Loggers. It is never called concurrently. OnError is expected
	// to return quickly; if errors occur while OnError is running, some may
	// not be reported. The default behavior is to call log.Printf.
	//
	// This field should be set only once, before any method of Client is called.
	OnError func(err error)
	// contains filtered or unexported fields
}

Client is a Logging client. A Client is associated with a single Cloud project.

func NewClient

func NewClient(ctx context.Context, parent string, opts ...option.ClientOption) (*Client, error)

NewClient returns a new logging client associated with the provided parent. A parent can take any of the following forms:

projects/PROJECT_ID
folders/FOLDER_ID
billingAccounts/ACCOUNT_ID
organizations/ORG_ID

for backwards compatibility, a string with no '/' is also allowed and is interpreted as a project ID.

By default NewClient uses WriteScope. To use a different scope, call NewClient using a WithScopes option (see https://godoc.org/google.golang.org/api/option#WithScopes).

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	// Use client to manage logs, metrics and sinks.
	// Close the client when finished.
	if err := client.Close(); err != nil {
		// TODO: Handle error.
	}
}
Output:

Example (ErrorFunc)

Although Logger.Flush and Client.Close both return errors, they don't tell you whether the errors were frequent or significant. For most programs, it doesn't matter if there were a few errors while writing logs, although if those few errors indicated a bug in your program, you might want to know about them. The best way to handle errors is by setting the OnError function. If it runs quickly, it will see every error generated during logging.

package main

import (
	"context"
	"fmt"
	"os"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	// Print all errors to stdout, and count them. Multiple calls to the OnError
	// function never happen concurrently, so there is no need for locking nErrs,
	// provided you don't read it until after the logging client is closed.
	var nErrs int
	client.OnError = func(e error) {
		fmt.Fprintf(os.Stdout, "logging: %v", e)
		nErrs++
	}
	// Use client to manage logs, metrics and sinks.
	// Close the client when finished.
	if err := client.Close(); err != nil {
		// TODO: Handle error.
	}
	fmt.Printf("saw %d errors\n", nErrs)
}
Output:

func (*Client) Close added in v0.2.0

func (c *Client) Close() error

Close waits for all opened loggers to be flushed and closes the client.

func (*Client) Logger

func (c *Client) Logger(logID string, opts ...LoggerOption) *Logger

Logger returns a Logger that will write entries with the given log ID, such as "syslog". A log ID must be less than 512 characters long and can only include the following characters: upper and lower case alphanumeric characters: [A-Za-z0-9]; and punctuation characters: forward-slash, underscore, hyphen, and period.

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	_ = lg // TODO: use the Logger.
}
Output:

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping reports whether the client's connection to the logging service and the authentication configuration are valid. To accomplish this, Ping writes a log entry "ping" to a log named "ping".

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	if err := client.Ping(ctx); err != nil {
		// TODO: Handle error.
	}
}
Output:

type Entry

type Entry struct {
	// Timestamp is the time of the entry. If zero, the current time is used.
	Timestamp time.Time

	// Severity is the entry's severity level.
	// The zero value is Default.
	Severity Severity

	// Payload must be either a string, or something that marshals via the
	// encoding/json package to a JSON object (and not any other type of JSON value).
	Payload interface{}

	// Labels optionally specifies key/value labels for the log entry.
	// The Logger.Log method takes ownership of this map. See Logger.CommonLabels
	// for more about labels.
	Labels map[string]string

	// InsertID is a unique ID for the log entry. If you provide this field,
	// the logging service considers other log entries in the same log with the
	// same ID as duplicates which can be removed. If omitted, the logging
	// service will generate a unique ID for this log entry. Note that because
	// this client retries RPCs automatically, it is possible (though unlikely)
	// that an Entry without an InsertID will be written more than once.
	InsertID string

	// HTTPRequest optionally specifies metadata about the HTTP request
	// associated with this log entry, if applicable. It is optional.
	HTTPRequest *HTTPRequest

	// Operation optionally provides information about an operation associated
	// with the log entry, if applicable.
	Operation *logpb.LogEntryOperation

	// LogName is the full log name, in the form
	// "projects/{ProjectID}/logs/{LogID}". It is set by the client when
	// reading entries. It is an error to set it when writing entries.
	LogName string

	// Resource is the monitored resource associated with the entry.
	Resource *mrpb.MonitoredResource

	// Trace is the resource name of the trace associated with the log entry,
	// if any. If it contains a relative resource name, the name is assumed to
	// be relative to //tracing.googleapis.com.
	Trace string

	// Optional. Source code location information associated with the log entry,
	// if any.
	SourceLocation *logpb.LogEntrySourceLocation
}

Entry is a log entry. See https://cloud.google.com/logging/docs/view/logs_index for more about entries.

type HTTPRequest added in v0.2.0

type HTTPRequest struct {
	// Request is the http.Request passed to the handler.
	Request *http.Request

	// RequestSize is the size of the HTTP request message in bytes, including
	// the request headers and the request body.
	RequestSize int64

	// Status is the response code indicating the status of the response.
	// Examples: 200, 404.
	Status int

	// ResponseSize is the size of the HTTP response message sent back to the client, in bytes,
	// including the response headers and the response body.
	ResponseSize int64

	// Latency is the request processing latency on the server, from the time the request was
	// received until the response was sent.
	Latency time.Duration

	// LocalIP is the IP address (IPv4 or IPv6) of the origin server that the request
	// was sent to.
	LocalIP string

	// RemoteIP is the IP address (IPv4 or IPv6) of the client that issued the
	// HTTP request. Examples: "192.168.1.1", "FE80::0202:B3FF:FE1E:8329".
	RemoteIP string

	// CacheHit reports whether an entity was served from cache (with or without
	// validation).
	CacheHit bool

	// CacheValidatedWithOriginServer reports whether the response was
	// validated with the origin server before being served from cache. This
	// field is only meaningful if CacheHit is true.
	CacheValidatedWithOriginServer bool
}

HTTPRequest contains an http.Request as well as additional information about the request and its response.

type Logger added in v0.2.0

type Logger struct {
	// contains filtered or unexported fields
}

A Logger is used to write log messages to a single log. It can be configured with a log ID, common monitored resource, and a set of common labels.

func (*Logger) Flush added in v0.2.0

func (l *Logger) Flush() error

Flush blocks until all currently buffered log entries are sent.

If any errors occurred since the last call to Flush from any Logger, or the creation of the client if this is the first call, then Flush returns a non-nil error with summary information about the errors. This information is unlikely to be actionable. For more accurate error reporting, set Client.OnError.

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	lg.Log(logging.Entry{Payload: "something happened"})
	lg.Flush()
}
Output:

func (*Logger) Log added in v0.2.0

func (l *Logger) Log(e Entry)

Log buffers the Entry for output to the logging service. It never blocks.

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	lg.Log(logging.Entry{Payload: "something happened"})
}
Output:

Example (Json)

To log a JSON value, wrap it in json.RawMessage.

package main

import (
	"context"
	"encoding/json"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	j := []byte(`{"Name": "Bob", "Count": 3}`)
	lg.Log(logging.Entry{Payload: json.RawMessage(j)})
}
Output:

Example (Struct)

An Entry payload can be anything that marshals to a JSON object, like a struct.

package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	type MyEntry struct {
		Name  string
		Count int
	}

	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	lg.Log(logging.Entry{Payload: MyEntry{Name: "Bob", Count: 3}})
}
Output:

func (*Logger) LogSync added in v0.2.0

func (l *Logger) LogSync(ctx context.Context, e Entry) error

LogSync logs the Entry synchronously without any buffering. Because LogSync is slow and will block, it is intended primarily for debugging or critical errors. Prefer Log for most uses. TODO(jba): come up with a better name (LogNow?) or eliminate.

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	err = lg.LogSync(ctx, logging.Entry{Payload: "red alert"})
	if err != nil {
		// TODO: Handle error.
	}
}
Output:

func (*Logger) StandardLogger added in v0.2.0

func (l *Logger) StandardLogger(s Severity) *log.Logger

StandardLogger returns a *log.Logger for the provided severity.

This method is cheap. A single log.Logger is pre-allocated for each severity level in each Logger. Callers may mutate the returned log.Logger (for example by calling SetFlags or SetPrefix).

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("my-log")
	slg := lg.StandardLogger(logging.Info)
	slg.Println("an informative message")
}
Output:

type LoggerOption added in v0.2.0

type LoggerOption interface {
	// contains filtered or unexported methods
}

A LoggerOption is a configuration option for a Logger.

func BufferedByteLimit added in v0.2.0

func BufferedByteLimit(n int) LoggerOption

BufferedByteLimit is the maximum number of bytes that the Logger will keep in memory before returning ErrOverflow. This option limits the total memory consumption of the Logger (but note that each Logger has its own, separate limit). It is possible to reach BufferedByteLimit even if it is larger than EntryByteThreshold or EntryByteLimit, because calls triggered by the latter two options may be enqueued (and hence occupying memory) while new log entries are being added. The default is DefaultBufferedByteLimit.

func CommonLabels added in v0.2.0

func CommonLabels(m map[string]string) LoggerOption

CommonLabels are labels that apply to all log entries written from a Logger, so that you don't have to repeat them in each log entry's Labels field. If any of the log entries contains a (key, value) with the same key that is in CommonLabels, then the entry's (key, value) overrides the one in CommonLabels.

func CommonResource added in v0.2.0

func CommonResource(r *mrpb.MonitoredResource) LoggerOption

CommonResource sets the monitored resource associated with all log entries written from a Logger. If not provided, the resource is automatically detected based on the running environment. This value can be overridden per-entry by setting an Entry's Resource field.

func ConcurrentWriteLimit added in v0.19.0

func ConcurrentWriteLimit(n int) LoggerOption

ConcurrentWriteLimit determines how many goroutines will send log entries to the underlying service. The default is 1. Set ConcurrentWriteLimit to a higher value to increase throughput.

func ContextFunc added in v0.29.0

func ContextFunc(f func() (ctx context.Context, afterCall func())) LoggerOption

ContextFunc is a function that will be called to obtain a context.Context for the WriteLogEntries RPC executed in the background for calls to Logger.Log. The default is a function that always returns context.Background. The second return value of the function is a function to call after the RPC completes.

The function is not used for calls to Logger.LogSync, since the caller can pass in the context directly.

This option is EXPERIMENTAL. It may be changed or removed.

Example

This example shows how to create a Logger that disables OpenCensus tracing of the WriteLogEntries RPC.

package main

import (
	"context"

	"cloud.google.com/go/logging"
	"go.opencensus.io/trace"
)

func main() {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	lg := client.Logger("logID", logging.ContextFunc(func() (context.Context, func()) {
		ctx, span := trace.StartSpan(context.Background(), "this span will not be exported",
			trace.WithSampler(trace.NeverSample()))
		return ctx, span.End
	}))
	_ = lg // TODO: Use lg
}
Output:

func DelayThreshold added in v0.2.0

func DelayThreshold(d time.Duration) LoggerOption

DelayThreshold is the maximum amount of time that an entry should remain buffered in memory before a call to the logging service is triggered. Larger values of DelayThreshold will generally result in fewer calls to the logging service, while increasing the risk that log entries will be lost if the process crashes. The default is DefaultDelayThreshold.

func EntryByteLimit added in v0.2.0

func EntryByteLimit(n int) LoggerOption

EntryByteLimit is the maximum number of bytes of entries that will be sent in a single call to the logging service. ErrOversizedEntry is returned if an entry exceeds EntryByteLimit. This option limits the size of a single RPC payload, to account for network or service issues with large RPCs. If EntryByteLimit is smaller than EntryByteThreshold, the latter has no effect. The default is zero, meaning there is no limit.

func EntryByteThreshold added in v0.2.0

func EntryByteThreshold(n int) LoggerOption

EntryByteThreshold is the maximum number of bytes of entries that will be buffered in memory before a call to the logging service is triggered. See EntryCountThreshold for a discussion of the tradeoffs involved in setting this option. The default is DefaultEntryByteThreshold.

func EntryCountThreshold added in v0.2.0

func EntryCountThreshold(n int) LoggerOption

EntryCountThreshold is the maximum number of entries that will be buffered in memory before a call to the logging service is triggered. Larger values will generally result in fewer calls to the logging service, while increasing both memory consumption and the risk that log entries will be lost if the process crashes. The default is DefaultEntryCountThreshold.

type Severity added in v0.2.0

type Severity int

Severity is the severity of the event described in a log entry. These guideline severity levels are ordered, with numerically smaller levels treated as less severe than numerically larger levels.

func ParseSeverity added in v0.2.0

func ParseSeverity(s string) Severity

ParseSeverity returns the Severity whose name equals s, ignoring case. It returns Default if no Severity matches.

Example
package main

import (
	"fmt"

	"cloud.google.com/go/logging"
)

func main() {
	sev := logging.ParseSeverity("ALERT")
	fmt.Println(sev)
}
Output:

Alert

func (Severity) String added in v0.2.0

func (v Severity) String() string

String converts a severity level to a string.

Directories

Path Synopsis
Package logging is an auto-generated package for the Stackdriver Logging API.
Package logging is an auto-generated package for the Stackdriver Logging API.
testing
Package testing provides support for testing the logging client.
Package testing provides support for testing the logging client.
Package logadmin contains a Stackdriver Logging client that can be used for reading logs and working with sinks, metrics and monitored resources.
Package logadmin contains a Stackdriver Logging client that can be used for reading logs and working with sinks, metrics and monitored resources.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL