logging

package module
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2024 License: Apache-2.0 Imports: 32 Imported by: 705

README

Cloud Logging Go Reference

For an interactive tutorial on using the client library in a Go application, click Guide Me.

Example Usage

First create a logging.Client to use throughout your application: [snip]:# (logging-1)

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

Usually, you'll want to add log entries to a buffer to be periodically flushed (automatically and asynchronously) to the Cloud Logging service. [snip]:# (logging-2)

logger := client.Logger("my-log")
logger.Log(logging.Entry{Payload: "something happened!"})

If you need to write a critical log entry use synchronous ingestion method. [snip]:# (logging-3)

logger := client.Logger("my-log")
logger.LogSync(context.Background(), logging.Entry{Payload: "something happened!"})

Close your client before your program exits, to flush any buffered log entries. [snip]:# (logging-4)

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

Logger configuration options

Creating a Logger using logging.Logger accept configuration LoggerOption arguments. The following options are supported:

Configuration option Arguments Description
CommonLabels map[string]string The set of labels that will be ingested for all log entries ingested by Logger.
ConcurrentWriteLimit int Number of parallel goroutine the Logger will use to ingest logs asynchronously. High number of routines may exhaust API quota. The default is 1.
DelayThreshold time.Duration Maximum time a log entry is buffered on client before being ingested. The default is 1 second.
EntryCountThreshold int Maximum number of log entries to be buffered on client before being ingested. The default is 1000.
EntryByteThreshold int Maximum size in bytes of log entries to be buffered on client before being ingested. The default is 8MiB.
EntryByteLimit int Maximum size in bytes of the single write call to ingest log entries. If EntryByteLimit is smaller than EntryByteThreshold, the latter has no effect. The default is zero, meaning there is no limit.
BufferedByteLimit int 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.
ContextFunc func() (ctx context.Context, afterCall func()) Callback function to be called to obtain context.Context during async log ingestion.
SourceLocationPopulation One of logging.DoNotPopulateSourceLocation, logging.PopulateSourceLocationForDebugEntries or logging.AlwaysPopulateSourceLocation Controls auto-population of the logging.Entry.SourceLocation field when ingesting log entries. Allows to disable population of source location info, allowing it only for log entries at Debug severity or enable it for all log entries. Enabling it for all entries may result in degradation in performance. Use logging_test.BenchmarkSourceLocationPopulation to test performance with and without the option. The default is set to logging.DoNotPopulateSourceLocation.
PartialSuccess Make each write call to Logging service with partialSuccess flag set. The default is to make calls without setting the flag.
RedirectAsJSON io.Writer Converts log entries to Jsonified one line string according to the structured logging format and writes it to provided io.Writer. Users should use this option with os.Stdout and os.Stderr to leverage the out-of-process ingestion of logs using logging agents that are deployed in Cloud Logging environments.

Documentation

Overview

Package logging contains a Cloud 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.

Creating a Client

Use a Client to interact with the Cloud 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 Cloud 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 Cloud 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.

err = lg.LogSync(ctx, logging.Entry{Payload: "ALERT! Something critical happened!"})
if err != nil {
	// TODO: Handle error.
}

Redirecting log ingestion

For cases when runtime environment supports out-of-process log ingestion, like logging agent, you can opt-in to write log entries to io.Writer instead of ingesting them to Cloud Logging service. Usually, you will use os.Stdout or os.Stderr as writers because Google Cloud logging agents are configured to capture logs from standard output. The entries will be Jsonified and wrote as one line strings following the structured logging format. See https://cloud.google.com/logging/docs/structured-logging#special-payload-fields for the format description. To instruct Logger to redirect log entries add RedirectAsJSON() LoggerOption`s.

// Create a logger to print structured logs formatted as a single line Json to stdout
loggger := client.Logger("test-log", RedirectAsJSON(os.Stdout))

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

If you have proto.Message and want to send it as a protobuf payload, marshal it to anypb.Any:

	// import
    func logMessage (m proto.Message) {
		var payload anypb.Any
		err := anypb.MarshalFrom(&payload, m)
		if err != nil {
			lg.Log(logging.Entry{Payload: payload})
		}
	}

