Logging client libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Logging API. Read more about the client libraries for Cloud APIs, including the older Google API Client Libraries, in Client Libraries Explained.

Cloud Logging client libraries are idiomatic interfaces around the API. Client libraries provide an integration option with Logging, in addition to the Logging agent available by default in most Google Cloud services. To learn more about setting up Logging using a language runtime, see Setting up Language Runtimes.

Incoming log entries with timestamps that are more than the logs retention period in the past or that are more than 24 hours in the future are discarded.

If you use Android, we recommend that you use Firebase for logging. For more information, see Write and view logs.

Install the client library

C++

See Setting up a C++ development environment for details about this client library's requirements and install dependencies.

C#

For more information, see Setting Up a C# Development Environment.

dotnet add package Google.Cloud.Logging.V2

Go

For more information, see Setting Up a Go Development Environment.

go get cloud.google.com/go/logging

Java

For more information, see Setting Up a Java Development Environment.

If you are using Maven with a BOM, add the following to your pom.xml file:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.20.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-logging</artifactId>
  </dependency>

  <!-- ...
</dependencies>

If you are using Maven without a BOM, add this to your dependencies:

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-logging</artifactId>
  <version>3.15.7</version>
</dependency>

If you are using Gradle, add the following to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.22.0')

implementation 'com.google.cloud:google-cloud-logging'

If you are using sbt, add the following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "3.15.8"

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/logging

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-logging

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-logging
Install the google-cloud-logging library, not an explicitly versioned library.

Ruby

For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-logging

Set up authentication

When you use client libraries, you use Application Default Credentials (ADC) to authenticate. For information about setting up ADC, see Provide credentials for Application Default Credentials. For information about using ADC with client libraries, see Authenticate using client libraries.

Use the client library

The following example shows how to use the client library.

C++

To learn how to install and use the client library for Logging, see Logging client libraries. For more information, see the Logging C++ API reference documentation.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


#include "google/cloud/logging/v2/logging_service_v2_client.h"
#include "google/cloud/project.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " project-id\n";
    return 1;
  }

  namespace logging = ::google::cloud::logging_v2;
  auto client = logging::LoggingServiceV2Client(
      logging::MakeLoggingServiceV2Connection());
  auto const project = google::cloud::Project(argv[1]);
  for (auto l : client.ListLogs(project.FullName())) {
    if (!l) throw std::move(l).status();
    std::cout << *l << "\n";
  }

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

C#

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


using System;
// Imports the Google Cloud Logging client library
using Google.Cloud.Logging.V2;
using Google.Cloud.Logging.Type;
using System.Collections.Generic;
using Google.Api;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Instantiates a client.
            var client = LoggingServiceV2Client.Create();

            // Prepare new log entry.
            LogEntry logEntry = new LogEntry();
            string logId = "my-log";
            LogName logName = new LogName(projectId, logId);
            logEntry.LogNameAsLogName = logName;
            logEntry.Severity = LogSeverity.Info;

            // Create log entry message.
            string message = "Hello World!";
            string messageId = DateTime.Now.Millisecond.ToString();
            Type myType = typeof(QuickStart);
            string entrySeverity = logEntry.Severity.ToString().ToUpper();
            logEntry.TextPayload =
                $"{messageId} {entrySeverity} {myType.Namespace}.LoggingSample - {message}";

            // Set the resource type to control which GCP resource the log entry belongs to.
            // See the list of resource types at:
            // https://cloud.google.com/logging/docs/api/v2/resource-list
            // This sample uses resource type 'global' causing log entries to appear in the 
            // "Global" resource list of the Developers Console Logs Viewer:
            //  https://console.cloud.google.com/logs/viewer
            MonitoredResource resource = new MonitoredResource
            {
                Type = "global"
            };

            // Create dictionary object to add custom labels to the log entry.
            IDictionary<string, string> entryLabels = new Dictionary<string, string>();
            entryLabels.Add("size", "large");
            entryLabels.Add("color", "red");

            // Add log entry to collection for writing. Multiple log entries can be added.
            IEnumerable<LogEntry> logEntries = new LogEntry[] { logEntry };

            // Write new log entry.
            client.WriteLogEntries(logName, resource, entryLabels, logEntries);

            Console.WriteLine("Log Entry created.");
        }
    }
}

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// Sample logging-quickstart writes a log entry to Cloud Logging.
package main

