Cloud Run Functions 로그 보기 및 쓰기
런타임 로그 작성
Cloud Run Functions에는 기본적으로 간단한 런타임 로깅이 포함되어 있습니다. stdout
또는 stderr
에 작성된 로그는 자동으로 Google Cloud 콘솔에 표시됩니다.
고급 로깅을 사용하려면 Cloud Logging 클라이언트 라이브러리를 사용합니다.
기본적으로 다음 스니펫에 표시된 것처럼 로그 페이로드는 단순 텍스트 문자열입니다. 문자열은 로그 항목의 textPayload
필드에 저장됩니다.
Node.js
대부분의 로그 항목에는 관련된 로그 수준이 없습니다. 예를 들면 다음과 같습니다.console.log()
,console.info()
,console.warn()
,console.error()
를 사용하여 내보낸 로그stdout
또는stderr
에 직접 작성된 로그
내부 시스템 메시지의 로그 수준은 DEBUG
입니다.
Python
- 표준 출력 또는 표준 오류에 대한 로그에는 관련된 로그 수준이 없습니다.
- 내부 시스템 메시지의 로그 수준은
DEBUG
입니다.
Go
stdout
또는stderr
에 대한 로그에는 관련된 로그 수준이 없습니다.- 내부 시스템 메시지의 로그 수준은
DEBUG
입니다.
자바
stdout
또는stderr
에 대한 로그에는 관련된 로그 수준이 없습니다.- 내부 시스템 메시지의 로그 수준은
DEBUG
입니다.
C#
using Google.Cloud.Functions.Framework; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace LogHelloWorld; public class Function : IHttpFunction { private readonly ILogger _logger; public Function(ILogger<Function> logger) => _logger = logger; public async Task HandleAsync(HttpContext context) { Console.WriteLine("I am a log to stdout!"); Console.Error.WriteLine("I am a log to stderr!"); _logger.LogInformation("I am an info log!"); _logger.LogWarning("I am a warning log!"); await context.Response.WriteAsync("Messages successfully logged!", context.RequestAborted); } }
stdout
(예:Console.WriteLine
을 통해) 및stderr
(예:Console.Error.WriteLine
을 통해)에 작성된 텍스트에는 로그 수준이 없습니다.- ASP.NET Core 로깅 수준은 다음과 같이 Cloud Logging 수준에 매핑됩니다.
LogLevel.Trace
및LogLevel.Debug map
는 Cloud LoggingDEBUG
에 매핑됩니다.LogLevel.Information
은 Cloud LoggingINFO
에 매핑됩니다.LogLevel.Warning
는 Cloud LoggingWARNING
에 매핑됩니다.LogLevel.Error
는 Cloud LoggingERROR
에 매핑됩니다.LogLevel.Critical
은 Cloud LoggingCRITICAL
에 매핑됩니다.
Ruby
로그 항목에는 관련된 로그 수준이 없습니다.
PHP
use Psr\Http\Message\ServerRequestInterface; function helloLogging(ServerRequestInterface $request): string { // Code running in Google Cloud Functions itself writes log entries to // Cloud Logging. (Default log severity level is INFO.) $log = fopen('php://stderr', 'wb'); fwrite($log, "Log entry from fwrite().\n"); // You can also specify a severity level explicitly using structured logs. // See this page for a list of log severity values: // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity fwrite($log, json_encode([ 'message' => 'Structured log with error severity', 'severity' => 'error' ]) . PHP_EOL); // This will log to standard error, which will appear in Cloud Logging error_log('error_log logs in Cloud Functions!'); // This will log an error message and immediately terminate the function execution // trigger_error('fatal errors are logged!'); // For HTTP functions, this is added to the HTTP response // For CloudEvent functions, this does nothing var_dump('var_dump goes to HTTP response for HTTP functions'); // You can also dump variables using var_export() and forward // the resulting string to Cloud Logging via an fwrite() call. $entry = var_export('var_export output can be captured.', true); fwrite($log, $entry); // Functions must return a String or PSR-7 Response object return ''; }
구조화된 로그 작성
위에서 설명한 기본 텍스트 로그에는 연결된 로그 수준이 없습니다.
로그 항목에 로그 수준이나 기타 특정 필드를 포함하려면 한 줄 형태의 직렬화된 JSON으로 stdout
또는 stderr
에 로그를 작성하면 됩니다. 이 줄은 Cloud Run Functions에서 감지 및 파싱하여 textPayload
대신 jsonPayload
필드에 배치합니다. 아래의 스니펫은 이러한 구조화된 로그를 작성하는 방법을 보여줍니다.
Node.js
Python
구조화된 로깅 지원은 Python 3.8 이상에서 사용할 수 있습니다.
Go
각 로그 항목의 구조는 Entry
유형으로 제공됩니다.
Entry 구조체가 로깅되면 String
메서드가 호출되어 Cloud Logging에서 예상하는 JSON 형식으로 마샬링합니다.
자바
logback.xml
구성에서 Logstash JSON 인코더를 사용 설정하여 Logback 및 SLF4J로 JSON 로깅을 사용 설정합니다.
메시지의 특수 JSON 필드 처리
구조화된 데이터를 JSON 딕셔너리로 제공하면 일부 특수 필드가 jsonPayload
에서 삭제되고 특수 필드 문서에 설명된 대로 생성된 LogEntry
의 해당 필드에 작성됩니다.
예를 들어 JSON에 severity
속성이 포함되어 있으면 이 속성은 jsonPayload
에서 삭제되고 대신 로그 항목의 severity
로 표시됩니다. message
속성이 있으면 이 속성은 로그 항목의 기본 표시 텍스트로 사용됩니다.
클라이언트 라이브러리를 사용한 로그 작성
Cloud Logging 클라이언트 라이브러리는 로그를 작성하는 다른 방법을 제공합니다. 이러한 라이브러리를 사용하면 프로그래밍 언어의 표준 로깅 메커니즘을 사용하고 지원되는 다양한 로깅 프레임워크와 통합할 수 있습니다. 또한 클라이언트 라이브러리는 일부 정보를 자동으로 캡처하고 필드를 적절하게 채우는 인터페이스를 제공하여 특수 JSON 필드 채우기를 단순화합니다.
클라이언트 라이브러리를 사용하여 Cloud Logging API로 로그를 동기식 또는 비동기식으로 작성할 수 있습니다. 일부 클라이언트 라이브러리에서는 구조화된 로그를 stdout
또는 stderr
에 직접 작성하도록 지원합니다. 로그를 비동기식으로 작성하는 경우 예기치 않은 함수 종료로 인해 로그 항목이 손실될 수 있습니다.
또한 Logging API를 사용하는 동기식 로깅에서는 API 호출이 완료될 때까지 기다려야 하므로 함수 실행 시간이 늘어납니다.
런타임 로그 보기
이 섹션에서는 런타임 로그를 볼 수 있는 옵션에 대해 설명합니다.
명령줄 도구 사용
Cloud Run Functions의 로그는 Cloud Logging UI 및 Google Cloud CLI를 통해 볼 수 있습니다.
gcloud CLI를 사용하여 로그를 보려면 gcloud functions logs read
명령어를 사용합니다.
gcloud functions logs read
특정 함수의 로그를 보려면 인수로 함수 이름을 제공합니다.
gcloud functions logs read FUNCTION_NAME
다음을 사용하여 특정 실행의 로그를 확인합니다.
gcloud functions logs read FUNCTION_NAME --execution-id EXECUTION_ID
모든 로그 보기 옵션은 gcloud functions logs read
문서를 참조하세요.
Logging 대시보드 사용
Google Cloud 콘솔에서 Cloud Run Functions의 런타임 로그를 볼 수도 있습니다.
Logging API 사용
Cloud Logging API를 통해 런타임 로그를 작성하고 검색할 수도 있습니다. Cloud Logging 클라이언트 라이브러리는 Logging API에 관용적인 인터페이스를 제공합니다.
Node.js
자세한 내용은 Node.js 클라이언트 라이브러리 참조를 확인하세요.Python
자세한 내용은 Python 클라이언트 라이브러리 참조를 확인하세요.Go
자세한 내용은 Go 클라이언트 라이브러리 참조를 확인하세요.자바
자세한 내용은 Java 클라이언트 라이브러리 참조를 확인하세요.C#
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()}"); } }
Ruby
PHP
use Google\Cloud\Logging\LoggingClient; /** * Print the timestamp and entry for the project and logger. * * @param string $projectId The Google project ID. * @param string $loggerName The name of the logger. */ 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); } }
Java의 추가 로깅 옵션은 Java 로깅을 참조하세요.
런타임 로그에 응답
로그를 Cloud Run Functions로 전달하여 Cloud Logging 이벤트에 응답할 수 있습니다. 자세한 내용은 Cloud Logging으로 2차 트리거 페이지를 참조하세요.
빌드 이미지 로그 보기
배포 프로세스에서 빌드 이미지 단계의 로그를 확인할 수도 있습니다. 자세한 내용을 보려면 링크를 클릭하세요.