Writing logs

This page includes some code samples for writing and managing logs in Cloud Logging. There are more code samples with the Client Libraries.

Listing logs entries

Here is some sample code to get a list of the log entries for a given logger. Because there can be many logs, the results are paginated. 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()) {

  String logFilter =
      "logName=projects/"
          + options.getProjectId()
          + "/logs/"
          + logName
          + " AND timestamp>=\"2020-09-01T00:00:00.000Z\"";

  // 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 Cloud Logging:

Writing log entries

Here is some sample code to write a single log entry to mylog. The service, region, labels, and other content will change depending on the entry and the application doing the writing.

If you write many log entries, it is better to batch multiple log entries into a single call to entries.write. This improves throughput and helps you avoid the quota limit on calls to entries.write.

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.

// 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 write to, e.g. my-log';

const log = logging.log(logName);

// Modify this resource to match a resource in your project
// See
// https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource
const resource = {
  // This example targets the "global" resource for simplicity
  type: 'global',
};

// A text log entry
const entry = log.entry({resource}, 'Hello, world!');

// A structured log entry
const secondEntry = log.entry(
  {resource: resource},
  {
    name: 'King Arthur',
    quest: 'Find the Holy Grail',
    favorite_color: 'Blue',
  }
);

async function writeLogEntry() {
  // Save the two log entries. You can write entries one at a time, but it is
  // best to write multiple entires together in a batch.
  await log.write([entry, secondEntry]);
  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}"

Creating logs

You create a new log by writing entries to the new log. There is no separate "create" operation.

Deleting logs

Here is some sample code to delete a log by deleting all its entries. A log with no entries does not appear in the list of project logs. Entries can be explicitly deleted, or they can expire according to the Logging retention policy. If you write new entries to the log, it will reappear.

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