import (
	"context"
	"fmt"
	"log"

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

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

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the name of the log to write to.
	logName := "my-log"

	// Selects the log to write to.
	logger := client.Logger(logName)

	// Sets the data to log.
	text := "Hello, world!"

	// Adds an entry to the log buffer.
	logger.Log(logging.Entry{Payload: text})

	// Closes the client and flushes the buffer to the Cloud Logging
	// service.
	if err := client.Close(); err != nil {
		log.Fatalf("Failed to close client: %v", err)
	}

	fmt.Printf("Logged: %v\n", text)
}

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload.StringPayload;
import com.google.cloud.logging.Severity;
import java.util.Collections;

/**
 * This sample demonstrates writing logs using the Cloud Logging API. The library also offers a
 * java.util.logging Handler `com.google.cloud.logging.LoggingHandler` Logback integration is also
 * available :
 * https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-contrib/google-cloud-logging-logback
 * Using the java.util.logging handler / Logback appender should be preferred to using the API
 * directly.
 */
public class QuickstartSample {

  /** Expects a new or existing Cloud log name as the first argument. */
  public static void main(String... args) throws Exception {
    // The name of the log to write to
    String logName = args[0]; // "my-log";
    String textPayload = "Hello, world!";

    // Instantiates a client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

      LogEntry entry =
          LogEntry.newBuilder(StringPayload.of(textPayload))
              .setSeverity(Severity.ERROR)
              .setLogName(logName)
              .setResource(MonitoredResource.newBuilder("global").build())
              .build();

      // Writes the log entry asynchronously
      logging.write(Collections.singleton(entry));

      // Optional - flush any pending log entries just before Logging is closed
      logging.flush();
    }
    System.out.printf("Logged: %s%n", textPayload);
  }
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

async function quickstart(
  projectId = 'YOUR_PROJECT_ID', // Your Google Cloud Platform project ID
  logName = 'my-log' // The name of the log to write to
) {
  // Creates a client
  const logging = new Logging({projectId});

  // Selects the log to write to
  const log = logging.log(logName);

  // The data to write to the log
  const text = 'Hello, world!';

  // The metadata associated with the entry
  const metadata = {
    resource: {type: 'global'},
    // See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity
    severity: 'INFO',
  };

  // Prepares a log entry
  const entry = log.entry(metadata, text);

  async function writeLog() {
    // Writes the log entry
    await log.write(entry);
    console.log(`Logged: ${text}`);
  }
  writeLog();
}

PHP

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Logging\LoggingClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$logging = new LoggingClient([
    'projectId' => $projectId
]);

# The name of the log to write to
$logName = 'my-log';

# Selects the log to write to
$logger = $logging->logger($logName);

# The data to log
$text = 'Hello, world!';

# Creates the log entry
$entry = $logger->entry($text);

# Writes the log entry
$logger->write($entry);

echo 'Logged ' . $text;

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# Imports the Google Cloud client library
from google.cloud import logging

# Instantiates a client
logging_client = logging.Client()

# The name of the log to write to
log_name = "my-log"
# Selects the log to write to
logger = logging_client.logger(log_name)

# The data to log
text = "Hello, world!"

# Writes the log entry
logger.log_text(text)

print("Logged: {}".format(text))

Ruby

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# Imports the Google Cloud client library
require "google/cloud/logging"

# Instantiates a client
logging = Google::Cloud::Logging.new

# Prepares a log entry
entry = logging.entry
# payload = "The data you want to log"
entry.payload = payload
# log_name = "The name of the log to write to"
entry.log_name = log_name
# The resource associated with the data
entry.resource.type = "global"

