本地问题排查服务

此示例演示了一个容易中断的服务(如果不仔细调查就很难排查问题)以及一个改进的代码版本。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Go

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// Sample hello demonstrates a difficult to troubleshoot service.
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func main() {
	log.Print("hello: service started")

	http.HandleFunc("/", helloHandler)


	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}

	log.Printf("Listening on port %s", port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	log.Print("hello: received request")

	name := os.Getenv("NAME")
	if name == "" {
		log.Printf("Missing required server parameter")
		// The panic stack trace appears in Cloud Error Reporting.
		panic("Missing required server parameter")
	}

	fmt.Fprintf(w, "Hello %s!\n", name)
}

Java

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import static spark.Spark.get;
import static spark.Spark.port;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

  private static final Logger logger = LoggerFactory.getLogger(App.class);

  public static void main(String[] args) {
    int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080"));
    port(port);

    get(
        "/",
        (req, res) -> {
          logger.info("Hello: received request.");
          String name = System.getenv("NAME");
          if (name == null) {
            // Standard error logs do not appear in Stackdriver Error Reporting.
            System.err.println("Environment validation failed.");
            String msg = "Missing required server parameter";
            logger.error(msg, new Exception(msg));
            res.status(500);
            return "Internal Server Error";
          }
          res.status(200);
          return String.format("Hello %s!", name);
        });
  }
}

Node.js

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  console.log('hello: received request.');

  const {NAME} = process.env;
  if (!NAME) {
    // Plain error logs do not appear in Stackdriver Error Reporting.
    console.error('Environment validation failed.');
    console.error(new Error('Missing required server parameter'));
    return res.status(500).send('Internal Server Error');
  }
  res.send(`Hello ${NAME}!`);
});
const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
  console.log(`hello: listening on port ${port}`);
});

Python

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import json
import os

from flask import Flask


app = Flask(__name__)


@app.route("/", methods=["GET"])
def index():
    """Example route for testing local troubleshooting.

    This route may raise an HTTP 5XX error due to missing environment variable.
    """
    print("hello: received request.")

    NAME = os.getenv("NAME")

    if not NAME:
        print("Environment validation failed.")
        raise Exception("Missing required service parameter.")

    return f"Hello {NAME}"


if __name__ == "__main__":
    PORT = int(os.getenv("PORT")) if os.getenv("PORT") else 8080

    # This is used when running locally. Gunicorn is used to run the
    # application on Cloud Run. See entrypoint in Dockerfile.
    app.run(host="127.0.0.1", port=PORT, debug=True)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器