The Standard Logger

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

// stdlg is an instance of *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 Cloud 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 MonitoredResource type and labels.

  • Parent entries must have HTTPRequest.Request (strictly speaking, only Method and URL are necessary), and HTTPRequest.Status populated.

- A child entry's timestamp must be within the time interval covered by the parent request. (i.e., before the parent.Timestamp and after the parent.Timestamp - parent.HTTPRequest.Latency. This assumes 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 (
	// DoNotPopulateSourceLocation is default for clients when WithSourceLocation is not provided
	DoNotPopulateSourceLocation = 0
	// PopulateSourceLocationForDebugEntries is set when WithSourceLocation(PopulateDebugEntries) is provided
	PopulateSourceLocationForDebugEntries = 1
	// AlwaysPopulateSourceLocation is set when WithSourceLocation(PopulateAllEntries) is provided
	AlwaysPopulateSourceLocation = 2
)
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 << 23 // 8MiB

	// DefaultBundleByteLimit is the default value for the BundleByteLimit LoggerOption.
	DefaultBundleByteLimit = 9437184 // 9.5 MiB

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

	// DetectProjectID is a sentinel value that instructs NewClient to detect the
	// project ID. It is given in place of the projectID argument. NewClient will
	// use the project ID from the given credentials or the default credentials
	// (https://developers.google.com/accounts/docs/application-default-credentials)
	// if no credentials were provided. When providing credentials, not all
	// options will allow NewClient to extract the project ID. Specifically a JWT
	// does not have the project ID encoded.
	DetectProjectID = "*detect-project-id*"
)
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 (
	// ErrRedirectProtoPayloadNotSupported is returned when Logger is configured to redirect output and
	// tries to redirect logs with protobuf payload.
	ErrRedirectProtoPayloadNotSupported = errors.New("printEntryToStdout: cannot find valid payload")

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

	// 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.
	ErrOversizedEntry = bundler.ErrOversizedItem
)

Functions

func ToLogEntry added in v1.4.0

func ToLogEntry(e Entry, parent string) (*logpb.LogEntry, error)

ToLogEntry takes an Entry structure and converts it to the LogEntry proto. 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.

ToLogEntry is implied when users invoke Logger.Log or Logger.LogSync, but its exported as a pub function here to give users additional flexibility when using the library. Don't call this method manually if Logger.Log or Logger.LogSync are used, it is intended to be used together with direct call to WriteLogEntries method.

Example
package main

import (
	"context"

	"cloud.google.com/go/logging"
	vkit "cloud.google.com/go/logging/apiv2"

	logpb "cloud.google.com/go/logging/apiv2/loggingpb"
)

func main() {
	e := logging.Entry{
		Payload: "Message",
	}
	le, err := logging.ToLogEntry(e, "my-project")
	if err != nil {
		// TODO: Handle error.
	}
	client, err := vkit.NewClient(context.Background())
	if err != nil {
		// TODO: Handle error.
	}
	_, err = client.WriteLogEntries(context.Background(), &logpb.WriteLogEntriesRequest{
		Entries: []*logpb.LogEntry{le},
		LogName: "stdout",
	})
	if err != nil {
		// TODO: Handle error.
	}
}
Output:

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.

If logging.DetectProjectId is provided as the parent, the parent will be interpreted as a project ID, and its value will be inferred from the environment.

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

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

	// ID of the span within the trace associated with the log entry.
	// The ID is a 16-character hexadecimal encoding of an 8-byte array.
	SpanID string

	// If set, symbolizes that this request was sampled.
	TraceSampled bool

	// 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

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

	// CacheFillBytes is the number of HTTP response bytes inserted into cache. Set only when a cache fill was attempted.
	CacheFillBytes int64

	// CacheLookup tells whether or not a cache lookup was attempted.
	CacheLookup bool
}

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

Example
package main

