Logging Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Stackdriver Logging API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.Logging.V2

Go

go get -u cloud.google.com/go/logging

Java

For more information, see Setting Up a Java Development Environment. 如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-logging</artifactId>
  <version>1.61.0</version>
</dependency>
如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:
compile 'com.google.cloud:google-cloud-logging:1.61.0'
如果您使用的是 SBT,请将以下代码添加到您的依赖项中:
libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "1.61.0"

如果您使用的是 IntelliJ 或 Eclipse,请通过以下 IDE 插件将客户端库添加到您的项目中:

上述插件还提供其他功能,例如服务帐号密钥管理。如需了解详情,请参阅各个插件相应的文档。

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/logging

PHP

composer require google/cloud-logging

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-logging

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 more information, see the GCP authentication documentation .

GCP Console

  1. 在 GCP Console 中,转到创建服务帐号密钥页面。

    转到“创建服务帐号密钥”页面
  2. 服务帐号列表中,选择新的服务帐号
  3. 服务帐号名称字段中,输入一个名称。
  4. 角色列表中,选择项目 > 所有者

    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  5. 点击创建。包含密钥的 JSON 文件就会下载到计算机。

命令行

您可以使用本地计算机上的 Cloud SDK 或在 Cloud Shell 中运行以下命令。

  1. 创建服务帐号。将 [NAME] 替换为服务帐号的名称。

    gcloud iam service-accounts create [NAME]
  2. 向服务帐号授予权限。将 [PROJECT_ID] 替换为您的项目 ID。

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    注意角色字段为您的服务帐号授予资源访问权限。稍后您可以使用 GCP Console 查看和更改此字段。如果您开发的是正式版应用,请指定比项目 > 所有者更为精细的权限。如需了解详情,请参阅为服务帐号授予角色
  3. 生成密钥文件。将 [FILE_NAME] 替换为密钥文件的名称。

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

通过设置环境变量 GOOGLE_APPLICATION_CREDENTIALS,向您的应用代码提供身份验证凭据。将 [PATH] 替换为包含服务帐号密钥的 JSON 文件的文件路径,将 [FILE_NAME] 替换为文件名。此变量仅适用于当前的 shell 会话,因此,如果您打开新的会话,请重新设置该变量。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示符:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

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);
            LogNameOneof logNameToWrite = LogNameOneof.From(logName);
            logEntry.LogName = logName.ToString();
            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();
            resource.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(logNameToWrite, resource, entryLabels, logEntries);

            Console.WriteLine("Log Entry created.");
        }
    }
}

Go

// Sample logging-quickstart writes a log entry to Stackdriver 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 Stackdriver Logging
	// service.
	if err := client.Close(); err != nil {
		log.Fatalf("Failed to close client: %v", err)
	}

	fmt.Printf("Logged: %v\n", text)
}

Java

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 Stackdriver Logging API.
 * The library also offers a java.util.logging Handler `com.google.cloud.logging.LoggingHandler`
 * Logback integration is also available : https://goo.gl/DNMoRh
 * Using the java.util.logging handler / Logback appender should be preferred to using the API
 * directly.
 */
public class QuickstartSample {

  /** Expects a new or existing Stackdriver 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

async function quickstart(
  projectId = 'YOUR_PROJECT_ID', // Your Google Cloud Platform project ID
  logName = 'my-log' // The name of the log to write to
) {
  // 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'},
  };

  // Prepares a log entry
  const entry = log.entry(metadata, text);

  // Writes the log entry
  await log.write(entry);
  console.log(`Logged: ${text}`);
}

PHP

# 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

# 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

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

Additional Resources

此页内容是否有用?请给出您的反馈和评价:

发送以下问题的反馈:

此网页
Stackdriver Logging
需要帮助?请访问我们的支持页面