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

Installing the client library

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 -u 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>20.1.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>2.2.0</version>
</dependency>

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

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

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

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

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

If you're using 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

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

Create a service account:

  1. In the Cloud Console, go to the Create service account page.

    Go to Create service account
  2. Select a project.
  3. In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name.

    In the Service account description field, enter a description. For example, Service account for quickstart.

  4. Click Create.
  5. Click the Select a role field.

    Under Quick access, click Basic, then click Owner.

  6. Click Continue.
  7. Click Done to finish creating the service account.

    Do not close your browser window. You will use it in the next step.

Create a service account key:

  1. In the Cloud Console, click the email address for the service account that you created.
  2. Click Keys.
  3. Click Add key, then click Create new key.
  4. Click Create. A JSON key file is downloaded to your computer.
  5. Click Close.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace NAME with a name for the service account.

    gcloud iam service-accounts create NAME
  2. Grant permissions to the service account. Replace PROJECT_ID with your project ID.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Generate the key file. Replace FILE_NAME with a name for the key file.

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\my-key.json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using 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 the Logging Client Libraries.


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 the Logging Client Libraries.


// 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 the Logging Client Libraries.

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 {

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

    // The name of the log to write to
    String logName = args[0]; // "my-log";

    // The data to write to the log
    String text = "Hello, world!";

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

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

    System.out.printf("Logged: %s%n", text);
  }
}

Node.js

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

// 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 the Logging Client Libraries.

# 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 the Logging Client Libraries.

# 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 the Logging Client Libraries.

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

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

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

# Prepares a log entry
entry = logging.entry
# The data to log
entry.payload = "Hello, world!"
# The name of the log to write to
entry.log_name = "my-log"
# 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 in structured format, with fields like resource, sourceLocation, labels, and trace that give additional context to each log. For more information about log entries, see Basic concepts.

Write structured logs

This sample demonstrates writing log entries.

C#

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

