# Uncomment and populate this variable in your code:# PROJECT = 'The project ID of your Cloud Run service';# Build structured log messages as an object.global_log_fields={}# Add log correlation to nest all log messages.# This is only relevant in HTTP-based contexts, and is ignored elsewhere.# (In particular, non-HTTP-based Cloud Functions.)request_is_defined="request"inglobals()or"request"inlocals()ifrequest_is_definedandrequest:trace_header=request.headers.get("X-Cloud-Trace-Context")iftrace_headerandPROJECT:trace=trace_header.split("/")global_log_fields["logging.googleapis.com/trace"]=f"projects/{PROJECT}/traces/{trace[0]}"# Complete a structured log entry.entry=dict(severity="NOTICE",message="This is the default display field.",# Log viewer accesses 'component' as jsonPayload.component'.component="arbitrary-property",**global_log_fields,)print(json.dumps(entry))
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-20。"],[[["\u003cp\u003eApp Engine automatically collects request logs for each HTTP request and app logs based on entries written to supported frameworks or files.\u003c/p\u003e\n"],["\u003cp\u003eApp logs can be written using Cloud Logging integration or by writing structured logs to \u003ccode\u003estdout\u003c/code\u003e and \u003ccode\u003estderr\u003c/code\u003e, allowing for structured data in the \u003ccode\u003ejsonPayload\u003c/code\u003e field.\u003c/p\u003e\n"],["\u003cp\u003eTo correlate request and app logs, extract the trace identifier from the \u003ccode\u003eX-Cloud-Trace-Context\u003c/code\u003e header and include it in the \u003ccode\u003elogging.googleapis.com/trace\u003c/code\u003e field of your structured log entry.\u003c/p\u003e\n"],["\u003cp\u003eLogs can be viewed in the Logs Explorer by selecting "GAE Application" as the resource type, or via the Google Cloud CLI using the \u003ccode\u003egcloud app logs tail\u003c/code\u003e command, and programmatically using several methods.\u003c/p\u003e\n"],["\u003cp\u003eLog management includes controlling log activity from the app, using log exclusions for request logs, and understanding the pricing, quotas, and retention policies for Cloud Logging.\u003c/p\u003e\n"]]],[],null,["# Write and view logs\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\nGo Java Node.js PHP Python Ruby\n\nThis page describes the logs that are available for App Engine apps, and\nhow to write, correlate, and view log entries.\n\nApp Engine collects two types of logs:\n\n- **Request log:** Logs of requests sent to your app. By default, App Engine\n automatically emits a log entry for each HTTP request an app receives.\n\n- **App log:** Log entries that are emitted by an App Engine app\n based on the log entries you write to a supported framework or file.\n\nApp Engine automatically sends both the request logs and app logs to the\n[Cloud Logging](/logging/docs/overview) agent.\n\n\nWrite app logs\n--------------\n\nApp Engine automatically emits logs for requests sent to your app, so\nthere is no need to write request logs. This section covers how to write app logs.\n\nWhen you write app logs from your App Engine app, the logs are picked up\nautomatically by Cloud Logging, as long as the logs are written using the\nfollowing methods:\n\n- [Integrate with Cloud Logging](#integrate_logging)\n- [Write structured logs with `stdout` and `stderr`](#stdout_stderr)\n\n\u003cbr /\u003e\n\n### Integrate with Cloud Logging\n\nYou can integrate your App Engine app with Cloud Logging.\nThis approach lets you use all the features offered by Cloud Logging and requires\nonly a few lines of Google-specific code.\n\n\n| **Important:** The Logs Explorer does not display an app log entry that exceeds 16 kilobytes.\n\n### Write structured logs to `stdout` and `stderr`\n\nBy default, App Engine uses the Cloud Logging client library to send logs.\nHowever, this method doesn't support structured logging. You can only write\nstructured logs using `stdout/stderr`. Additionally, you can also send text strings to\n`stdout` and `stderr`. By default, the log payload is a\ntext string stored in the `textPayload` field of the log entry. The strings\nappear as messages in the Logs Explorer, the command line, and the\nCloud Logging API, and are associated with the App Engine service\nand version that emitted them.\n\nTo get more value from the logs, you can filter these strings in the Logs Explorer\nby severity level. To filter these strings, you need to format the strings as\n[**structured data**](/logging/docs/structured-logging).\nTo do this, you write logs in the form of a single\nline of serialized JSON. App Engine picks up and parses this serialized JSON line,\nand places it into the `jsonPayload` field of the log entry instead of `textPayload`.\n\n\u003cbr /\u003e\n\nIn the App Engine standard environment, writing structured logs to `stdout` and `stderr`\ndon't count against the log ingestion requests per minute quota in the Cloud Logging API.\n\n\n### Special JSON fields in messages\n\nWhen you provide a structured log as a JSON dictionary, some special fields are\nstripped from the `jsonPayload` and are written to the corresponding field in\nthe generated\n[LogEntry](/logging/docs/reference/v2/rest/v2/LogEntry) as described in\nthe documentation for [special fields](/logging/docs/agent/configuration#special-fields).\n\nFor example, if your JSON includes a `severity` property, it is removed from\nthe `jsonPayload` and appears instead as the log entry's `severity`.\nThe `message` property is used as the main display text of the log entry if present.\n\n\u003cbr /\u003e\n\n### Correlate request logs with app logs\n\n\nAfter you've [formatted the entries as a JSON object](#stdout_stderr) and provided\nspecific metadata, you can enable filtering and correlation with request logs.\nTo correlate the request log entries with the app log entries, you need the request's\ntrace identifier. Follow the instructions to correlate log messages:\n\n1. Extract the trace identifier from the `X-Cloud-Trace-Context` request header.\n2. In your structured log entry, write the ID to a field named `logging.googleapis.com/trace`. For more information about the `X-Cloud-Trace-Context` header, see [Forcing a request to be traced](/trace/docs/setup#force-trace).\n\nTo view correlated logs, see [View correlated log entries in the Logs Explorer](#view_correlated_logs).\n\n\nView logs\n---------\n\nYou can view app logs and request logs in several ways:\n\n- [Use Logs Explorer](#logs_explorer) from Cloud Logging in the Google Cloud console.\n- [Use the Google Cloud CLI](#cli) to view logs using gcloud.\n- [Read logs programmatically](#read-programmatically) using various methods.\n\n### Use Logs Explorer\n\nYou can view your app and request logs using the\n[Logs Explorer](/logging/docs/view/logs-explorer-interface):\n\n1. Go to **Logs Explorer** in the Google Cloud console:\n\n [Go to Logs Explorer](https://console.cloud.google.com/logs/query)\n2. Select an existing Google Cloud project at the top of the page.\n\n3. In **Resource Type** , select **GAE Application**.\n\nYou can filter the Logs Explorer by App Engine service, version and\nother criteria. You can also search the logs for specific entries.\nSee [Using the Logs Explorer](/logging/docs/view/logs-explorer-interface)\nfor details.\n\nIf you send simple text entries to standard output, you cannot use the Logs\nViewer to filter app entries by severity, nor can you see which app logs\ncorrespond to specific requests. You can still use other types of filtering\nin the Logs Explorer, such as text and timestamp.\n\n### View correlated log entries in the Logs Explorer\n\nIn the Logs Explorer, to view the child log entries correlated with a parent\nlog entry, expand the log entry.\n\nFor example, to display your App Engine request log entry and application log\nentries, do the following:\n\n1. In the navigation panel of the Google Cloud console, select\n **Logging** , and then select **Logs Explorer**:\n\n [Go to Logs Explorer](https://console.cloud.google.com/logs/query)\n2. In **Resource Type** , select **GAE Application**.\n\n3. To view and correlate request logs, in **Log Name** , select **request_log** . Alternatively,\n to correlate by request logs, click **Correlate by** and select **request_log**.\n\n4. In the **Query results** pane, to expand a log entry,\n click **Expand**. On expanding, each request log\n will show the associated app logs.\n\nAfter creating a filter for the logs, each request log shows corresponding\napp logs as child logs. Logs Explorer achieves this by correlating\nthe `trace` field in app logs and a given request log, assuming the application\nuses the `google-cloud-logging` library.\n\nThe following image shows app logs grouped by the `trace` field:\n\n### Use the Google Cloud CLI\n\nTo view your App Engine logs from the command line, use the\nfollowing command: \n\n```bash\ngcloud app logs tail\n```\n\nFor more information, see [gcloud app logs tail](/sdk/gcloud/reference/app/logs/tail).\n\n### Reading logs programmatically\n\nIf you want to read the logs programmatically, you can use one of these methods:\n\n- Use a [log sink to Pub/Sub and a script to pull from Pub/Sub](/logging/docs/export).\n- Call the Cloud Logging API through the [client library](/logging/docs/reference/libraries) for your programming language.\n- Call the [Cloud Logging API REST endpoints](/logging/docs/reference/v2/rest) directly.\n\nPricing, quotas, and logs retention policy\n------------------------------------------\n\nFor information about pricing that applies to both request and app logs, see\n[Pricing for Cloud Logging](/logging/pricing#logging-costs).\n\nFor the logs retention policy and the maximum size of log entries, see [Quotas\nand limits](/logging/quotas). If you want to store your logs for a longer\nperiod, you can [export your logs](/logging/docs/export) to Cloud Storage.\nYou can also export your logs to BigQuery and Pub/Sub for\nfurther processing.\n\n### Managing log resource usage\n\nYou can control the amount of logging activity from your app logs by writing\nmore or fewer entries from your app's code. Request logs are created\nautomatically, so to manage the number of request log entries associated with\nyour app, Use the [logs exclusion](/logging/docs/exclusions#overview) feature\nfrom Cloud Logging.\n\nKnown issues\n------------\n\nThe following are some logging issues in the second-generation runtimes:\n\n- Sometimes app log entries are not correlated with the request log. This\n happens the first time your app receives a request and any other time\n App Engine writes status messages to your app's log. For more\n information, see\n \u003chttps://issuetracker.google.com/issues/138365527\u003e.\n\n- When you route logs from log sink to Cloud Storage, the Cloud Storage\n destination only contains request logs. App Engine writes app logs to\n different folders.\n\n- BigQuery fails to ingest logs due to the `@type` field in request logs. This\n disrupts the auto-schema detection, since BigQuery doesn't allow `@type` in field\n names. To resolve this, you must manually define the schema, and remove the\n `@type` field from request logs.\n\n- If you use the logging REST APIs, a background thread writes logs to Cloud Logging.\n If the main thread isn't active, the instance doesn't get CPU time, which causes\n the background thread to stop. Log processing time is delayed. At\n some point, the instance is removed and any unsent logs are lost. To avoid losing logs, use one of the following options:\n\n - Configure the Cloud Logging SDK to use gRPC. With gRPC, the logs are sent to Cloud Logging immediately. However this can increase the required CPU limits.\n - Send log messages to Cloud Logging using `stdout/stderr`. This pipeline is outside the App Engine instance and doesn't get throttled.\n\nWhat's next\n-----------\n\n- See [Monitor and alert latency](/appengine/docs/standard/monitoring-and-alerting-latency) to learn how to use Cloud Logging to view logs for debugging errors, and how to use Cloud Trace to understand app latency."]]