Skip to content

Commit

Permalink
Remove relative path from filenames
Browse files Browse the repository at this point in the history
Beacuse it is much easier to read [main.go:33] than
[/home/kgr/git/test_runlogger/main.go:33]. And it makes even less sence
when using this in the cloud...
  • Loading branch information
karl-gustav committed May 13, 2022
1 parent c557224 commit 2e1d20c
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strconv"
"time"
Expand All @@ -30,16 +31,25 @@ var stdout = bufio.NewWriter(os.Stdout)

type Logger struct{}

var prefixPath string

// StructuredLogger is used to have structured logging in stackdriver (Google Cloud Platform)
func StructuredLogger() *Logger {
setPrefixPath()
return &Logger{}
}

// PlainLogger is used when you are not in a cloud run environment
func PlainLogger() *Logger {
setPrefixPath()
return nil
}

func setPrefixPath() {
_, fileName, _, _ := runtime.Caller(2)
prefixPath = filepath.Dir(fileName) + "/"
}

func (l *Logger) Debug(v ...interface{}) {
l.writeLog(debug_severety, fmt.Sprint(v...), nil)
}
Expand Down Expand Up @@ -141,9 +151,9 @@ func (l *Logger) writeLog(severety severety, message string, obj interface{}) {
if l == nil {
if obj != nil {
j, _ := json.Marshal(obj)
fmt.Printf("%s in [%s:%d]: %s\n%s\n", severety, file, line, message, j)
fmt.Printf("%s in [%s:%d]: %s\n%s\n", severety, relative(file), line, message, j)
} else {
fmt.Printf("%s in [%s:%d]: %s\n", severety, file, line, message)
fmt.Printf("%s in [%s:%d]: %s\n", severety, relative(file), line, message)
}
return
}
Expand All @@ -154,7 +164,7 @@ func (l *Logger) writeLog(severety severety, message string, obj interface{}) {
Severity: severety,
Timestamp: time.Now(),
SourceLocation: &sourceLocation{
File: file,
File: relative(file),
Function: runtime.FuncForPC(pc).Name(),
Line: strconv.Itoa(line),
},
Expand All @@ -171,6 +181,13 @@ func (l *Logger) writeLog(severety severety, message string, obj interface{}) {
}
}

func relative(path string) string {
if filepath.HasPrefix(path, prefixPath) {
return path[len(prefixPath):]
}
return path
}

// stackdriverLogStruct source https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
type stackdriverLogStruct struct {
TextPayload string `json:"message,omitempty"`
Expand Down

0 comments on commit 2e1d20c

Please sign in to comment.