Service for local troubleshooting

Sample demonstrating an easily broken service that is difficult to troubleshoot without careful investigation, and an improved version of the code.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

Go


// 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

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

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 = process.env.PORT || 8080;
app.listen(port, () => {
  console.log(`hello: listening on port ${port}`);
});

Python

import json
import os

from flask import Flask


app = Flask(__name__)


@app.route("/", methods=["GET"])
def index():
    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)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser