Scrivere log strutturati in Cloud Functions
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questo esempio mostra come scrivere log strutturati in Cloud Functions utilizzando il client di logging Google Cloud. I log strutturati forniscono un modo più dettagliato e organizzato per registrare le informazioni sulla tua applicazione, semplificando la risoluzione dei problemi e l'analisi.
Esempio di codice
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","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)."]]