private void WriteLogEntry(string logId, string message)
{
    var client = LoggingServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    LogEntry logEntry = new LogEntry
    {
        LogNameAsLogName = logName,
        Severity = LogSeverity.Info,
        TextPayload = $"{typeof(LoggingSample).FullName} - {message}"
    };
    MonitoredResource resource = new MonitoredResource { Type = "global" };
    IDictionary<string, string> entryLabels = new Dictionary<string, string>
    {
        { "size", "large" },
        { "color", "red" }
    };
    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 the Logging Client Libraries.

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 the Logging Client Libraries.

List<LogEntry> entries = new ArrayList<>();
entries.add(LogEntry.of(StringPayload.of("Entry payload")));
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("key", "value");
entries.add(LogEntry.of(JsonPayload.of(jsonMap)));
logging.write(
    entries,
    WriteOption.logName(logName),
    WriteOption.resource(MonitoredResource.newBuilder("global").build()));

Node.js

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

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() {
  // Synchronously write the log entry
  await log.write(text_entry);

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

  // Asynchronously 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 the Logging Client Libraries.

use Google\Cloud\Logging\LoggingClient;

/** 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);
    $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 the Logging Client Libraries.

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="ERROR")

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

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

Ruby

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

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 the Logging Client Libraries.


// 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 the Logging Client Libraries.

# 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.get_default_handler()
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 the Logging Client Libraries.


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

Node.js

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

/*
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 the Logging Client Libraries.

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 the Logging Client Libraries.

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"`, projID, 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 the Logging Client Libraries.

// Instantiates a client
LoggingOptions options = LoggingOptions.getDefaultInstance();

String logName = args[0];

try (Logging logging = options.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
  // Below we are restricting the results to only last hour to speedup getting the results back
  Calendar calendar = Calendar.getInstance();
  calendar.add(Calendar.HOUR, -1);
  DateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
  String logFilter = "logName=projects/" + options.getProjectId() + "/logs/" + logName
      + " AND timestamp>=\"" + rfc3339.format(calendar.getTime()) + "\"";

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

Node.js

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

// 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 the Logging Client Libraries.

use Google\Cloud\Logging\LoggingClient;

/** Return an iterator for listing log entries.
 *
 * @param string $projectId The Google project ID.
 * @param string $loggerName The name of the logger.
 * @return ItemIterator<Google\Cloud\Logging\Entry>
 */
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 the Logging Client Libraries.

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 the Logging Client Libraries.

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.

Node.js

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

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 more information about logs, see Available Logs and Basic concepts.

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 the Logging Client Libraries.

// 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();

Delete a log

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

C#

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

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 the Logging Client Libraries.

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

Java

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

boolean deleted = logging.deleteLog(logName);
if (deleted) {
  // the log was deleted
} else {
  // the log was not found
}

Node.js

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

// 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 the Logging Client Libraries.

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 the Logging Client Libraries.

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 the Logging Client Libraries.

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 Logs exports.

Create a sink

C#

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

        private void CreateSink(string sinkId, string logId)
        {
            var sinkClient = ConfigServiceV2Client.Create();
            CreateSinkRequest sinkRequest = new CreateSinkRequest();
            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);
            sinkRequest.Sink = myLogSink;
            sinkClient.CreateSink(projectName, myLogSink, _retryAWhile);
            Console.WriteLine($"Created sink: {sinkId}.");
        }

Go

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

ctx := context.Background()
_, err := client.CreateSink(ctx, &logadmin.Sink{
	ID:          "severe-errors-to-gcs",
	Destination: "storage.googleapis.com/logsinks-bucket",
	Filter:      "severity >= ERROR",
})

Java

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

SinkInfo sinkInfo = SinkInfo.of(sinkName, DatasetDestination.of(datasetName));
Sink sink = logging.create(sinkInfo);

Node.js

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

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

// Creates clients
const logging = new Logging();
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines to run the code.
 */
// const sinkName = 'Name of your sink, e.g. my-sink';
// const bucketName = 'Desination bucket, e.g. my-bucket';
// const filter = 'Optional log filer, e.g. severity=ERROR';

// The destination can be a Cloud Storage bucket, a Cloud Pub/Sub topic,
// or a BigQuery dataset. In this case, it is a Cloud Storage Bucket.
// See https://cloud.google.com/logging/docs/api/tasks/exporting-logs for
// information on the destination format.
const destination = storage.bucket(bucketName);
const sink = logging.sink(sinkName);

/**
 * The filter determines which logs this sink matches and will be exported
 * to the destination. For example a filter of 'severity>=INFO' will send
 * all logs that have a severity of INFO or greater to the destination.
 * See https://cloud.google.com/logging/docs/view/advanced_filters for more
 * filter information.
 */
const config = {
  destination: destination,
  filter: filter,
};

async function createSink() {
  // See https://googleapis.dev/nodejs/logging/latest/Sink.html#create
  await sink.create(config);
  console.log(`Created sink ${sinkName} to ${bucketName}`);
}
createSink();

PHP

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

/** Create a log sink.
 *
 * @param string $projectId The Google project ID.
 * @param string $sinkName The name of the sink.
 * @param string $destination The destination of the sink.
 * @param string $filterString The filter for the sink.
 */
function create_sink($projectId, $sinkName, $destination, $filterString)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $logging->createSink(
        $sinkName,
        $destination,
        ['filter' => $filterString]
    );
    printf("Created a sink '%s'." . PHP_EOL, $sinkName);
}

Python

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

def create_sink(sink_name, destination_bucket, filter_):
    """Creates a sink to export logs to the given Cloud Storage bucket.

    The filter determines which logs this sink matches and will be exported
    to the destination. For example a filter of 'severity>=INFO' will send
    all logs that have a severity of INFO or greater to the destination.
    See https://cloud.google.com/logging/docs/view/advanced_filters for more
    filter information.
    """
    logging_client = logging.Client()

    # The destination can be a Cloud Storage bucket, a Cloud Pub/Sub topic,
    # or a BigQuery dataset. In this case, it is a Cloud Storage Bucket.
    # See https://cloud.google.com/logging/docs/api/tasks/exporting-logs for
    # information on the destination format.
    destination = "storage.googleapis.com/{bucket}".format(bucket=destination_bucket)

    sink = logging_client.sink(sink_name, filter_=filter_, destination=destination)

    if sink.exists():
        print("Sink {} already exists.".format(sink.name))
        return

    sink.create()
    print("Created sink {}".format(sink.name))

Ruby

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

require "google/cloud/logging"

logging = Google::Cloud::Logging.new
storage = Google::Cloud::Storage.new
# bucket_name = "name-of-my-storage-bucket"
bucket  = storage.create_bucket bucket_name

# Grant owner permission to Cloud Logging service
email = "cloud-logs@google.com"
bucket.acl.add_owner "group-#{email}"

# sink_name = "name-of-my-sink"
sink = logging.create_sink sink_name, "storage.googleapis.com/#{bucket.id}"
puts "#{sink.name}: #{sink.filter} -> #{sink.destination}"

