go: cloud.google.com/go/logging Index | Examples | Files | Directories

package logging

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

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 basic use.

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

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,
}

Index

Examples

Package Files

doc.go logging.go

Constants

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

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

    // Scope for administrative actions on the logging service.
    AdminScope = "https://www.googleapis.com/auth/logging.admin"
)
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
)
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

var ErrOverflow = bundler.ErrOverflow

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

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.

type Client Uses

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 Uses

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

NewClient returns a new logging client associated with the provided 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).

Code:

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.
}

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.

Code:

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)

func (*Client) Close Uses

func (c *Client) Close() error

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

func (*Client) Logger Uses

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.

Code:

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.

func (*Client) Ping Uses

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".

Code:

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.
}

type Entry Uses

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. It is set
    // by the client when reading entries. It is an error to set it when
    // writing entries.
    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
}

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

type HTTPRequest Uses

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 Uses

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 Uses

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.

Code:

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()

func (*Logger) Log Uses

func (l *Logger) Log(e Entry)

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

Code:

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"})

func (*Logger) LogSync Uses

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.

Code:

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.
}

func (*Logger) StandardLogger Uses

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).

Code:

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")

type LoggerOption Uses

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

A LoggerOption is a configuration option for a Logger.

func BufferedByteLimit Uses

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 Uses

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 Uses

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 DelayThreshold Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func ParseSeverity(s string) Severity

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

Code:

sev := logging.ParseSeverity("ALERT")
fmt.Println(sev)

Output:

Alert

func (Severity) String Uses

func (v Severity) String() string

String converts a severity level to a string.

Directories

PathSynopsis
apiv2Package logging is an experimental, auto-generated package for the Stackdriver Logging API.
internal
internal/testingPackage testing provides support for testing the logging client.
logadminPackage logadmin contains a Stackdriver Logging client that can be used for reading logs and working with sinks, metrics and monitored resources.

Package logging imports 24 packages (graph) and is imported by 54 packages. Updated 2017-09-24. Refresh now. Tools for package owners.