Écrire des journaux structurés dans Cloud Functions
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cet exemple montre comment écrire des journaux structurés dans Cloud Functions à l'aide du client de journalisation Google Cloud. Les journaux structurés offrent un moyen plus détaillé et organisé d'enregistrer des informations sur votre application, ce qui facilite l'analyse et la résolution des problèmes.
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis sample demonstrates how to write structured logs in Cloud Functions using the Google Cloud logging client in both Node.js and Python.\u003c/p\u003e\n"],["\u003cp\u003eStructured logs offer a detailed and organized method for recording application information, aiding in issue troubleshooting and analysis.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples showcase initializing the logging client, creating log entries with metadata like severity and components, and writing them to the log.\u003c/p\u003e\n"],["\u003cp\u003eIn both samples, setting up Application Default Credentials is required for authenticating to Cloud Run functions.\u003c/p\u003e\n"],["\u003cp\u003eThe HTTP request data is attached automatically for request-log correlation.\u003c/p\u003e\n"]]],[],null,["# Write structured Logging in Cloud Functions\n\nThis sample demonstrates how to write structured logs in Cloud Functions using the Google Cloud logging client. Structured logs provide a more detailed and organized way to record information about your application, making it easier to troubleshoot and analyze issues.\n\nCode sample\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 {Logging} = require('https://cloud.google.com/nodejs/docs/reference/logging/latest/overview.html');\n const functions = require('@google-cloud/functions-framework');\n const pkg = require('./package.json');\n\n functions.http('structuredLogging', async (req, res) =\u003e {\n // Initialize the logging client\n const logging = new https://cloud.google.com/nodejs/docs/reference/logging/latest/logging/logging.html();\n // Required to capture your project id\n await logging.https://cloud.google.com/nodejs/docs/reference/logging/latest/logging/logging.html();\n // Create a LogSync transport, defaulting to process.stdout\n const log = logging.https://cloud.google.com/nodejs/docs/reference/logging/latest/logging/logging.html(pkg.name);\n const text = 'Hello, world!';\n // Create a structured log entry with severity,\n // additional component fields, and HTTP request.\n // Appending the httpRequest enables log correlation.\n const metadata = {\n severity: 'https://cloud.google.com/nodejs/docs/reference/logging/latest/logging/protos.google.logging.type.logseverity.html',\n component: 'arbitrary-property',\n httpRequest: req,\n };\n // Prepares a log entry\n const entry = log.entry(metadata, text);\n log.write(entry);\n res.status(200).send('Success: A log message was written');\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 import logging\n\n import functions_framework\n from google.cloud.logging import https://cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html\n\n\n @functions_framework.http\n def structured_logging(request):\n # Initialize the Google Cloud logging client\n cloud_logging_client = Client()\n # Set up a Log Handler that exports logs in JSON format to stdout\n # when running in a serverless environment.\n # To manually set up a Structured Log Handler, see\n # https://googleapis.dev/python/logging/latest/handlers-structured-log.html\n cloud_logging_client.https://cloud.google.com/python/docs/reference/logging/latest/google.cloud.logging_v2.client.Client.html#google_cloud_logging_v2_client_Client_setup_logging()\n\n # Construct log message and additional metadata\n # https://cloud.google.com/run/docs/logging#using-json\n msg = \"Hello, world!\"\n metadata = {\"component\": \"arbitrary-property\"}\n\n # Write structured log with additional component fields\n # HTTP request data is attached automatically for request-log correlation\n logging.info(msg, extra={\"json_fields\": metadata})\n\n return \"Success: A log message was written\"\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)."]]