本地问题排查服务
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
此示例演示了一个容易中断的服务(如果不仔细调查就很难排查问题)以及一个改进的代码版本。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[],[],null,["# Service for local troubleshooting\n\nSample demonstrating an easily broken service that is difficult to troubleshoot without careful investigation, and an improved version of the code.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Local troubleshooting](/anthos/run/archive/docs/tutorials/local-troubleshooting)\n- [Local troubleshooting](/kubernetes-engine/enterprise/knative-serving/docs/tutorials/local-troubleshooting)\n- [Tutorial: Local troubleshooting of a Cloud Run service](/run/docs/tutorials/local-troubleshooting)\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run, 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 // Sample hello demonstrates a difficult to troubleshoot service.\n package main\n\n import (\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n )\n\n func main() {\n \tlog.Print(\"hello: service started\")\n\n \thttp.HandleFunc(\"/\", helloHandler)\n\n\n \tport := os.Getenv(\"PORT\")\n \tif port == \"\" {\n \t\tport = \"8080\"\n \t\tlog.Printf(\"Defaulting to port %s\", port)\n \t}\n\n \tlog.Printf(\"Listening on port %s\", port)\n \tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%s\", port), nil))\n }\n\n func helloHandler(w http.ResponseWriter, r *http.Request) {\n \tlog.Print(\"hello: received request\")\n\n \tname := os.Getenv(\"NAME\")\n \tif name == \"\" {\n \t\tlog.Printf(\"Missing required server parameter\")\n \t\t// The panic stack trace appears in Cloud Error Reporting.\n \t\tpanic(\"Missing required server parameter\")\n \t}\n\n \tfmt.Fprintf(w, \"Hello %s!\\n\", name)\n }\n\n### Java\n\n\nTo authenticate to Cloud Run, 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 static spark.Spark.get;\n import static spark.Spark.port;\n\n import org.slf4j.Logger;\n import org.slf4j.LoggerFactory;\n\n public class App {\n\n private static final Logger logger = LoggerFactory.getLogger(App.class);\n\n public static void main(String[] args) {\n int port = Integer.parseInt(System.getenv().getOrDefault(\"PORT\", \"8080\"));\n port(port);\n\n get(\n \"/\",\n (req, res) -\u003e {\n logger.info(\"Hello: received request.\");\n String name = System.getenv(\"NAME\");\n if (name == null) {\n // Standard error logs do not appear in Stackdriver Error Reporting.\n System.err.println(\"Environment validation failed.\");\n String msg = \"Missing required server parameter\";\n logger.error(msg, new Exception(msg));\n res.status(500);\n return \"Internal Server Error\";\n }\n res.status(200);\n return String.format(\"Hello %s!\", name);\n });\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run, 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 express = require('express');\n const app = express();\n\n app.get('/', (req, res) =\u003e {\n console.log('hello: received request.');\n\n const {NAME} = process.env;\n if (!NAME) {\n // Plain error logs do not appear in Stackdriver Error Reporting.\n console.error('Environment validation failed.');\n console.error(new Error('Missing required server parameter'));\n return res.status(500).send('Internal Server Error');\n }\n res.send(`Hello ${NAME}!`);\n });\n const port = parseInt(process.env.PORT) || 8080;\n app.listen(port, () =\u003e {\n console.log(`hello: listening on port ${port}`);\n });\n\n### Python\n\n\nTo authenticate to Cloud Run, 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 json\n import os\n\n from flask import Flask\n\n\n app = Flask(__name__)\n\n\n @app.route(\"/\", methods=[\"GET\"])\n def index():\n \"\"\"Example route for testing local troubleshooting.\n\n This route may raise an HTTP 5XX error due to missing environment variable.\n \"\"\"\n print(\"hello: received request.\")\n\n NAME = os.getenv(\"NAME\")\n\n if not NAME:\n print(\"Environment validation failed.\")\n raise Exception(\"Missing required service parameter.\")\n\n return f\"Hello {NAME}\"\n\n\n if __name__ == \"__main__\":\n PORT = int(os.getenv(\"PORT\")) if os.getenv(\"PORT\") else 8080\n\n # This is used when running locally. Gunicorn is used to run the\n # application on Cloud Run. See entrypoint in Dockerfile.\n app.run(host=\"127.0.0.1\", port=PORT, debug=True)\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=cloudrun)."]]