# Writes the log entry
logging.write_entries entry

puts "Logged #{entry.payload}"

The following sections provide additional code samples for writing and managing logs in Logging. As some features are omitted, the language documentation for each library is the authoritative reference.

Log entries

Logs consist of individual log entries, each in a structured format with fields like resource, sourceLocation, labels, and trace that give additional context to each log. For more information about log entries, see the API reference page LogEntry.

Write structured logs

This sample demonstrates writing log entries.

C#

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

private void WriteLogEntry(string logId)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    var jsonPayload = new Struct()
    {
        Fields =
        {
            { "name", Value.ForString("King Arthur") },
            { "quest", Value.ForString("Find the Holy Grail") },
            { "favorite_color", Value.ForString("Blue") }
        }
    };
    LogEntry logEntry = new LogEntry
    {
        LogNameAsLogName = logName,
        Severity = LogSeverity.Info,
        JsonPayload = jsonPayload
    };
    MonitoredResource resource = new MonitoredResource { Type = "global" };
    IDictionary<string, string> entryLabels = new Dictionary<string, string>
    {
        { "size", "large" },
        { "color", "blue" }
    };
    client.WriteLogEntries(logName, resource, entryLabels,
        new[] { logEntry }, _retryAWhile);
    Console.WriteLine($"Created log entry in log-id: {logId}.");
}

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


For step-by-step guidance on running this code directly in Cloud Shell Editor:

  1. Click Guide me.

  2. You see a panel Learn. Click Start to follow the tutorial.

Guide me


import (
	"context"
	"log"

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

func structuredWrite(projectID string) {
	ctx := context.Background()
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create logging client: %v", err)
	}
	defer client.Close()
	const name = "log-example"
	logger := client.Logger(name)
	defer logger.Flush() // Ensure the entry is written.

	logger.Log(logging.Entry{
		// Log anything that can be marshaled to JSON.
		Payload: struct{ Anything string }{
			Anything: "The payload can be any type!",
		},
		Severity: logging.Debug,
	})
}

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


For step-by-step guidance on running this code directly in Cloud Shell Editor:

  1. Click Guide me.

  2. You see a panel Learn. Click Start to follow the tutorial.

Guide me

import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload.JsonPayload;
import com.google.cloud.logging.Severity;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.Map;

public class WriteLogEntry {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Optionally provide the logname as an argument
    String logName = args.length > 0 ? args[0] : "test-log";

    // Instantiates a client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {
      Map<String, String> payload =
          ImmutableMap.of(
              "name", "King Arthur", "quest", "Find the Holy Grail", "favorite_color", "Blue");
      LogEntry entry =
          LogEntry.newBuilder(JsonPayload.of(payload))
              .setSeverity(Severity.INFO)
              .setLogName(logName)
              .setResource(MonitoredResource.newBuilder("global").build())
              .build();

      // Writes the log entry asynchronously
      logging.write(Collections.singleton(entry));

      // Optional - flush any pending log entries just before Logging is closed
      logging.flush();
    }
    System.out.printf("Wrote to %s\n", logName);
  }
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


For step-by-step guidance on running this code directly in Cloud Shell Editor:

  1. Click Guide me.

  2. You see a panel Learn. Click Start to follow the tutorial.

Guide me

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

/**
 * TODO(developer): Uncomment the following line and replace with your values.
 */
// const logName = 'my-log';
const log = logging.log(logName);

// A text log entry
const text_entry = log.entry('Hello world!');

// A json log entry with additional context
const metadata = {
  severity: 'WARNING',
  labels: {
    foo: 'bar',
  },
  // A default log resource is added for some GCP environments
  // This log resource can be overwritten per spec:
  // https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource
  resource: {
    type: 'global',
  },
};

const message = {
  name: 'King Arthur',
  quest: 'Find the Holy Grail',
  favorite_color: 'Blue',
};

const json_Entry = log.entry(metadata, message);

