Cloud Functions 로그 항목을 작성합니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
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!");
}
}
Go
// Package helloworld provides a set of Cloud Functions samples.
package helloworld
import (
"fmt"
"log"
"net/http"
)
// HelloLogging logs messages.
func HelloLogging(w http.ResponseWriter, r *http.Request) {
log.Println("This is stderr")
fmt.Println("This is stdout")
// Structured logging can be used to set severity levels.
// See https://cloud.google.com/logging/docs/structured-logging.
fmt.Println(`{"message": "This has ERROR severity", "severity": "error"}`)
// cloud.google.com/go/logging can optionally be used for additional options.
}
Java
import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.logging.Logger;
public class LogHelloWorld implements HttpFunction {
private static final Logger logger = Logger.getLogger(LogHelloWorld.class.getName());
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
System.out.println("I am a log to stdout!");
System.err.println("I am a log to stderr!");
logger.info("I am an info log!");
logger.warning("I am a warning log!");
BufferedWriter writer = response.getWriter();
writer.write("Messages successfully logged!");
}
}
Node.js
exports.helloWorld = (req, res) => {
console.log('I am a log entry!');
console.error('I am an error!');
res.end();
};
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 doesn't log anything
error_log('error_log does not log 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 '';
}
Python
def hello_world(data, context):
"""Background Cloud Function.
Args:
data (dict): The dictionary with data specific to the given event.
context (google.cloud.functions.Context): The event metadata.
"""
print('Hello, stdout!')
Ruby
require "functions_framework"
FunctionsFramework.http "log-helloworld" do |_request|
# Any output sent to either stdout or stderr will be captured and written to
# the function's logs.
puts "Hello, stdout!"
warn "Hello, stderr!"
# Return the response body as a string.
"Hello, world!"
end
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.