Get a sink

Java

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

import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Sink;

/** Retrieve Cloud Logging Sink metadata. */
public class GetSinkMetadata {
  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    // The Name of your sink
    String sinkName = "sink-name"; // i.e my-sink

    getSinkMetadata(sinkName);
  }

  public static void getSinkMetadata(String sinkName) throws Exception {
    // Instantiates a logging client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {

      Sink sink = logging.getSink(sinkName);

      // print sink metadata
      System.out.println("Name:" + sink.getName());
      System.out.println("Version Format:" + sink.getVersionFormat());
      System.out.println("Filter:" + sink.getFilter());
      System.out.println("Destination:" + sink.getDestination());
    }
  }
}

Node.js

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

// 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 sinkName = 'Name of your sink, e.g. my-sink';

const sink = logging.sink(sinkName);

async function printSinkMetadata() {
  // See https://googleapis.dev/nodejs/logging/latest/Sink.html#getMetadata
  const [metadata] = await sink.getMetadata();
  console.log(`Name: ${metadata.name}`);
  console.log(`Destination: ${metadata.destination}`);
  console.log(`Filter: ${metadata.filter}`);
}
printSinkMetadata();

List sinks

C#

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

private void ListSinks()
{
    var sinkClient = ConfigServiceV2Client.Create();
    ProjectName projectName = new ProjectName(s_projectId);
    var listOfSinks = sinkClient.ListSinks(projectName, callSettings: _retryAWhile);
    foreach (var sink in listOfSinks)
    {
        Console.WriteLine($"{sink.Name} {sink.ToString()}");
    }
}

Go

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

ctx := context.Background()

var sinks []string
it := client.Sinks(ctx)
for {
	sink, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	sinks = append(sinks, sink.ID)
}

Java

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

Page<Sink> sinks = logging.listSinks(ListOption.pageSize(100));
for (Sink sink : sinks.iterateAll()) {
  // do something with the sink
}

Node.js

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

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

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

async function printSinkMetadata() {
  // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getSinks
  const [sinks] = await logging.getSinks();
  console.log('Sinks:');
  sinks.forEach(sink => {
    console.log(sink.name);
    console.log(`  Destination: ${sink.metadata.destination}`);
    console.log(`  Filter: ${sink.metadata.filter}`);
  });
}
printSinkMetadata();

PHP

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

/**
 * List log sinks.
 *
 * @param string $projectId
 * @return ItemIterator<Google\Cloud\Logging\Sink>
 */
function list_sinks($projectId)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $sinks = $logging->sinks();
    foreach ($sinks as $sink) {
        /* @var $sink \Google\Cloud\Logging\Sink */
        foreach ($sink->info() as $key => $value) {
            printf('%s:%s' . PHP_EOL,
                $key,
                is_string($value) ? $value : var_export($value, true)
            );
        }
        print PHP_EOL;
    }
}

Python

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

def list_sinks():
    """Lists all sinks."""
    logging_client = logging.Client()

    sinks = list(logging_client.list_sinks())

    if not sinks:
        print("No sinks.")

    for sink in sinks:
        print("{}: {} -> {}".format(sink.name, sink.filter_, sink.destination))

Ruby

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

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

logging.sinks.each do |sink|
  puts "#{sink.name}: #{sink.filter} -> #{sink.destination}"
end

Update a sink

C#

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

private void UpdateSinkLog(string sinkId, string logId)
{
    var sinkClient = ConfigServiceV2Client.Create();
    LogName logName = new LogName(s_projectId, logId);
    LogSinkName sinkName = new LogSinkName(s_projectId, sinkId);
    var sink = sinkClient.GetSink(sinkName, _retryAWhile);
    sink.Filter = $"logName={logName.ToString()}AND severity<=ERROR";
    sinkClient.UpdateSink(sinkName, sink, _retryAWhile);
    Console.WriteLine($"Updated {sinkId} to export logs from {logId}.");
}

Go

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

ctx := context.Background()
_, err := client.UpdateSink(ctx, &logadmin.Sink{
	ID:          "severe-errors-to-gcs",
	Destination: "storage.googleapis.com/logsinks-new-bucket",
	Filter:      "severity >= INFO",
})

Java

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

SinkInfo sinkInfo =
    SinkInfo.newBuilder(sinkName, DatasetDestination.of(datasetName))
        .setVersionFormat(SinkInfo.VersionFormat.V2)
        .setFilter("severity>=ERROR")
        .build();
