Write structured Logging in Cloud Functions
Stay organized with collections
Save and categorize content based on your preferences.
This 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.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","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)."]]