DEV Community

Rogier van den Berg
Rogier van den Berg

Posted on

Easy Google Cloud Logging from your Golang project in Google Cloud Run

In my journey of learning Go, for almost a day I have been searching and thinking in the wrong direction, and I want to prevent you from doing the same 😅

I am building a HTTP Service running in Google Cloud Run in Go and wanted an easy way to log stuff to Google Cloud Logging.

Cloud Run Logs

Cloud Run has two types of logs, and these are automatically sent to Cloud Logging:

  • Request logs: logs of requests sent to Cloud Run services. These logs are created automatically.
  • Container logs: logs emitted from the container instances, typically from your own code, when writing to stdout or stderr

Loggers

If you start searching on how to do logging, you will find many possibilities, this makes it very difficult to decide and/or even to know which one to use.

Even worse, because I'm making a HTTP service, I was searching in the direction of creating middleware for my chi router. 🤦‍♂️

KISS

But then it hit me: As Cloud Run already automatically takes care of the HTTP request logging, I only needed to log certain important 'events'. Thus, I could just write to os.stdout in the correct format.

And even better, there is a very easy to use log package for that:, having great benefits like no dependencies, uses ' severity ' to support the Cloud Logging filters.

The only implementation is

package main

import "github.com/apsystole/log"

func main() {
    log.Print("my message")
    // {"message":"my message","severity":"INFO"}
}
Enter fullscreen mode Exit fullscreen mode

or

log.Error("my message")
 // {"message":"my message","severity":"ERROR"}
Enter fullscreen mode Exit fullscreen mode

Bottom line: keep it simple, stupid ;)

Top comments (0)