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

docs

architecture.mdclient-logger.mdconstants.mderrors.mdhttp-request.mdindex.mdlogadmin.mdlogger-config.mdpayloads.mdseverity.mdstandard-logger.mdtracing.mdwriting-logs.md
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.

client-logger.mddocs/

Client and Logger Management

This document describes how to create and manage Cloud Logging clients and loggers.

Creating a Client

func NewClient(ctx context.Context, parent string, opts ...option.ClientOption) (*Client, error)

Creates a new logging client associated with the provided parent resource. The parent parameter can take any of the following forms:

  • projects/PROJECT_ID - Associate with a specific project
  • folders/FOLDER_ID - Associate with a folder
  • billingAccounts/ACCOUNT_ID - Associate with a billing account
  • organizations/ORG_ID - Associate with an organization
  • Project ID string (backwards compatibility) - String with no '/' is interpreted as a project ID
  • logging.DetectProjectID - Auto-detect project ID from environment

The client uses WriteScope by default. To use a different scope, provide a WithScopes option.

Parameters:

  • ctx - Context for the operation
  • parent - Parent resource identifier
  • opts - Optional client configuration options (e.g., credentials, scopes)

Returns:

  • *Client - The created logging client
  • error - Error if client creation fails

Example:

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

ctx := context.Background()

// Create client with project ID
client, err := logging.NewClient(ctx, "my-project-id")
if err != nil {
    // Handle error
}
defer client.Close()

// Create client with full project path
client2, err := logging.NewClient(ctx, "projects/my-project-id")
if err != nil {
    // Handle error
}
defer client2.Close()

// Create client with auto-detected project ID
client3, err := logging.NewClient(ctx, logging.DetectProjectID)
if err != nil {
    // Handle error
}
defer client3.Close()

// Create client for organization
client4, err := logging.NewClient(ctx, "organizations/my-org-id")
if err != nil {
    // Handle error
}
defer client4.Close()

Client Type

type Client struct {
    OnError func(err error)
}

The Client type represents a logging client associated with a single Cloud project, folder, billing account, or organization.

Fields:

  • OnError func(err error) - Callback function called when an error occurs in a call to Log or Flush. The error may be due to an invalid Entry, an overflow (ErrOverflow), or a communication error. OnError is called with errors from all Loggers and is never called concurrently. It should return quickly. The default behavior is to call log.Printf. This field should be set only once, before any method of Client is called.

Creating a Logger

func (c *Client) Logger(logID string, opts ...LoggerOption) *Logger

Creates a Logger that will write entries with the given log ID. 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]
  • Punctuation characters: forward-slash (/), underscore (_), hyphen (-), and period (.)

Parameters:

  • logID - The log identifier (e.g., "syslog", "application-log")
  • opts - Optional logger configuration options (see Logger Configuration)

Returns:

  • *Logger - The created logger instance

Example:

// Create a simple logger
logger := client.Logger("my-application-log")

// Create a logger with options
logger2 := client.Logger("structured-log",
    logging.CommonLabels(map[string]string{
        "environment": "production",
        "service": "api-server",
    }),
    logging.ConcurrentWriteLimit(5),
    logging.DelayThreshold(2 * time.Second),
)

Logger Type

type Logger struct {
    // 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.

Closing the Client

func (c *Client) Close() error

Waits for all opened loggers to be flushed and closes the client. This should be called before your program exits to ensure all buffered log entries are sent to the Cloud Logging service.

Returns:

  • error - Error if closing fails

Example:

defer client.Close()

// Or with error handling
if err := client.Close(); err != nil {
    log.Printf("failed to close client: %v", err)
}

Testing the Connection

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

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

Parameters:

  • ctx - Context for the operation

Returns:

  • error - Error if ping fails, nil if connection is valid

Example:

ctx := context.Background()
if err := client.Ping(ctx); err != nil {
    log.Fatalf("client connection failed: %v", err)
}

Error Handling

The Client's OnError callback is invoked when errors occur during logging operations. This provides a centralized way to handle errors from all loggers created by the client.

Example:

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

// Set custom error handler before creating loggers
client.OnError = func(err error) {
    // Custom error handling
    if err == logging.ErrOverflow {
        metrics.IncrementCounter("logging_overflow")
    }
    log.Printf("logging error: %v", err)
}

logger := client.Logger("my-log")
// Any errors from this logger will call the OnError callback

Complete Example

package main

import (
    "context"
    "log"
    "time"

    "cloud.google.com/go/logging"
)

func main() {
    ctx := context.Background()

    // Create client
    client, err := logging.NewClient(ctx, "my-project")
    if err != nil {
        log.Fatalf("failed to create client: %v", err)
    }
    defer client.Close()

    // Set custom error handler
    client.OnError = func(err error) {
        log.Printf("logging error: %v", err)
    }

    // Test connection
    if err := client.Ping(ctx); err != nil {
        log.Fatalf("client connection failed: %v", err)
    }

    // Create logger with options
    logger := client.Logger("app-log",
        logging.CommonLabels(map[string]string{
            "environment": "production",
        }),
        logging.DelayThreshold(2*time.Second),
    )

    // Log some entries
    logger.Log(logging.Entry{
        Payload:  "Application started",
        Severity: logging.Info,
    })

    // Flush before closing
    if err := logger.Flush(); err != nil {
        log.Printf("failed to flush: %v", err)
    }
}