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.
This document describes how to create and manage Cloud Logging clients and loggers.
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 projectfolders/FOLDER_ID - Associate with a folderbillingAccounts/ACCOUNT_ID - Associate with a billing accountorganizations/ORG_ID - Associate with an organizationlogging.DetectProjectID - Auto-detect project ID from environmentThe client uses WriteScope by default. To use a different scope, provide a WithScopes option.
Parameters:
ctx - Context for the operationparent - Parent resource identifieropts - Optional client configuration options (e.g., credentials, scopes)Returns:
*Client - The created logging clienterror - Error if client creation failsExample:
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()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.func (c *Client) Logger(logID string, opts ...LoggerOption) *LoggerCreates 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:
Parameters:
logID - The log identifier (e.g., "syslog", "application-log")opts - Optional logger configuration options (see Logger Configuration)Returns:
*Logger - The created logger instanceExample:
// 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),
)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.
func (c *Client) Close() errorWaits 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 failsExample:
defer client.Close()
// Or with error handling
if err := client.Close(); err != nil {
log.Printf("failed to close client: %v", err)
}func (c *Client) Ping(ctx context.Context) errorReports 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 operationReturns:
error - Error if ping fails, nil if connection is validExample:
ctx := context.Background()
if err := client.Ping(ctx); err != nil {
log.Fatalf("client connection failed: %v", err)
}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 callbackpackage 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)
}
}