Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: golangci-lint
on:
push:
branches:
- master
pull_request:
branches:
- master
env:
GOPRIVATE: "github.com/Khan"
GOFLAGS: "-trimpath"
GO_VERSION: 1.18
jobs:
golangci:
name: Linter
runs-on: ubuntu-latest
steps:
- name: Install Go
uses: actions/setup-go@v2
with:
# stable: 'false' # Keep this line to be able to use rc and beta version of Go (ex: 1.18.0-rc1).
go-version: ${{ env.GO_VERSION }}
- uses: actions/checkout@v2
- name: lint
uses: golangci/golangci-lint-action@v3.1.0
with:
version: latest
# skip cache because of flaky behaviors
skip-build-cache: true
skip-pkg-cache: true
args: --timeout 5m --issues-exit-code=0
# only-new-issues: true #show only new issues if it's a pull request. options working-directory and only-new-issues are incompatible
28 changes: 28 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Test
on:
push:
branches:
- master
pull_request:
branches:
- master
env:
GOPRIVATE: "github.com/Khan"
GOFLAGS: "-trimpath"
GO_VERSION: 1.18
jobs:
test:
# runs-on: [self-hosted, linux, x64]
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- name: Install Go
uses: actions/setup-go@v2
with:
go-version: ${{ env.GO_VERSION }}
- name: Checkout code
uses: actions/checkout@v2
- name: Test
run: |-
echo "starting go tests without race"
go test ./... -timeout 5m -v -trimpath
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# logrus-stackdriver-formatter

