列表

演示如何列出日志条目。

包含此代码示例的文档页面

如需查看上下文中使用的代码示例,请参阅以下文档:

代码示例

C#

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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

如需了解如何安装和使用 Logging 客户端库,请参阅 Logging 客户端库

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