Writing, Viewing, and Responding to Logs

Writing logs

Cloud Functions includes simple logging by default. Logs written to stdout or stderr will appear automatically in the Logging dashboard. 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();
};
  • Logs emitted using console.log() have the INFO log level.
  • Logs emitted using console.error() have the ERROR log level.
  • Logs written directly to stdout or stderr do not have an associated log level.
  • 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")
}
  • Logs to stdout or stderr do not have an associated log level.
  • Internal system messages have the DEBUG log level.

Viewing 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 -h

Using the Logging dashboard

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

Using the Logging API

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.
// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://github.com/googleapis/google-cloud-node/blob/master/docs/authentication.md
const Logging = require('@google-cloud/logging');

function getLogEntries() {
  // Instantiates a client
  const logging = Logging();

  const options = {
    pageSize: 10,
    filter: 'resource.type="cloud_function"',
  };

  // Retrieve the latest Cloud Function log entries
  // See https://googlecloudplatform.github.io/gcloud-node/#/docs/logging
  return logging.getEntries(options).then(([entries]) => {
    console.log('Entries:');
    entries.forEach(entry => console.log(entry));
    return entries;
  });
}

Python

For more information, see the Python Client Library reference.
import os
import google.cloud.logging as cloud_logging
cloud_client = cloud_logging.Client()
log_name = 'cloudfunctions.googleapis.com%2Fcloud-functions'
cloud_logger = cloud_client.logger(log_name.format(os.getenv('GCP_PROJECT')))


def get_log_entries(request):
    """
    HTTP Cloud Function that displays log entries from Cloud Functions.
    Args:
        request (flask.Request): The request object.
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    """"""

    all_entries = cloud_logger.list_entries(page_size=10)
    entries = next(all_entries.pages)

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

    return 'Done!'

Go

For more information, see the Go Client Library reference.
// Package log contains logging examples.
package log

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/logging/apiv2"
	"google.golang.org/api/iterator"
	loggingpb "google.golang.org/genproto/googleapis/logging/v2"
)

// logEntries retrieves log entries from projectID and writes them to the
// passed io.Writer.
func logEntries(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := logging.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("logging.NewClient: %v", err)
	}

	req := &loggingpb.ListLogEntriesRequest{
		ResourceNames: []string{"projects/" + projectID},
		PageSize:      10,
	}

	fmt.Fprintln(w, "Entries:")
	it := client.ListLogEntries(ctx, req)
	// Wrap in a for loop to get all available log entries.
	resp, err := it.Next()
	if err == iterator.Done {
		return nil
	}
	if err != nil {
		return fmt.Errorf("it.Next: %v", err)
	}
	fmt.Fprintln(w, resp.GetPayload())
	return nil
}

Responding to 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.

Оцените, насколько информация на этой странице была вам полезна:

Оставить отзыв о...

Текущей странице
Cloud Functions Documentation