[![Go Report Card](https://goreportcard.com/badge/github.com/StevenACoffman/logrus-stackdriver-formatter)](https://goreportcard.com/report/github.com/StevenACoffman/logrus-stackdriver-formatter)
[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/StevenACoffman/logrus-stackdriver-formatter)
[![License MIT](https://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat)](https://github.com/StevenACoffman/logrus-stackdriver-formatter#license)
[![Go Report Card](https://goreportcard.com/badge/github.com/Mattel/logrus-stackdriver-formatter)](https://goreportcard.com/report/github.com/Mattel/logrus-stackdriver-formatter)
[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/Mattel/logrus-stackdriver-formatter)
[![License MIT](https://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat)](https://github.com/Mattel/logrus-stackdriver-formatter#license)

Logrus-stackdriver-formatter provides:
+ [logrus](https://github.com/sirupsen/logrus) formatter for Stackdriver.
Expand All @@ -23,7 +23,7 @@ package main

import (

stackdriver "github.com/StevenACoffman/logrus-stackdriver-formatter"
stackdriver "github.com/Mattel/logrus-stackdriver-formatter"
"github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -52,7 +52,7 @@ Here's a sample entry (prettified) from the example:
"severity": "ERROR",
"context": {
"reportLocation": {
"file": "github.com/StevenACoffman/logrus-stackdriver-formatter/example_test.go",
"file": "github.com/Mattel/logrus-stackdriver-formatter/example_test.go",
"line": 21,
"function": "ExampleLogError"
}
Expand Down Expand Up @@ -99,7 +99,7 @@ and log-structured data streams.
```go
import (
"os"
logadapter "github.com/StevenACoffman/logrus-stackdriver-formatter"
logadapter "github.com/Mattel/logrus-stackdriver-formatter"
kitlog "github.com/go-kit/kit/log"
)

Expand All @@ -118,7 +118,7 @@ func main() {
```go
import (
"os"
logadapter "github.com/StevenACoffman/logrus-stackdriver-formatter"
logadapter "github.com/Mattel/logrus-stackdriver-formatter"
kitlog "github.com/go-kit/kit/log"
)

Expand Down
96 changes: 84 additions & 12 deletions example/example_test.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,108 @@
package logadapterexample

import (
"os"
"bufio"
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"

"github.com/gofrs/uuid"
"go.opentelemetry.io/otel/trace"

stackdriver "github.com/Mattel/logrus-stackdriver-formatter"
"github.com/sirupsen/logrus"
)

var (
TraceFlags = trace.FlagsSampled
TraceID = uuid.Must(uuid.FromString("105445aa7843bc8bf206b12000100000"))
SpanID = [8]byte{0, 0, 0, 0, 0, 0, 0, 1}
SpanContext = trace.SpanContext{}.WithSpanID(SpanID).
WithTraceID(trace.TraceID(TraceID)).
WithTraceFlags(TraceFlags)
)

func ExampleWithError() {
logger := logrus.New()
logger.Out = os.Stdout
var b bytes.Buffer
foo := bufio.NewWriter(&b)
logger.Out = foo
logger.Formatter = stackdriver.NewFormatter(
stackdriver.WithService("test-service"),
stackdriver.WithVersion("v0.1.0"),
stackdriver.WithSkipTimestamp(),
stackdriver.WithGlobalTraceID(TraceID),
)

logger.Info("application up and running")
logger.WithField("span_context", SpanContext).Info("application up and running")

_, err := strconv.ParseInt("text", 10, 64)
if err != nil {
logger.WithError(err).WithField("trace", "1").Errorln("unable to parse integer")
logger.WithField("span_context", SpanContext).WithError(err).
Errorln("unable to parse integer")
}
foo.Flush()

fmt.Println(PrettyString(b.String()))

// Output:
// {"message":"application up and running","severity":"INFO","context":{}}
// {"serviceContext":{"service":"test-service","version":"v0.1.0"},"message":
// "unable to parse integer\nstrconv.ParseInt:
// parsing \"text\": invalid syntax","severity":"ERROR","context":
// {"reportLocation":
// {"file":"testing/example_test.go","line":121,"function":"runExample"}},
// "sourceLocation":
// {"file":"testing/example_test.go","line":121,"function":"runExample"}}
// {
// "logName": "projects//logs/test-service",
// "message": "application up and running",
// "severity": "INFO",
// "context": {},
// "logging.googleapis.com/sourceLocation": {
// "file": "testing/run_example.go",
// "line": 63,
// "function": "runExample"
// },
// "logging.googleapis.com/trace": "projects//traces/105445aa7843bc8bf206b12000100000",
// "logging.googleapis.com/spanId": "0000000000000001",
// "logging.googleapis.com/trace_sampled": true
// }
// {
// "@type": "type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent",
// "logName": "projects//logs/test-service",
// "serviceContext": {
// "service": "test-service",
// "version": "v0.1.0"
// },
// "message": "unable to parse integer\nstrconv.ParseInt: parsing \"text\": invalid syntax",
// "severity": "ERROR",
// "context": {
// "data": {
// "error": "strconv.ParseInt: parsing \"text\": invalid syntax"
// },
// "reportLocation": {
// "filePath": "testing/run_example.go",
// "lineNumber": 63,
// "functionName": "runExample"
// }
// },
// "logging.googleapis.com/sourceLocation": {
// "file": "testing/run_example.go",
// "line": 63,
// "function": "runExample"
// },
// "logging.googleapis.com/trace": "projects//traces/105445aa7843bc8bf206b12000100000",
// "logging.googleapis.com/spanId": "0000000000000001",
// "logging.googleapis.com/trace_sampled": true
// }
}

func PrettyString(str string) string {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
if strings.Contains(str, "\n") {
var pieces []string
for _, split := range strings.Split(str, "\n") {
pieces = append(pieces, PrettyString(split))
}
return strings.Join(pieces, "\n")
}
return str
}
return prettyJSON.String()
}
10 changes: 6 additions & 4 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ func (f *Formatter) ToEntry(e *logrus.Entry) (Entry, error) {

// @type as ReportedErrorEvent if all required fields may be provided
// https://cloud.google.com/error-reporting/docs/formatting-error-messages#json_representation
if len(message) > 0 && ee.ServiceContext.Service != "" && (ee.StackTrace != "" || ee.SourceLocation != nil) {
if len(message) > 0 && ee.ServiceContext.Service != "" &&
(ee.StackTrace != "" || ee.SourceLocation != nil) {
ee.Type = reportedErrorEventType
}
}
Expand All @@ -347,9 +348,10 @@ func (f *Formatter) ToEntry(e *logrus.Entry) (Entry, error) {
delete(ee.Context.Data, "httpRequest")
}

// Promote the httpRequest details to parent entry so logs may be presented with HTTP request details
// Only do this when the logging middleware provides special instructions in log entry context to do so,
// as the resulting log message summary line is specially formatted to ignore the payload message
// Promote the httpRequest details to parent entry so logs may be presented with HTTP request
// details Only do this when the logging middleware provides special instructions in log entry
// context to do so, as the resulting log message summary line is specially formatted to ignore
// the payload message
if req, ok := ee.Context.Data["httpRequest"].(requestDetails); ok {
ee.HTTPRequest = req.HTTPRequest
delete(ee.Context.Data, "httpRequest")
Expand Down
Loading