# README
logrus-stackdriver-formatter
logrus formatter for Stackdriver.
In addition to supporting level-based logging to Stackdriver, for Error, Fatal and Panic levels it will append error context for Error Reporting.
Installation
go get -u github.com/TV4/logrus-stackdriver-formatter
Usage
package main
import (
"github.com/sirupsen/logrus"
stackdriver "github.com/TV4/logrus-stackdriver-formatter"
)
var log = logrus.New()
func init() {
log.Formatter = stackdriver.NewFormatter(
stackdriver.WithService("your-service"),
stackdriver.WithVersion("v0.1.0"),
)
log.Level = logrus.DebugLevel
log.Info("ready to log!")
}
Here's a sample entry (prettified) from the example:
{
"serviceContext": {
"service": "test-service",
"version": "v0.1.0"
},
"message": "unable to parse integer: strconv.ParseInt: parsing \"text\": invalid syntax",
"severity": "ERROR",
"context": {
"reportLocation": {
"filePath": "github.com/TV4/logrus-stackdriver-formatter/example_test.go",
"lineNumber": 21,
"functionName": "ExampleLogError"
}
}
}
HTTP request context
If you'd like to add additional context like the httpRequest
, here's a convenience function for creating a HTTP logger:
func httpLogger(logger *logrus.Logger, r *http.Request) *logrus.Entry {
return logger.WithFields(logrus.Fields{
"httpRequest": map[string]interface{}{
"method": r.Method,
"url": r.URL.String(),
"userAgent": r.Header.Get("User-Agent"),
"referrer": r.Header.Get("Referer"),
},
})
}
Then, in your HTTP handler, create a new context logger and all your log entries will have the HTTP request context appended to them:
func handler(w http.ResponseWriter, r *http.Request) {
httplog := httpLogger(log, r)
// ...
httplog.Infof("Logging with HTTP request context")
}
# Functions
InitLogging initializes a logger to send things to stackdriver.
LoggingMiddleware is a middleware for writing request logs in a stuctured format to stackdriver.
NewFormatter returns a new Formatter.
WithProjectID makes sure all entries have your Project information.
WithService lets you configure the service name used for error reporting.
WithStackSkip lets you configure which packages should be skipped for locating the error.
WithVersion lets you configure the service version used for error reporting.
# Structs
Context is sent with every message to stackdriver.
Entry stores a log entry.
Formatter implements Stackdriver formatting for logrus.
HTTPRequest defines details of a request and response to append to a log.
ReportLocation is the information about where an error occurred.
ServiceContext provides the data about the service we are sending to Google.
# Type aliases
Option lets you configure the Formatter.