or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/cloud.google.com/go/logging@v1.13.1
tile.json

tessl/golang-cloud-google-com--go--logging

tessl install tessl/golang-cloud-google-com--go--logging@1.13.0

Cloud Logging client library for Go that enables writing log entries to Google Cloud Logging service with buffered asynchronous and synchronous logging capabilities.

index.mddocs/

Cloud Logging for Go

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.

Package Information

  • Package Name: cloud.google.com/go/logging
  • Package Type: golang
  • Language: Go
  • Version: v1.13.1
  • Installation: go get cloud.google.com/go/logging@v1.13.1

Core Imports

import (
    "cloud.google.com/go/logging"
    "cloud.google.com/go/logging/logadmin"
)

Basic Usage

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

Architecture

Understanding the package structure, buffering mechanisms, and design patterns.

Package Architecture

Capabilities

Client Creation and Management

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_ID
  • folders/FOLDER_ID
  • billingAccounts/ACCOUNT_ID
  • organizations/ORG_ID
  • Project ID string (backwards compatibility)
  • logging.DetectProjectID (auto-detect from environment)
func (c *Client) Close() error

func (c *Client) Ping(ctx context.Context) error

Client and Logger Management

Writing Log Entries

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

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

Writing Log Entries

Logger Configuration

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

Logger Configuration

Log Entry Payloads

Support for multiple payload types including strings, JSON objects, structs, json.RawMessage, and protobuf messages.

The Payload field of an Entry can be:

  • A string
  • A value that marshals to a JSON object (map[string]interface{}, struct)
  • json.RawMessage for raw JSON bytes
  • anypb.Any for protobuf messages

Payload Types and Formatting

Severity Levels

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

Severity Levels

HTTP Request Metadata

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

HTTP Request Metadata

Trace and Span Context

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

Trace and Span Context

Standard Logger Integration

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

Standard Logger Integration

Administrative Operations (logadmin)

Read 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) *ResourceDescriptorIterator

Administrative Operations

Error Handling

Handle 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)
    // ...
}

Error Handling

Constants and Defaults

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
)

Constants and Defaults

Types

Core Types

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
}

logadmin Types

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
}