Skip to content
This repository was archived by the owner on May 20, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
953ea61
added http request, trace, logName and source location structures
jmcalves275 May 16, 2018
3473848
Update README.md
May 16, 2018
475780b
bug fix http request
jmcalves275 May 16, 2018
a23b1a0
change response size type
jmcalves275 May 16, 2018
d4a463c
change types of the http request struct
jmcalves275 May 16, 2018
2501d1c
added projectID and logID to build the logName correctly
jmcalves275 May 16, 2018
5e4ed8a
Format errors correctly
Jun 23, 2018
fbe0366
Merge remote-tracking branch 'brpx/master' into sd-v2
icco Dec 28, 2018
1700450
Merge remote-tracking branch 'PrimaBlock/master' into sd-v2
icco Dec 28, 2018
1af0b42
Add deps
icco Dec 28, 2018
a1ea5a7
Remove final newline
icco Dec 28, 2018
69791ff
readd newlines
icco Dec 29, 2018
7742696
use nano timestamp
icco Dec 29, 2018
933aa6f
Revert readme change
icco Dec 29, 2018
5586202
Fix all lint errors
icco Dec 31, 2018
b834d7d
Seperate out logic
icco Dec 31, 2018
99417c5
Make formatter test simpler
icco Dec 31, 2018
efa0e31
Error testing
icco Dec 31, 2018
b8620bb
Fix tests
icco Dec 31, 2018
ad83059
Add current package to stack skip
icco Dec 31, 2018
0ff02a5
Fix stack tests
icco Dec 31, 2018
63514eb
Move example
icco Dec 31, 2018
e586e52
expand travis config
icco Dec 31, 2018
5da9030
Add init func
icco Jan 7, 2019
3e11939
add http middleware
icco Jan 7, 2019
845c340
update modules
icco Jan 7, 2019
17603cf
add cloudbuild
icco Oct 28, 2019
b7db189
only build one version
icco Oct 28, 2019
a8fe26c
project root
icco Oct 28, 2019
1addc9b
just fix dir name
icco Oct 28, 2019
3f1e085
change line numbers
icco Oct 28, 2019
f50eab2
fix line numbers
icco Oct 28, 2019
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
9 changes: 3 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
language: go

go:
- 1.9.2
- "1.x"

sudo: false

install:
- go get github.com/go-stack/stack
- go get github.com/sirupsen/logrus
before_script:
- go get golang.org/x/lint/golint
- go get github.com/kr/pretty

script:
- golint -set_exit_status
- go vet
- go test
- go test -v ./...
4 changes: 4 additions & 0 deletions cloudbuild.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
steps:
- name: 'gcr.io/cloud-builders/go'
args: ['build', '.']
env: ['PROJECT_ROOT=logrus-stackdriver-formatter']
2 changes: 1 addition & 1 deletion example_test.go → example/example.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package stackdriver_test
package stackdriver_example