import (
	"context"
	"net/http"

	"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")
	httpEntry := logging.Entry{
		Payload: "optional message",
		HTTPRequest: &logging.HTTPRequest{
			// TODO: pass in request
			Request: &http.Request{},
			// TODO: set the status code
			Status: http.StatusOK,
		},
	}
	lg.Log(httpEntry)
}
Output:

type Logger

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

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

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

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.

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

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:

func (*Logger) StandardLoggerFromTemplate added in v1.7.0

func (l *Logger) StandardLoggerFromTemplate(template *Entry) *log.Logger

StandardLoggerFromTemplate returns a Go Standard Logging API *log.Logger.

The returned logger emits logs using logging.(*Logger).Log() with an entry constructed from the provided template Entry struct.

The caller is responsible for ensuring that the template Entry struct does not change during the the lifetime of the returned *log.Logger.

Prefer (*Logger).StandardLogger() which is more efficient if the template only sets Severity.

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	"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")
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		slg := lg.StandardLoggerFromTemplate(&logging.Entry{
			Severity:    logging.Info,
			HTTPRequest: &logging.HTTPRequest{Request: r},
		})
		slg.Println("Before hello world")
		fmt.Fprintf(w, "Hello world!\n")
	})
}
Output:

func (*Logger) ToLogEntry added in v1.5.0

func (l *Logger) ToLogEntry(e Entry, parent string) (*logpb.LogEntry, error)

ToLogEntry for Logger instance

type LoggerOption

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

LoggerOption is a configuration option for a Logger.

func BufferedByteLimit

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

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

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 (on GCE, GCR, GCF and GAE Standard only). This value can be overridden per-entry by setting an Entry's Resource field.

func ConcurrentWriteLimit

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

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

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

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

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

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.

func PartialSuccess added in v1.5.0

func PartialSuccess() LoggerOption

PartialSuccess sets the partialSuccess flag to true when ingesting a bundle of log entries. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write#body.request_body.FIELDS.partial_success If not provided the partialSuccess flag is set to false.

func RedirectAsJSON added in v1.5.0

func RedirectAsJSON(w io.Writer) LoggerOption

RedirectAsJSON instructs Logger to redirect output of calls to Log and LogSync to provided io.Writer instead of ingesting to Cloud Logging. Logger formats log entries following logging agent's Json format. See https://cloud.google.com/logging/docs/structured-logging#special-payload-fields for more info about the format. Use this option to delegate log ingestion to an out-of-process logging agent. If no writer is provided, the redirect is set to stdout.

Example (WithStdout)
package main

import (
	"context"
	"os"

	"cloud.google.com/go/internal/uid"
	"cloud.google.com/go/logging"
	"cloud.google.com/go/logging/logadmin"
)

const testLogIDPrefix = "GO-LOGGING-CLIENT/TEST-LOG"

var client *logging.Client

func main() {
	logger := client.Logger("redirect-to-stdout", logging.RedirectAsJSON(os.Stdout))
	logger.Log(logging.Entry{Severity: logging.Debug, Payload: "redirected log"})
}
Output:

func SourceLocationPopulation added in v1.5.0

func SourceLocationPopulation(f int) LoggerOption

SourceLocationPopulation is the flag controlling population of the source location info in the ingested entries. This options allows to configure automatic population of the SourceLocation field for all ingested entries, entries with DEBUG severity or disable it. Note that enabling this option can decrease execution time of Logger.Log and Logger.LogSync by the factor of 2 or larger. The default disables source location population.

This option is not used when an entry is created using ToLogEntry.

type Severity

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

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

func (v Severity) String() string

String converts a severity level to a string.

func (*Severity) UnmarshalJSON added in v1.1.0

func (v *Severity) UnmarshalJSON(data []byte) error

UnmarshalJSON turns a string representation of severity into the type Severity.

Directories

Path Synopsis
Package logging is an auto-generated package for the Cloud Logging API.
Package logging is an auto-generated package for the Cloud 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 Cloud Logging client that can be used for reading logs and working with sinks, metrics and monitored resources.
Package logadmin contains a Cloud 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