tessl install tessl/golang-cloud-google-com--go--logging@1.13.0Cloud Logging client library for Go that enables writing log entries to Google Cloud Logging service with buffered asynchronous and synchronous logging capabilities.
Cloud Logging for Go provides a comprehensive client library for writing log entries to Google Cloud Logging service and managing logging resources. The library offers both asynchronous buffered logging for high-throughput scenarios and synchronous logging for critical events, supports multiple payload types including strings, JSON objects, structs, and protobuf messages, and provides extensive configuration options for buffering thresholds, concurrency limits, and batch processing.
go get cloud.google.com/go/logging@v1.13.1import (
"cloud.google.com/go/logging"
"cloud.google.com/go/logging/logadmin"
)import (
"context"
"cloud.google.com/go/logging"
)
func main() {
ctx := context.Background()
// Create a logging client
client, err := logging.NewClient(ctx, "my-project")
if err != nil {
// Handle error
}
defer client.Close()
// Create a logger
logger := client.Logger("my-log")
// Log an entry (buffered, asynchronous)
logger.Log(logging.Entry{
Payload: "something happened!",
Severity: logging.Info,
})
// For critical entries, use synchronous logging
err = logger.LogSync(ctx, logging.Entry{
Payload: "critical event!",
Severity: logging.Critical,
})
}Understanding the package structure, buffering mechanisms, and design patterns.
Create and manage Cloud Logging clients that connect to Google Cloud Logging service.
func NewClient(ctx context.Context, parent string, opts ...option.ClientOption) (*Client, error)The parent parameter can take the following forms:
projects/PROJECT_IDfolders/FOLDER_IDbillingAccounts/ACCOUNT_IDorganizations/ORG_IDlogging.DetectProjectID (auto-detect from environment)func (c *Client) Close() error
func (c *Client) Ping(ctx context.Context) errorWrite log entries to Cloud Logging using buffered asynchronous logging or synchronous logging for critical events.
func (l *Logger) Log(e Entry)
func (l *Logger) LogSync(ctx context.Context, e Entry) error
func (l *Logger) Flush() errorThe Entry type represents a log entry:
type Entry struct {
Timestamp time.Time
Severity Severity
Payload interface{}
Labels map[string]string
InsertID string
HTTPRequest *HTTPRequest
Operation *logpb.LogEntryOperation
LogName string
Resource *mrpb.MonitoredResource
Trace string
SpanID string
TraceSampled bool
SourceLocation *logpb.LogEntrySourceLocation
}Configure loggers with various options for buffering, concurrency, labels, resources, and output redirection.
func CommonLabels(m map[string]string) LoggerOption
func CommonResource(r *mrpb.MonitoredResource) LoggerOption
func ConcurrentWriteLimit(n int) LoggerOption
func DelayThreshold(d time.Duration) LoggerOption
func EntryCountThreshold(n int) LoggerOption
func EntryByteThreshold(n int) LoggerOption
func EntryByteLimit(n int) LoggerOption
func BufferedByteLimit(n int) LoggerOption
func SourceLocationPopulation(f int) LoggerOption
func PartialSuccess() LoggerOption
func RedirectAsJSON(w io.Writer) LoggerOption
func ContextFunc(f func() (ctx context.Context, afterCall func())) LoggerOptionSupport for multiple payload types including strings, JSON objects, structs, json.RawMessage, and protobuf messages.
The Payload field of an Entry can be:
Log entries can be assigned severity levels to indicate the importance and urgency of events.
type Severity int
const (
Default Severity
Debug Severity
Info Severity
Notice Severity
Warning Severity
Error Severity
Critical Severity
Alert Severity
Emergency Severity
)
func ParseSeverity(s string) Severity
func (v Severity) String() string
func (v *Severity) UnmarshalJSON(data []byte) errorAssociate log entries with HTTP requests for correlation and grouping in Cloud Logging console.
type HTTPRequest struct {
Request *http.Request
RequestSize int64
Status int
ResponseSize int64
Latency time.Duration
LocalIP string
RemoteIP string
CacheHit bool
CacheValidatedWithOriginServer bool
CacheFillBytes int64
CacheLookup bool
}Automatically populate trace and span IDs from OpenTelemetry, W3C Traceparent, or X-Cloud-Trace-Context headers for distributed tracing integration.
// Entry fields for tracing
type Entry struct {
// ...
Trace string
SpanID string
TraceSampled bool
// ...
}Create Go standard library *log.Logger instances that write to Cloud Logging.
func (l *Logger) StandardLogger(s Severity) *log.Logger
func (l *Logger) StandardLoggerFromTemplate(template *Entry) *log.LoggerRead logs, manage sinks for exporting logs, create and manage logs-based metrics, and work with monitored resources.
// logadmin.Client for administrative operations
func NewClient(ctx context.Context, parent string, opts ...option.ClientOption) (*Client, error)
// Reading logs
func (c *Client) Entries(ctx context.Context, opts ...EntriesOption) *EntryIterator
func (c *Client) Logs(ctx context.Context) *LogIterator
// Managing sinks
func (c *Client) Sink(ctx context.Context, sinkID string) (*Sink, error)
func (c *Client) Sinks(ctx context.Context) *SinkIterator
func (c *Client) CreateSink(ctx context.Context, sink *Sink) (*Sink, error)
func (c *Client) UpdateSink(ctx context.Context, sink *Sink) (*Sink, error)
func (c *Client) DeleteSink(ctx context.Context, sinkID string) error
// Managing metrics
func (c *Client) Metric(ctx context.Context, metricID string) (*Metric, error)
func (c *Client) Metrics(ctx context.Context) *MetricIterator
func (c *Client) CreateMetric(ctx context.Context, m *Metric) error
func (c *Client) UpdateMetric(ctx context.Context, m *Metric) error
func (c *Client) DeleteMetric(ctx context.Context, metricID string) error
// Managing logs
func (c *Client) DeleteLog(ctx context.Context, logID string) error
// Resource descriptors
func (c *Client) ResourceDescriptors(ctx context.Context) *ResourceDescriptorIteratorHandle errors from logging operations including overflow, oversized entries, and redirect failures.
var (
ErrRedirectProtoPayloadNotSupported error
ErrOverflow error
ErrOversizedEntry error
)
// Client.OnError callback
type Client struct {
OnError func(err error)
// ...
}Predefined constants for scopes, default configuration values, and source location population options.
const (
ReadScope = "https://www.googleapis.com/auth/logging.read"
WriteScope = "https://www.googleapis.com/auth/logging.write"
AdminScope = "https://www.googleapis.com/auth/logging.admin"
)
const (
DefaultDelayThreshold = time.Second
DefaultEntryCountThreshold = 1000
DefaultEntryByteThreshold = 8388608 // 8MiB
DefaultBundleByteLimit = 9437184 // 9.5 MiB
DefaultBufferedByteLimit = 1073741824 // 1GiB
DetectProjectID = "*detect-project-id*"
)
const (
DoNotPopulateSourceLocation = 0
PopulateSourceLocationForDebugEntries = 1
AlwaysPopulateSourceLocation = 2
)type Client struct {
OnError func(err error)
}
type Logger struct {
// unexported fields
}
type Entry struct {
Timestamp time.Time
Severity Severity
Payload interface{}
Labels map[string]string
InsertID string
HTTPRequest *HTTPRequest
Operation *logpb.LogEntryOperation
LogName string
Resource *mrpb.MonitoredResource
Trace string
SpanID string
TraceSampled bool
SourceLocation *logpb.LogEntrySourceLocation
}
type HTTPRequest struct {
Request *http.Request
RequestSize int64
Status int
ResponseSize int64
Latency time.Duration
LocalIP string
RemoteIP string
CacheHit bool
CacheValidatedWithOriginServer bool
CacheFillBytes int64
CacheLookup bool
}
type Severity int
type LoggerOption interface {
// unexported methods
}type Client struct {
// unexported fields (logadmin package)
}
type Sink struct {
ID string
Destination string
Filter string
WriterIdentity string
IncludeChildren bool
}
type SinkOptions struct {
UniqueWriterIdentity bool
UpdateDestination bool
UpdateFilter bool
UpdateIncludeChildren bool
}
type Metric struct {
ID string
Description string
Filter string
}
type EntryIterator struct {
// unexported fields
}
type LogIterator struct {
// unexported fields
}
type SinkIterator struct {
// unexported fields
}
type MetricIterator struct {
// unexported fields
}
type ResourceDescriptorIterator struct {
// unexported fields
}
type EntriesOption interface {
// unexported methods
}