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.)
You have at least 2 solutions :
logrus
) and a special Stackdriver adapter to have logs with the right format and right level in Stackdriver loggingThis 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).
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) :