Mathias Bak
Mathias Bak

Reputation: 5115

How to configure cloud.google.com/go/logging to look like logs written to stdout?

I'm writing a Google Cloud Function in Go. I can write log messages simply by writing to stdout. The logs produced includes info about the function, its runtime, trace info, etc. Super nice, however, I want to add some structured data to my logs which means stdout is not flexible enough. So I'm trying to use "cloud.google.com/go/logging". I set it up like so:

// Set up like this
logClient, err = logging.NewClient(ctx, "my-project-id")
if err != nil {
    return
}
logger := logClient.Logger("my-function-name")

// And log like this
logger.Log(logging.Entry{
    Payload:  "Hello World!",
    Severity: logging.Info,
})

However, the logs I see the Cloud Console are missing all of that nice info that is automatically attached to the stdout logs.

To get some of it back, I can add this option when setting up the logger:

logging.CommonResource(&monitoredres.MonitoredResource{
    Type: fmt.Sprintf("projects/%s/logs/cloudfunctions.googleapis.com%scloud-functions", os.Getenv("GCP_PROJECT"), "%2F"),
    Labels: map[string]string{
        "function_name": os.Getenv("FUNCTION_NAME"),
        "project_id":    os.Getenv("GCP_PROJECT"),
        "region":        os.Getenv("FUNCTION_REGION"),
    },
})

This allows me to see the logs when I click the "see logs" button in the cloud function list in the Cloud Console. However, it's missing the function execution id and trace id.

Am I missing something obvious here or is it just ridiculously complicated to set up decent logging for Google Cloud services? Any help appreciated.

Upvotes: 2

Views: 215

Answers (1)

Mathias Bak
Mathias Bak

Reputation: 5115

The trick was to simply write a json string to stdout.

fmt.Println(`{"field_name": "Hello World!"}`)

The schema for the logs can be found here.

e.g. set the severity like so:

fmt.Println(`{"field_name": "Hello World!", "severity": "DEBUG"}`)

Upvotes: 3

Related Questions