async function writeLogEntry() {
  // Asynchronously write the log entry
  await log.write(text_entry);

  // Asynchronously batch write the log entries
  await log.write([text_entry, json_Entry]);

  // Let the logging library dispatch logs
  log.write(text_entry);

  console.log(`Wrote to ${logName}`);
}
writeLogEntry();

PHP

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Logging\LoggingClient;
use Google\Cloud\Logging\Logger;

/** Write a log message via the Stackdriver Logging API.
 *
 * @param string $projectId The Google project ID.
 * @param string $loggerName The name of the logger.
 * @param string $message The log message.
 */
function write_log($projectId, $loggerName, $message)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $logger = $logging->logger($loggerName, [
        'resource' => [
            'type' => 'gcs_bucket',
            'labels' => [
                'bucket_name' => 'my_bucket'
            ]
        ]
    ]);
    $entry = $logger->entry($message, [
        'severity' => Logger::INFO
    ]);
    $logger->write($entry);
    printf("Wrote a log to a logger '%s'." . PHP_EOL, $loggerName);
}

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


For step-by-step guidance on running this code directly in Cloud Shell Editor:

  1. Click Guide me.

  2. You see a panel Learn. Click Start to follow the tutorial.

Guide me

def write_entry(logger_name):
    """Writes log entries to the given logger."""
    logging_client = logging.Client()

    # This log can be found in the Cloud Logging console under 'Custom Logs'.
    logger = logging_client.logger(logger_name)

    # Make a simple text log
    logger.log_text("Hello, world!")

    # Simple text log with severity.
    logger.log_text("Goodbye, world!", severity="WARNING")

    # Struct log. The struct can be any JSON-serializable dictionary.
    logger.log_struct(
        {
            "name": "King Arthur",
            "quest": "Find the Holy Grail",
            "favorite_color": "Blue",
        },
        severity="INFO",
    )

    print("Wrote logs to {}.".format(logger.name))

Ruby

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

entry = logging.entry
# payload = "The data you want to log"
entry.payload = payload
# log_name = "The name of the log to write to"
entry.log_name = log_name
entry.severity = :NOTICE
entry.resource.type = "gae_app"
entry.resource.labels[:module_id] = "default"
entry.resource.labels[:version_id] = "20160101t163030"

logging.write_entries entry
puts "Wrote payload: #{entry.payload} to log: #{entry.log_name}"

Write standard logs

Some libraries support writing structured logs using the standard library logging syntax native to the language. This example demonstrates how to reconfigure the standard log-writing interface to write to Cloud Logging.

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// Sample stdlogging writes log.Logger logs to the Cloud Logging.
package main

import (
	"context"
	"log"

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

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

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the log to write to.
	logName := "my-log"

	logger := client.Logger(logName).StandardLogger(logging.Info)

	// Logs "hello world", log entry is visible at
	// Cloud Logs.
	logger.Println("hello world")
}

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# Imports the Cloud Logging client library
import google.cloud.logging

# Instantiates a client
client = google.cloud.logging.Client()

# Retrieves a Cloud Logging handler based on the environment
# you're running in and integrates the handler with the
# Python logging module. By default this captures all logs
# at INFO level and higher
client.setup_logging()

# Imports Python standard library logging
import logging

# The data to log
text = "Hello, world!"

# Emits the data using the standard logging module
logging.warning(text)

print("Logged: {}".format(text))

Write request logs

This sample demonstrates logging a supported HttpRequest datatype to Logging.

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// Writes an advanced log entry to Cloud Logging.
package main

import (
	"context"
	"log"
	"net/http"
	"os"

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

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

	// Creates a client.
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	client, err := logging.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the log to write to.
	logger := client.Logger("my-log")

	// Logs a basic entry.
	logger.Log(logging.Entry{Payload: "hello world"})

	// TODO(developer): replace with your request value.
	r, err := http.NewRequest("GET", "http://example.com", nil)

	// Logs an HTTPRequest type entry.
	// Some request metadata will be autopopulated in the log entry.
	httpEntry := logging.Entry{
		Payload: "optional message",
		HTTPRequest: &logging.HTTPRequest{
			Request: r,
		},
	}
	logger.Log(httpEntry)
}

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.HttpRequest;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload;
import com.google.cloud.logging.Severity;
import java.util.Collections;

