Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging to stderr and stdout golang Google Cloud Platform

Currently running a go service on GCP however in the logs viewer every message is treated as an error.

Is there a generally advised way of logging to stderr and stdout depending on the log level. Ie errors to stderr and anything else to stdout.

I'm currently using the logrus package and have come across this implementation. Other ways i see achieving this while still using the same package is to pass the logger to each package that needs it or to create a global log object, neither of which i am too keen on.

https://github.com/microsoft/fabrikate/pull/252/commits/bd24d62d7c2b851ad6e7b36653eb0a6dc364474b#diff-ed0770fdbf87b0c6d536e33a99a8df9c

like image 911
jwtea Avatar asked Oct 28 '22 08:10

jwtea


1 Answers

You can use Stackdriver library package for GoLang:

go get -u cloud.google.com/go/logging

Then you can use StandardLogger:

// Sample stdlogging writes log.Logger logs to the Stackdriver Logging.
package main

import (
        "context"
        "log"

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

func main() {
        ctx := context.Background()

        // Sets your Google Cloud Platform project ID.
        projectID := "YOUR_PROJECT_ID"

        // Creates a client.
        client, err := logging.NewClient(ctx, projectID)
        if err != nil {
                log.Fatalf("Failed to create client: %v", err)
        }
        defer client.Close()

        // Sets the name of the log to write to.
        logName := "my-log"

        logger := client.Logger(logName).StandardLogger(logging.Info)

        // Logs "hello world", log entry is visible at
        // Stackdriver Logs.
        logger.Println("hello world")
}

Here you can find documentation on Google Cloud website

Update:


Alternatively you could give a try GCP formatter for logrus

This will not tie your app to Google Cloud Platform. However, it does not mean that on another platform you will not need to change your code to format output.

Using StackDriver library is the recommended solution for Google Cloud.

like image 88
Pawel Czuczwara Avatar answered Nov 15 '22 08:11

Pawel Czuczwara