Sink sink = logging.update(sinkInfo);

Node.js

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

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

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

/**
 * TODO(developer): Uncomment the following lines to run the code.
 */
// const sinkName = 'Name of sink to update, e.g. my-sink';
// const filter = 'New filter for the sink, e.g. severity >= WARNING';

const sink = logging.sink(sinkName);

/**
 * The filter determines which logs this sink matches and will be exported
 * to the destination. For example a filter of 'severity>=INFO' will send
 * all logs that have a severity of INFO or greater to the destination.
 * See https://cloud.google.com/logging/docs/view/advanced_filters for more
 * filter information.
 */
const metadataInfo = {
  filter: filter,
};

async function updateSink() {
  // See https://googleapis.dev/nodejs/logging/latest/Sink.html#setMetadata
  const [metadata] = await sink.setMetadata(metadataInfo);
  console.log(`Sink ${sinkName} updated.`, metadata);
}
updateSink();

PHP

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

/**
 * Update a log sink.
 *
 * @param string $projectId
 * @param string sinkName
 * @param string $filterString
 */
function update_sink($projectId, $sinkName, $filterString)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $sink = $logging->sink($sinkName);
    $sink->update(['filter' => $filterString]);
    printf("Updated a sink '%s'." . PHP_EOL, $sinkName);
}

Python

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

def update_sink(sink_name, filter_):
    """Changes a sink's filter.

    The filter determines which logs this sink matches and will be exported
    to the destination. For example a filter of 'severity>=INFO' will send
    all logs that have a severity of INFO or greater to the destination.
    See https://cloud.google.com/logging/docs/view/advanced_filters for more
    filter information.
    """
    logging_client = logging.Client()
    sink = logging_client.sink(sink_name)

    sink.reload()

    sink.filter_ = filter_
    print("Updated sink {}".format(sink.name))
    sink.update()

Ruby

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

require "google/cloud/logging"

logging = Google::Cloud::Logging.new
storage = Google::Cloud::Storage.new
# bucket_name = "name-of-my-storage-bucket"
bucket  = storage.create_bucket bucket_name
# sink_name = "name-of-my-sink"
sink    = logging.sink sink_name

sink.destination = "storage.googleapis.com/#{bucket.id}"

sink.save
puts "Updated sink destination for #{sink.name} to #{sink.destination}"

Delete a sink

C#

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

private void DeleteSink(string sinkId)
{
    var sinkClient = ConfigServiceV2Client.Create();
    LogSinkName sinkName = new LogSinkName(s_projectId, sinkId);
    sinkClient.DeleteSink(sinkName, _retryAWhile);
    Console.WriteLine($"Deleted {sinkId}.");
}

Go

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

ctx := context.Background()
if err := client.DeleteSink(ctx, "severe-errors-to-gcs"); err != nil {
	return err
}

Java

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

boolean deleted = logging.deleteSink(sinkName);
if (deleted) {
  // the sink was deleted
} else {
  // the sink was not found
}

Node.js

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

// 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 sinkName = 'Name of sink to delete, e.g. my-sink';

const sink = logging.sink(sinkName);

async function deleteSink() {
  // See https://googleapis.dev/nodejs/logging/latest/Sink.html#delete
  await sink.delete();
  console.log(`Sink ${sinkName} deleted.`);
}
deleteSink();

PHP

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

/** Delete a log sink.
 *
 * @param string $projectId The Google project ID.
 * @param string $sinkName The name of the sink.
 */
function delete_sink($projectId, $sinkName)
{
    $logging = new LoggingClient(['projectId' => $projectId]);
    $logging->sink($sinkName)->delete();
    printf("Deleted a sink '%s'." . PHP_EOL, $sinkName);
}

Python

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

def delete_sink(sink_name):
    """Deletes a sink."""
    logging_client = logging.Client()
    sink = logging_client.sink(sink_name)

    sink.delete()

    print("Deleted sink {}".format(sink.name))

Ruby

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

require "google/cloud/logging"

logging = Google::Cloud::Logging.new

# sink_name = "name-of-my-sink"
sink = logging.sink sink_name
sink.delete
puts "Deleted sink: #{sink.name}"

Additional resources

Additional client libraries

In addition to the libraries shown above, a set of integration libraries are available to support using popular third-party logging libraries with Cloud Logging.

Language Library
C# ASP.NET
C# log4Net
Java logback
Node bunyan
Node winston
PHP PSR-3
Ruby stackdriver