package logging

Import Path
	cloud.google.com/go/logging (on go.dev)

Dependency Relation
	imports 26 packages, and imported by 2 packages

Involved Source Files 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. 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. 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 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. logging.go
Package-Level Type Names (total 16, in which 6 are exported)
/* sort exporteds by: | */
Client is a Logging client. A Client is associated with a single Cloud project. 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. Close waits for all opened loggers to be flushed and closes the client. 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. 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". *T : database/sql/driver.Pinger *T : io.Closer func NewClient(ctx context.Context, parent string, opts ...option.ClientOption) (*Client, error)
Entry is a log entry. See https://cloud.google.com/logging/docs/view/logs_index for more about entries. HTTPRequest optionally specifies metadata about the HTTP request associated with this log entry, if applicable. It is optional. 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. 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. 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. Operation optionally provides information about an operation associated with the log entry, if applicable. 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). Resource is the monitored resource associated with the entry. Severity is the entry's severity level. The zero value is Default. Optional. Source code location information associated with the log entry, if any. 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. Timestamp is the time of the entry. If zero, the current time is used. 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. If set, symbolizes that this request was sampled. func (*Logger).Log(e Entry) func (*Logger).LogSync(ctx context.Context, e Entry) error func golang.org/x/pkgsite/internal/middleware.LocalLogger.Log(entry Entry) func golang.org/x/pkgsite/internal/middleware.Logger.Log(Entry)
HTTPRequest contains an http.Request as well as additional information about the request and its response. CacheHit reports whether an entity was served from cache (with or without validation). 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. Latency is the request processing latency on the server, from the time the request was received until the response was sent. LocalIP is the IP address (IPv4 or IPv6) of the origin server that the request was sent to. 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". Request is the http.Request passed to the handler. RequestSize is the size of the HTTP request message in bytes, including the request headers and the request body. ResponseSize is the size of the HTTP response message sent back to the client, in bytes, including the response headers and the response body. Status is the response code indicating the status of the response. Examples: 200, 404.
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. 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. Log buffers the Entry for output to the logging service. It never blocks. 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. 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). *T : golang.org/x/pkgsite/internal/middleware.Logger func (*Client).Logger(logID string, opts ...LoggerOption) *Logger func golang.org/x/pkgsite/internal/log.UseStackdriver(ctx context.Context, cfg *config.Config, logName string) (_ *Logger, err error)
A LoggerOption is a configuration option for a Logger. func BufferedByteLimit(n int) LoggerOption func CommonLabels(m map[string]string) LoggerOption func CommonResource(r *mrpb.MonitoredResource) LoggerOption func ConcurrentWriteLimit(n int) LoggerOption func ContextFunc(f func() (ctx context.Context, afterCall func())) LoggerOption func DelayThreshold(d time.Duration) LoggerOption func EntryByteLimit(n int) LoggerOption func EntryByteThreshold(n int) LoggerOption func EntryCountThreshold(n int) LoggerOption func (*Client).Logger(logID string, opts ...LoggerOption) *Logger
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. String converts a severity level to a string. T : expvar.Var T : fmt.Stringer func ParseSeverity(s string) Severity func (*Logger).StandardLogger(s Severity) *log.Logger const Alert const Critical const Debug const Default const Emergency const Error const Info const Notice const Warning
Package-Level Functions (total 21, in which 11 are exported)
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
ParseSeverity returns the Severity whose name equals s, ignoring case. It returns Default if no Severity matches.
Package-Level Variables (total 8, in which 2 are exported)
ErrOverflow signals that the number of buffered entries for a Logger exceeds its BufferLimit.
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.
Package-Level Constants (total 18, in which 16 are exported)
AdminScope is the scope for administrative actions on the logging service.
Alert means a person must take an action immediately.
Critical means events that cause more severe problems or brief outages.
Debug means debug or trace information.
Default means the log entry has no assigned severity level.
DefaultBufferedByteLimit is the default value for the BufferedByteLimit LoggerOption.
DefaultDelayThreshold is the default value for the DelayThreshold LoggerOption.
DefaultEntryByteThreshold is the default value for the EntryByteThreshold LoggerOption.
DefaultEntryCountThreshold is the default value for the EntryCountThreshold LoggerOption.
Emergency means one or more systems are unusable.
Error means events that are likely to cause problems.
Info means routine information, such as ongoing status or performance.
Notice means normal but significant events, such as start up, shut down, or configuration.
ReadScope is the scope for reading from the logging service.
Warning means events that might cause problems.
WriteScope is the scope for writing to the logging service.