Writing, Viewing, and Responding to Logs

Writing runtime logs

Cloud Functions includes simple runtime logging by default. Logs written to stdout or stderr will appear automatically in the Cloud Console. For more advanced logging, use the Stackdriver Logging Client Library.

Node.js

exports.helloWorld = (req, res) => {
  console.log('I am a log entry!');
  console.error('I am an error!');
  res.end();
};
Most log entries do not have an associated log level. These include:

  • Logs emitted using console.log(), console.info() , console.warn() or console.error()
  • Logs written directly to stdout or stderr

Internal system messages have the DEBUG log level.

Python

def hello_world(data, context):
    """Background Cloud Function.
    Args:
         data (dict): The dictionary with data specific to the given event.
         context (google.cloud.functions.Context): The event metadata.
    """
    print('Hello, stdout!')
  • Logs to standard output or standard error do not have an associated log level.
  • Internal system messages have the DEBUG log level.

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

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

// HelloLogging logs messages.
func HelloLogging(w http.ResponseWriter, r *http.Request) {
	log.Println("This is stderr")
	fmt.Println("This is stdout")

	// Structured logging can be used to set severity levels.
	// See https://cloud.google.com/logging/docs/structured-logging.
	fmt.Println(`{"message": "This has ERROR severity", "severity": "error"}`)

	// cloud.google.com/go/logging can optionally be used for additional options.
}
  • Logs to stdout or stderr do not have an associated log level.
  • Internal system messages have the DEBUG log level.

Java


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.logging.Logger;

public class LogHelloWorld implements HttpFunction {

  private static final Logger logger = Logger.getLogger(LogHelloWorld.class.getName());

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    System.out.println("I am a log to stdout!");
    System.err.println("I am a log to stderr!");

    logger.info("I am an info log!");
    logger.warning("I am a warning log!");

    BufferedWriter writer = response.getWriter();
    writer.write("Messages successfully logged!");
  }
}
  • Logs to stdout or stderr do not have an associated log level.
  • Internal system messages have the DEBUG log level.

Viewing runtime logs

Using the command-line tool

Logs for Cloud Functions are viewable in the Stackdriver Logging UI, and via the gcloud command-line tool.

To view logs with the gcloud tool, use the logs read command:

gcloud functions logs read

To view the logs for a specific function, provide the function name as an argument:

gcloud functions logs read FUNCTION_NAME

You can even view the logs for a specific execution:

gcloud functions logs read FUNCTION_NAME --execution-id EXECUTION_ID

For the full range of log viewing options, view the help for logs read:

gcloud functions logs read --help

Using the Logging dashboard

You can also view runtime logs for Cloud Functions from the Cloud Console.

Using the Logging API

Runtime logs can also be written and retrieved through the Logging API. The Stackdriver Logging Client Libraries provide an idiomatic interface to the Logging API:

Node.js

For more information, see the Node.js Client Library reference.
// Imports the Google Cloud client library
const {Logging} = require('@google-cloud/logging');

// Creates a client
const logging = new Logging();

/**
 * TODO(developer): Uncomment the following line to run the code.
 */
// const logName = 'Name of the log from which to list entries, e.g. my-log';

const log = logging.log(logName);

async function printEntryMetadata() {
  // List the most recent entries for a given log
  // See
  // https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging/latest/logging?method=getEntries
  const [entries] = await log.getEntries();
  console.log('Logs:');
  entries.forEach(entry => {
    const metadata = entry.metadata;
    console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
  });
}
printEntryMetadata();

Python

For more information, see the Python Client Library reference.
def list_entries(logger_name):
    """Lists the most recent entries for a given logger."""
    logging_client = logging.Client()
    logger = logging_client.logger(logger_name)

    print('Listing entries for logger {}:'.format(logger.name))

    for entry in logger.list_entries():
        timestamp = entry.timestamp.isoformat()
        print('* {}: {}'.format
              (timestamp, entry.payload))

Go

For more information, see the Go Client Library reference.
var entries []*logging.Entry
const name = "log-example"
iter := adminClient.Entries(ctx,
	// Only get entries from the log-example log.
	logadmin.Filter(fmt.Sprintf(`logName = "projects/%s/logs/%s"`, projID, name)),
	// Get most recent entries first.
	logadmin.NewestFirst(),
)

// Fetch the most recent 20 entries.
for len(entries) < 20 {
	entry, err := iter.Next()
	if err == iterator.Done {
		return entries, nil
	}
	if err != nil {
		return nil, err
	}
	entries = append(entries, entry)
}
return entries, nil

Java

For more information, see the Java Client Library reference.
// Instantiates a client
LoggingOptions options = LoggingOptions.getDefaultInstance();

String logName = args[0];

try (Logging logging = options.getService()) {

  String logFilter = "logName=projects/" + options.getProjectId() + "/logs/" + logName;

  // List all log entries
  Page<LogEntry> entries = logging.listLogEntries(EntryListOption.filter(logFilter));
  do {
    for (LogEntry logEntry : entries.iterateAll()) {
      System.out.println(logEntry);
    }
    entries = entries.getNextPage();
  } while (entries != null);
}

Responding to runtime logs

You can respond to Stackdriver-logged events by forwarding their logs to a Cloud Function. For more information, see the Second-Party Triggers with Stackdriver page.

Viewing build image logs

You can also see the logs for the build image step of the deployment process. Follow the link for more information.