列出日志

演示如何列出可用日志的名称。

代码示例

Go

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

如需向 Logging 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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
}

Java

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

如需向 Logging 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

Node.js

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

如需向 Logging 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

Python

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

如需向 Logging 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器