/** Write LogEntry with HTTP request using the Cloud Logging API. */
public class LogEntryWriteHttpRequest {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String logName = "log-name"; // i.e "my-log"
    String payLoad = "payload"; // i.e "Hello world!"
    HttpRequest httpRequest =
        HttpRequest.newBuilder()
            .setRequestUrl("www.example.com")
            .setRequestMethod(HttpRequest.RequestMethod.GET) // Supported method GET,POST,PUT,HEAD
            .setStatus(200)
            .build();
    createLogEntryRequest(logName, payLoad, httpRequest);
  }

  public static void createLogEntryRequest(String logName, String payLoad, HttpRequest httpRequest)
      throws Exception {
    // Instantiates a logging client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {
      // create an instance of LogEntry with HTTP request
      LogEntry logEntry =
          LogEntry.newBuilder(Payload.StringPayload.of(payLoad))
              .setSeverity(Severity.ERROR)
              .setLogName(logName)
              .setHttpRequest(httpRequest)
              .setResource(MonitoredResource.newBuilder("global").build())
              .build();

      // Writes the log entry asynchronously
      logging.write(Collections.singleton(logEntry));
      System.out.printf("Logged: %s", payLoad);
    }
  }
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/*
const projectId = 'YOUR_PROJECT_ID'; // Your Google Cloud Platform project ID
const logName = 'my-log'; // The name of the log to write to
const requestMethod = 'GET'; // GET, POST, PUT, etc.
const requestUrl = 'http://www.google.com';
const status = 200;
const userAgent = `my-user-agent/1.0.0`;
const latencySeconds = 3;
const responseSize = 256; // response size in bytes.
*/

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging({projectId});

// Selects the log to write to
const log = logging.log(logName);

// The data to write to the log
const text = 'Hello, world!';

// The metadata associated with the entry
const metadata = {
  resource: {type: 'global'},
  httpRequest: {
    requestMethod,
    requestUrl,
    status,
    userAgent,
    latency: {
      seconds: latencySeconds,
    },
    responseSize,
  },
};

// Prepares a log entry
const entry = log.entry(metadata, text);

// Writes the log entry
async function writeLog() {
  await log.write(entry);
  console.log(`Logged: ${text}`);
}
writeLog();

List log entries

This sample demonstrates listing the log entries of a given logger. The log names returned are in resource format; they are URL-encoded and the log names are prefixed by /projects/PROJECT_ID/logs/.

C#

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

private void ListLogEntries(string logId)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    ProjectName projectName = new ProjectName(s_projectId);
    var results = client.ListLogEntries(Enumerable.Repeat(projectName, 1), $"logName={logName.ToString()}",
        "timestamp desc", callSettings: _retryAWhile);
    foreach (var row in results)
    {
        Console.WriteLine($"{row.TextPayload.Trim()}");
    }
}

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"log"
	"time"

	"cloud.google.com/go/logging"
	"cloud.google.com/go/logging/logadmin"
	"google.golang.org/api/iterator"
)

func getEntries(projectID string) ([]*logging.Entry, error) {
	ctx := context.Background()
	adminClient, err := logadmin.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create logadmin client: %v", err)
	}
	defer adminClient.Close()

	var entries []*logging.Entry
	const name = "log-example"
	lastHour := time.Now().Add(-1 * time.Hour).Format(time.RFC3339)

	iter := adminClient.Entries(ctx,
		// Only get entries from the "log-example" log within the last hour.
		logadmin.Filter(fmt.Sprintf(`logName = "projects/%s/logs/%s" AND timestamp > "%s"`, projectID, name, lastHour)),
		// Get most recent entries first.
		logadmin.NewestFirst(),
	)

	// Fetch the most recent 20 entries.
	for len(entries) < 20 {
		entry, err := iter.Next()
		if err == iterator.Done {
			return entries, nil
		}
		if err != nil {
			return nil, err
		}
		entries = append(entries, entry)
	}
	return entries, nil
}

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.api.gax.paging.Page;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.Logging.EntryListOption;
import com.google.cloud.logging.LoggingOptions;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

