Menulis log
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Menulis entri log Cloud Functions.
Jelajahi lebih lanjut
Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:
Contoh kode
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to write log entries in Cloud Functions using various programming languages, including C#, Go, Java, Node.js, PHP, Python, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eCloud Functions logs can be written to both standard output (stdout) and standard error (stderr), which are then captured and displayed in Cloud Logging.\u003c/p\u003e\n"],["\u003cp\u003eStructured logging is supported, allowing for the specification of severity levels like "error" within log messages.\u003c/p\u003e\n"],["\u003cp\u003eSetting up Application Default Credentials (ADC) is necessary for authenticating to Cloud Run functions during local development, allowing you to write logs to the appropriate places.\u003c/p\u003e\n"],["\u003cp\u003eThis page provides code samples in multiple languages showing how to write log entries using standard logging mechanisms and libraries, like using \u003ccode\u003elog.Println\u003c/code\u003e in Go or \u003ccode\u003elogger.info\u003c/code\u003e in Java, among others.\u003c/p\u003e\n"]]],[],null,["# Write logs\n\nWrites a Cloud Functions log entry.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [View and write Cloud Run function logs](/functions/1stgendocs/monitoring/logging)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using Google.Cloud.Functions.Framework;\n using Microsoft.AspNetCore.Http;\n using Microsoft.Extensions.Logging;\n using System;\n using System.Threading.Tasks;\n\n namespace LogHelloWorld;\n\n public class Function : IHttpFunction\n {\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public async Task HandleAsync(HttpContext context)\n {\n Console.WriteLine(\"I am a log to stdout!\");\n Console.Error.WriteLine(\"I am a log to stderr!\");\n\n _logger.LogInformation(\"I am an info log!\");\n _logger.LogWarning(\"I am a warning log!\");\n\n await context.Response.WriteAsync(\"Messages successfully logged!\", context.RequestAborted);\n }\n }\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package helloworld provides a set of Cloud Functions samples.\n package helloworld\n\n import (\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n func init() {\n \tfunctions.HTTP(\"HelloLogging\", HelloLogging)\n }\n\n // HelloLogging logs messages.\n func HelloLogging(w http.ResponseWriter, r *http.Request) {\n \tlog.Println(\"This is stderr\")\n \tfmt.Println(\"This is stdout\")\n\n \t// Structured logging can be used to set severity levels.\n \t// See https://cloud.google.com/logging/docs/structured-logging.\n \tfmt.Println(`{\"message\": \"This has ERROR severity\", \"severity\": \"error\"}`)\n\n \t// cloud.google.com/go/logging can optionally be used for additional options.\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.BufferedWriter;\n import java.io.IOException;\n import java.util.logging.Logger;\n\n public class LogHelloWorld implements HttpFunction {\n\n private static final Logger logger = Logger.getLogger(LogHelloWorld.class.getName());\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException {\n System.out.println(\"I am a log to stdout!\");\n System.err.println(\"I am a log to stderr!\");\n\n logger.info(\"I am an info log!\");\n logger.warning(\"I am a warning log!\");\n\n BufferedWriter writer = response.getWriter();\n writer.write(\"Messages successfully logged!\");\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n functions.http('helloWorld', (req, res) =\u003e {\n console.log('I am a log entry!');\n console.error('I am an error!');\n res.end();\n });\n\n### PHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use Psr\\Http\\Message\\ServerRequestInterface;\n\n function helloLogging(ServerRequestInterface $request): string\n {\n // Code running in Google Cloud Functions itself writes log entries to\n // Cloud Logging. (Default log severity level is INFO.)\n $log = fopen('php://stderr', 'wb');\n fwrite($log, \"Log entry from fwrite().\\n\");\n\n // You can also specify a severity level explicitly using structured logs.\n // See this page for a list of log severity values:\n // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity\n fwrite($log, json_encode([\n 'message' =\u003e 'Structured log with error severity',\n 'severity' =\u003e 'error'\n ]) . PHP_EOL);\n\n // This will log to standard error, which will appear in Cloud Logging\n error_log('error_log logs in Cloud Functions!');\n\n // This will log an error message and immediately terminate the function execution\n // trigger_error('fatal errors are logged!');\n\n // For HTTP functions, this is added to the HTTP response\n // For CloudEvent functions, this does nothing\n var_dump('var_dump goes to HTTP response for HTTP functions');\n\n // You can also dump variables using var_export() and forward\n // the resulting string to Cloud Logging via an fwrite() call.\n $entry = var_export('var_export output can be captured.', true);\n fwrite($log, $entry);\n\n // Functions must return a String or PSR-7 Response object\n return '';\n }\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def hello_world(data, context):\n \"\"\"Background Cloud Function.\n Args:\n data (dict): The dictionary with data specific to the given event.\n context (google.cloud.functions.Context): The event metadata.\n \"\"\"\n print(\"Hello, stdout!\")\n\n### Ruby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n\n FunctionsFramework.http \"log-helloworld\" do |_request|\n # Any output sent to either stdout or stderr will be captured and written to\n # the function's logs.\n puts \"Hello, stdout!\"\n warn \"Hello, stderr!\"\n\n # Return the response body as a string.\n \"Hello, world!\"\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]