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. }
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
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.
Constants
ReadScope, WriteScope, AdminScope
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"
)
DefaultDelayThreshold, DefaultEntryCountThreshold, DefaultEntryByteThreshold, DefaultBufferedByteLimit
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="">
Default, Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency
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
ErrOverflow
var ErrOverflow = bundler.ErrOverflow
ErrOverflow signals that the number of buffered entries for a Logger exceeds its BufferLimit.
ErrOversizedEntry
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.
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
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).
Examples
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.
}
}
errorFunc
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)
}
func (*Client) Close
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.
}
func (*Client) Ping
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.
}
}
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.
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)
}
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
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()
}
func (*Logger) Log
Log buffers the Entry for output to the logging service. It never blocks.
Examples
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"})
}
json
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)})
}
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}})
}
func (*Logger) LogSync
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.
}
}
func (*Logger) StandardLogger
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")
}
LoggerOption
type LoggerOption interface {
// contains filtered or unexported methods
}
A 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 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
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
}
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.
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
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)
}
func (Severity) String
String converts a severity level to a string.
func (*Severity) UnmarshalJSON
UnmarshalJSON turns a string representation of severity into the type Severity.