import (
"os"
Expand Down
123 changes: 101 additions & 22 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,35 +33,63 @@ var levelsToSeverity = map[logrus.Level]severity{
logrus.PanicLevel: severityAlert,
}

type serviceContext struct {
// ServiceContext provides the data about the service we are sending to Google.
type ServiceContext struct {
Service string `json:"service,omitempty"`
Version string `json:"version,omitempty"`
}

type reportLocation struct {
FilePath string `json:"filePath,omitempty"`
LineNumber int `json:"lineNumber,omitempty"`
FunctionName string `json:"functionName,omitempty"`
// ReportLocation is the information about where an error occurred.
type ReportLocation struct {
FilePath string `json:"file,omitempty"`
LineNumber int `json:"line,omitempty"`
FunctionName string `json:"function,omitempty"`
}

type context struct {
// Context is sent with every message to stackdriver.
type Context struct {
Data map[string]interface{} `json:"data,omitempty"`
ReportLocation *reportLocation `json:"reportLocation,omitempty"`
HTTPRequest map[string]interface{} `json:"httpRequest,omitempty"`
ReportLocation *ReportLocation `json:"reportLocation,omitempty"`
HTTPRequest *HTTPRequest `json:"httpRequest,omitempty"`
}

type entry struct {
// HTTPRequest defines details of a request and response to append to a log.
type HTTPRequest struct {
RequestMethod string `json:"requestMethod,omitempty"`
RequestURL string `json:"requestUrl,omitempty"`
RequestSize string `json:"requestSize,omitempty"`
Status string `json:"status,omitempty"`
ResponseSize string `json:"responseSize,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
RemoteIP string `json:"remoteIp,omitempty"`
ServerIP string `json:"serverIp,omitempty"`
Referer string `json:"referer,omitempty"`
Latency string `json:"latency,omitempty"`
CacheLookup bool `json:"cacheLookup,omitempty"`
CacheHit bool `json:"cacheHit,omitempty"`
CacheValidatedWithOriginServer bool `json:"cacheValidatedWithOriginServer,omitempty"`
CacheFillBytes string `json:"cacheFillBytes,omitempty"`
Protocol string `json:"protocol,omitempty"`
}

// Entry stores a log entry.
type Entry struct {
LogName string `json:"logName,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
ServiceContext *serviceContext `json:"serviceContext,omitempty"`
Message string `json:"message,omitempty"`
Severity severity `json:"severity,omitempty"`
Context *context `json:"context,omitempty"`
HTTPRequest *HTTPRequest `json:"httpRequest,omitempty"`
Trace string `json:"trace,omitempty"`
ServiceContext *ServiceContext `json:"serviceContext,omitempty"`
Message string `json:"message,omitempty"`
Context *Context `json:"context,omitempty"`
SourceLocation *ReportLocation `json:"sourceLocation,omitempty"`
}

// Formatter implements Stackdriver formatting for logrus.
type Formatter struct {
Service string
Version string
ProjectID string
StackSkip []string
}

Expand All @@ -82,6 +110,13 @@ func WithVersion(v string) Option {
}
}

// WithProjectID makes sure all entries have your Project information.
func WithProjectID(i string) Option {
return func(f *Formatter) {
f.ProjectID = i
}
}

// WithStackSkip lets you configure which packages should be skipped for locating the error.
func WithStackSkip(v string) Option {
return func(f *Formatter) {
Expand All @@ -94,6 +129,7 @@ func NewFormatter(options ...Option) *Formatter {
fmtr := Formatter{
StackSkip: []string{
"github.com/sirupsen/logrus",
"github.com/icco/logrus-stackdriver-formatter",
},
}
for _, option := range options {
Expand Down Expand Up @@ -129,26 +165,56 @@ func (f *Formatter) errorOrigin() (stack.Call, error) {
}
}

// Format formats a logrus entry according to the Stackdriver specifications.
func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
severity := levelsToSeverity[e.Level]
// taken from https://github.com/sirupsen/logrus/blob/master/json_formatter.go#L51
func replaceErrors(source logrus.Fields) logrus.Fields {
data := make(logrus.Fields, len(source))
for k, v := range source {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
return data
}

ee := entry{
// ToEntry formats a logrus entry to a stackdriver entry.
func (f *Formatter) ToEntry(e *logrus.Entry) (Entry, error) {
severity := levelsToSeverity[e.Level]

ee := Entry{
Message: e.Message,
Severity: severity,
Context: &context{
Data: e.Data,
Context: &Context{
Data: replaceErrors(e.Data),
},
}

if val, ok := e.Data["trace"]; ok {
ee.Trace = val.(string)
}

if val, exists := e.Data["httpRequest"]; exists {
r, ok := val.(*HTTPRequest)
if ok {
ee.HTTPRequest = r
}
}

if val, ok := e.Data["logID"]; ok {
ee.LogName = "projects/" + f.ProjectID + "/logs/" + val.(string)
}

if !skipTimestamp {
ee.Timestamp = time.Now().UTC().Format(time.RFC3339)
ee.Timestamp = time.Now().UTC().Format(time.RFC3339Nano)
}

switch severity {
case severityError, severityCritical, severityAlert:
ee.ServiceContext = &serviceContext{
ee.ServiceContext = &ServiceContext{
Service: f.Service,
Version: f.Version,
}
Expand All @@ -166,7 +232,7 @@ func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
// As a convenience, when using supplying the httpRequest field, it
// gets special care.
if reqData, ok := ee.Context.Data["httpRequest"]; ok {
if req, ok := reqData.(map[string]interface{}); ok {
if req, ok := reqData.(*HTTPRequest); ok {
ee.Context.HTTPRequest = req
delete(ee.Context.Data, "httpRequest")
}
Expand All @@ -176,14 +242,27 @@ func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
if c, err := f.errorOrigin(); err == nil {
lineNumber, _ := strconv.ParseInt(fmt.Sprintf("%d", c), 10, 64)

ee.Context.ReportLocation = &reportLocation{
ee.Context.ReportLocation = &ReportLocation{
FilePath: fmt.Sprintf("%+s", c),
LineNumber: int(lineNumber),
FunctionName: fmt.Sprintf("%n", c),
}

ee.SourceLocation = &ReportLocation{
FilePath: fmt.Sprintf("%+s", c),
LineNumber: int(lineNumber),
FunctionName: fmt.Sprintf("%n", c),
}
}
}

return ee, nil
}

// Format formats a logrus entry according to the Stackdriver specifications.
func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
ee, _ := f.ToEntry(e)

b, err := json.Marshal(ee)
if err != nil {
return nil, err
Expand Down
Loading