public class ListLogEntries {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace the variable value with valid log name before running the sample
    // or provide it as an argument.
    String logName = args.length > 0 ? args[0] : "test-log";

    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

      // When composing a filter, using indexed fields, such as timestamp, resource.type, logName
      // and
      // others can help accelerate the results
      // Full list of indexed fields here:
      // https://cloud.google.com/logging/docs/view/advanced-queries#finding-quickly
      // This sample restrict the results to only last minute to minimize number of API calls
      Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
      calendar.add(Calendar.MINUTE, -1);
      DateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      String logFilter =
          "logName=projects/"
              + logging.getOptions().getProjectId()
              + "/logs/"
              + logName
              + " AND timestamp>=\""
              + rfc3339.format(calendar.getTime())
              + "\"";

      // List all log entries
      Page<LogEntry> entries = logging.listLogEntries(EntryListOption.filter(logFilter));
      while (entries != null) {
        for (LogEntry logEntry : entries.iterateAll()) {
          System.out.println(logEntry);
        }
        entries = entries.getNextPage();
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging();

/**
 * TODO(developer): Uncomment the following line to run the code.
 */
// const logName = 'Name of the log from which to list entries, e.g. my-log';

const log = logging.log(logName);

async function printEntryMetadata() {
  // List the most recent entries for a given log
  // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
  const [entries] = await log.getEntries();
  console.log('Logs:');
  entries.forEach(entry => {
    const metadata = entry.metadata;
    console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
  });
}
printEntryMetadata();

PHP

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Logging\LoggingClient;

/**
 * Print the timestamp and entry for the project and logger.
 *
 * @param string $projectId The Google project ID.
 * @param string $loggerName The name of the logger.
 */
function list_entries($projectId, $loggerName)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $loggerFullName = sprintf('projects/%s/logs/%s', $projectId, $loggerName);
    $oneDayAgo = date(\DateTime::RFC3339, strtotime('-24 hours'));
    $filter = sprintf(
        'logName = "%s" AND timestamp >= "%s"',
        $loggerFullName,
        $oneDayAgo
    );
    $options = [
        'filter' => $filter,
    ];
    $entries = $logging->entries($options);

    // Print the entries
    foreach ($entries as $entry) {
        /* @var $entry \Google\Cloud\Logging\Entry */
        $entryInfo = $entry->info();
        if (isset($entryInfo['textPayload'])) {
            $entryText = $entryInfo['textPayload'];
        } else {
            $entryPayload = [];
            foreach ($entryInfo['jsonPayload'] as $key => $value) {
                $entryPayload[] = "$key: $value";
            }
            $entryText = '{' . implode(', ', $entryPayload) . '}';
        }
        printf('%s : %s' . PHP_EOL, $entryInfo['timestamp'], $entryText);
    }
}

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def list_entries(logger_name):
    """Lists the most recent entries for a given logger."""
    logging_client = logging.Client()
    logger = logging_client.logger(logger_name)

    print("Listing entries for logger {}:".format(logger.name))

    for entry in logger.list_entries():
        timestamp = entry.timestamp.isoformat()
        print("* {}: {}".format(timestamp, entry.payload))

Ruby

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/logging"

# log_name = "my_log_name"
logging = Google::Cloud::Logging.new
entries = logging.entries filter: "logName:#{log_name}",
                          max:    1000,
                          order:  "timestamp desc"

entries.each do |entry|
  puts "[#{entry.timestamp}] #{entry.log_name} #{entry.payload.inspect}"
end

There are also other ways to view your log entries in Logging:

Tail log entries

Live tailing lets you view your log entries in real time as Cloud Logging writes them. For information on the API method for live tailing, see the entries.tail method.

This sample demonstrates live tailing log entries of a given logger.

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"fmt"
	"io"

