로그 항목 테일링

실시간 로그 항목을 테일링하는 방법을 보여줍니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Go

Logging용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Logging 클라이언트 라이브러리를 참조하세요.

Logging에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	logging "cloud.google.com/go/logging/apiv2"
	loggingpb "google.golang.org/genproto/googleapis/logging/v2"
)

// tailLogs creates a channel to stream log entries that were recently ingested for a project
func tailLogs(projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	client, err := logging.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient error: %w", err)
	}
	defer client.Close()

	stream, err := client.TailLogEntries(ctx)
	if err != nil {
		return fmt.Errorf("TailLogEntries error: %w", err)
	}
	defer stream.CloseSend()

	req := &loggingpb.TailLogEntriesRequest{
		ResourceNames: []string{
			"projects/" + projectID,
		},
	}
	if err := stream.Send(req); err != nil {
		return fmt.Errorf("stream.Send error: %w", err)
	}

	// read and print two or more streamed log entries
	for counter := 0; counter < 2; {
		resp, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("stream.Recv error: %w", err)
		}
		fmt.Printf("received:\n%v\n", resp)
		if resp.Entries != nil {
			counter += len(resp.Entries)
		}
	}
	return nil
}

Java

Logging용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Logging 클라이언트 라이브러리를 참조하세요.

Logging에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.LogEntryServerStream;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.Logging.TailOption;
import com.google.cloud.logging.LoggingOptions;

public class TailLogEntries {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Optionally provide the logname as an argument.
    String logName = args.length > 0 ? args[0] : "";

    LoggingOptions options = LoggingOptions.getDefaultInstance();
    try (Logging logging = options.getService()) {

      // Optionally compose a filter to tail log entries only from specific log
      LogEntryServerStream stream;

      if (logName != "") {
        stream =
            logging.tailLogEntries(
                TailOption.filter(
                    "logName=projects/" + options.getProjectId() + "/logs/" + logName));
      } else {
        stream = logging.tailLogEntries();
      }
      System.out.println("start streaming..");
      for (LogEntry log : stream) {
        System.out.println(log);
        // cancel infinite streaming after receiving first entry
        stream.cancel();
      }
    }
  }
}

Node.js

Logging용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Logging 클라이언트 라이브러리를 참조하세요.

Logging에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const {Logging} = require('@google-cloud/logging');
const logging = new Logging();

/**
 * TODO(developer): Replace logName with the name of your log.
 */
const log = logging.log(logName);
console.log('running tail log entries test');

const stream = log
  .tailEntries({
    filter: 'timestamp > "2021-01-01T23:00:00Z"',
  })
  .on('error', console.error)
  .on('data', resp => {
    console.log(resp.entries);
    console.log(resp.suppressionInfo);
    // If you anticipate many results, you can end a stream early to prevent
    // unnecessary processing and API requests.
    stream.end();
  })
  .on('end', () => {
    console.log('log entry stream has ended');
  });

// Note: to get all project logs, invoke logging.tailEntries

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.