Replacement for Go App Engine "google.golang.org/appengine/log" package, with log levels?

408 views Asked by At

I noticed this package is deprecated, per the documentation here: https://cloud.google.com/appengine/docs/standard/go/go-differences

What is the correct way to log on Go 1.12+ without losing log levels by simply printing? (DEBUG/INFO/WARNING/ERROR/CRITICAL/etc.)

1

There are 1 answers

2
norbjd On BEST ANSWER

You have at least 2 solutions :

  1. Use cloud.google.com/go/logging
  2. Use a generic logging framework (like logrus) and a special Stackdriver adapter to have logs with the right format and right level in Stackdriver logging

Use cloud.google.com/go/logging

This is the default solution I think :

import "cloud.google.com/go/logging"

ctx := context.Background()
client, err := logging.NewClient(ctx, "my-project")

logger := client.Logger("my-log")
logger.Log(logging.Entry{Payload: "something happened!", Severity: logging.Info})

But it can be tedious to create an Entry object every time you want to log something. If you want to just write log.Debug, log.Info, of course you can create functions logDebug, logInfo, etc, but you can also use another solution (based on logrus).

Use logrus and Stackdriver adapter

As I said, you can use logrus) which is pretty common for logging in Go projects. But you need to make a small modification to transform the default text log to a log entry format that Stackdriver can understand.

import (
        log "github.com/sirupsen/logrus"
        stackdriver "github.com/TV4/logrus-stackdriver-formatter" // adapter
)

log.SetFormatter(stackdriver.NewFormatter())
log.SetLevel(log.DebugLevel) // default is Info

log.Debug("This is debug")
log.Info("This is info")
log.Error("This is error")
log.Warn("This is warn")

Result is the following (notice the right levels) :

Stackdriver logs