Writing Logs

This page includes some code samples for writing and managing logs. 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#

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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);
    IEnumerable<string> projectIds = new string[] { projectName.ToString() };
    var results = client.ListLogEntries(projectIds, $"logName={logName.ToString()}",
        "timestamp desc", callSettings: RetryAWhile);
    foreach (var row in results)
    {
        Console.WriteLine($"{row.TextPayload.Trim()}");
    }
}

Go

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

var entries []*logging.Entry
const name = "log-example"
iter := adminClient.Entries(ctx,
	// Only get entries from the log-example log.
	logadmin.Filter(fmt.Sprintf(`logName = "projects/%s/logs/%s"`, projID, name)),
	// 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

Page<LogEntry> entries = logging.listLogEntries(EntryListOption.filter(filter));
for (LogEntry entry : entries.iterateAll()) {
  // do something with the entry
}

Node.js

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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);

// List the most recent entries for a given log
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
log
  .getEntries()
  .then(results => {
    const entries = results[0];

    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

/** 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new project: "my-gcp-project-id"
entries = logging.entries filter: 'resource.type = "gae_app"'

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

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#

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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
    {
        LogName = logName.ToString(),
        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(LogNameOneof.From(logName), resource, entryLabels,
        new[] { logEntry }, RetryAWhile);
    Console.WriteLine($"Created log entry in log-id: {logId}.");
}

Go

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

const name = "log-example"
logger := client.Logger(name)
defer logger.Flush() // Ensure the entry is written.

infolog := logger.StandardLogger(logging.Info)
infolog.Printf("infolog is a standard Go log.Logger with INFO severity.")

Java

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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: resource}, 'Hello, world!');

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

// 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.
log
  .write([entry, secondEntry])
  .then(() => {
    console.log(`Wrote to ${logName}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

/** 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new project: "my-gcp-project-id"

entry = logging.entry
entry.log_name = "my_application_log"
entry.payload  = "Log message"
entry.severity = :NOTICE
entry.resource.type = "gae_app"
entry.resource.labels[:module_id] = "default"
entry.resource.labels[:version_id] = "20160101t163030"

logging.write_entries entry

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 Stackdriver Logging retention policy. If you write new entries to the log, it will reappear.

C#

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

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

Go

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

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

Java

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

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

Node.js

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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);

// Deletes a logger and all its entries.
// Note that a deletion can take several minutes to take effect.
// See https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging/log?method=delete
log
  .delete()
  .then(() => {
    console.log(`Deleted log: ${logName}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

/** 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver 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

For more on installing and creating a Stackdriver Logging client, refer to Stackdriver Logging Client Libraries.

require "google/cloud/logging"

logging = Google::Cloud::Logging.new project: "my-gcp-project-id"

logging.delete_log "my_application_log"

Send feedback about...

Stackdriver Logging