	logging "cloud.google.com/go/logging/apiv2"
	loggingpb "google.golang.org/genproto/googleapis/logging/v2"
)

// tailLogs creates a channel to stream log entries that were recently ingested for a project
func tailLogs(projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	client, err := logging.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient error: %w", err)
	}
	defer client.Close()

	stream, err := client.TailLogEntries(ctx)
	if err != nil {
		return fmt.Errorf("TailLogEntries error: %w", err)
	}
	defer stream.CloseSend()

	req := &loggingpb.TailLogEntriesRequest{
		ResourceNames: []string{
			"projects/" + projectID,
		},
	}
	if err := stream.Send(req); err != nil {
		return fmt.Errorf("stream.Send error: %w", err)
	}

	// read and print two or more streamed log entries
	for counter := 0; counter < 2; {
		resp, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("stream.Recv error: %w", err)
		}
		fmt.Printf("received:\n%v\n", resp)
		if resp.Entries != nil {
			counter += len(resp.Entries)
		}
	}
	return nil
}

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.LogEntryServerStream;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.Logging.TailOption;
import com.google.cloud.logging.LoggingOptions;

public class TailLogEntries {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Optionally provide the logname as an argument.
    String logName = args.length > 0 ? args[0] : "";

    LoggingOptions options = LoggingOptions.getDefaultInstance();
    try (Logging logging = options.getService()) {

      // Optionally compose a filter to tail log entries only from specific log
      LogEntryServerStream stream;

      if (logName != "") {
        stream =
            logging.tailLogEntries(
                TailOption.filter(
                    "logName=projects/" + options.getProjectId() + "/logs/" + logName));
      } else {
        stream = logging.tailLogEntries();
      }
      System.out.println("start streaming..");
      for (LogEntry log : stream) {
        System.out.println(log);
        // cancel infinite streaming after receiving first entry
        stream.cancel();
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

/**
 * TODO(developer): Replace logName with the name of your log.
 */
const log = logging.log(logName);
console.log('running tail log entries test');

const stream = log
  .tailEntries({
    filter: 'timestamp > "2021-01-01T23:00:00Z"',
  })
  .on('error', console.error)
  .on('data', resp => {
    console.log(resp.entries);
    console.log(resp.suppressionInfo);
    // If you anticipate many results, you can end a stream early to prevent
    // unnecessary processing and API requests.
    stream.end();
  })
  .on('end', () => {
    console.log('log entry stream has ended');
  });

// Note: to get all project logs, invoke logging.tailEntries

Logs

A log, also called a log stream, is the set of log entries that have the same full resource name. The full resource name is equivalent to the LogName field in the LogEntry. For general information about logs, see Cloud Logging overview.

List logs

This example demonstrates listing the names of available Logs.

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging();

async function printLogNames() {
  const [logs] = await logging.getLogs();
  console.log('Logs:');
  logs.forEach(log => {
    console.log(log.name);
  });
}
printLogNames();

Java

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.api.gax.paging.Page;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;

public class ListLogs {

  public static void main(String... args) throws Exception {

    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

      // List all log names
      Page<String> logNames = logging.listLogs();
      while (logNames != null) {
        for (String logName : logNames.iterateAll()) {
          System.out.println(logName);
        }
        logNames = logNames.getNextPage();
      }
    }
  }
}

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from typing import List
from google.cloud import logging_v2


def list_logs(project_id: str) -> List[str]:
    """Lists all logs in a project.

    Args:
        project_id: the ID of the project

    Returns:
        A list of log names.
    """
    client = logging_v2.services.logging_service_v2.LoggingServiceV2Client()
    request = logging_v2.types.ListLogsRequest(
        parent=f"projects/{project_id}",
    )

    logs = client.list_logs(request=request)
    for log in logs:
        print(log)

    return logs

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/logging/logadmin"
	"google.golang.org/api/iterator"
)

// listLogs lists all available logs in the project.
func listLogs(w io.Writer, projectID string) error {
	ctx := context.Background()

	client, err := logadmin.NewClient(ctx, projectID)
	if err != nil {
		return err
	}
	defer client.Close()

	iter := client.Logs(ctx)
	for {
		log, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("List logs failed: %w", err)
		}
		fmt.Fprintf(w, "%s\n", log)
	}
	return nil
}

Delete a log

This example demonstrates deleting a log by deleting all of its existing log entries. A log with no entries does not appear in the list of Google Cloud project logs. Log entries can be explicitly deleted, or they can expire according to the Logging retention policy.

C#

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

private void DeleteLog(string logId)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    client.DeleteLog(logName, _retryAWhile);
    Console.WriteLine($"Deleted {logId}.");
}

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import (
	"context"
	"log"

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

func deleteLog(projectID string) error {
	ctx := context.Background()
	adminClient, err := logadmin.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create logadmin client: %v", err)
	}
	defer adminClient.Close()

	const name = "log-example"
	if err := adminClient.DeleteLog(ctx, name); err != nil {
		return err
	}
	return nil
}

Node.js

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging();

/**
 * TODO(developer): Uncomment the following line to run the code.
 */
// const logName = 'Name of the log to delete, e.g. my-log';

const log = logging.log(logName);

async function deleteLog() {
  // Deletes a logger and all its entries.
  // Note that a deletion can take several minutes to take effect.
  // See https://googleapis.dev/nodejs/logging/latest/Log.html#delete
  await log.delete();
  console.log(`Deleted log: ${logName}`);
}
deleteLog();

PHP

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Logging\LoggingClient;

/** Delete a logger and all its entries.
 *
 * @param string $projectId The Google project ID.
 * @param string $loggerName The name of the logger.
 */
function delete_logger($projectId, $loggerName)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $logger = $logging->logger($loggerName);
    $logger->delete();
    printf("Deleted a logger '%s'." . PHP_EOL, $loggerName);
}

Python

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def delete_logger(logger_name):
    """Deletes a logger and all its entries.

    Note that a deletion can take several minutes to take effect.
    """
    logging_client = logging.Client()
    logger = logging_client.logger(logger_name)

    logger.delete()

    print("Deleted all logging entries for {}".format(logger.name))

Ruby

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

# log_name = "The name of the log"
logging.delete_log log_name
puts "Deleted log: #{log_name}"

Log Sinks

You route logs by creating sinks that send certain log entries to specific destinations. For more information about sinks, see Routing and storage overview: Sinks.

Create a sink

C#

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

        private void CreateSink(string sinkId, string logId)
        {
            var sinkClient = ConfigServiceV2Client.Create();
            LogSink myLogSink = new LogSink();
            myLogSink.Name = sinkId;

            // This creates a sink using a Google Cloud Storage bucket 
            // named the same as the projectId.
            // This requires editing the bucket's permissions to add the Entity Group 
            // named 'cloud-logs@google.com' with 'Owner' access for the bucket.
            // If this is being run with a Google Cloud service account,
            // that account will need to be granted 'Owner' access to the Project.
            // In Powershell, use this command:
            // PS > Add-GcsBucketAcl <your-bucket-name> -Role OWNER -Group cloud-logs@google.com
            myLogSink.Destination = "storage.googleapis.com/" + s_projectId;
            LogName logName = new LogName(s_projectId, logId);
            myLogSink.Filter = $"logName={logName.ToString()}AND severity<=ERROR";
            ProjectName projectName = new ProjectName(s_projectId);
            sinkClient.CreateSink(projectName, myLogSink, _retryAWhile);
            Console.WriteLine($"Created sink: {sinkId}.");
        }

Go

To learn how to install and use the client library for Logging, see Logging client libraries.

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.