Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature logger escale #42

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
13 changes: 0 additions & 13 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
version: 2.1

orbs:
sq: escaletech/sonarqube@0.2
gh-release: escaletech/gh-conventional-release@0.1.9

jobs:
Expand All @@ -21,14 +20,6 @@ jobs:
- persist_to_workspace:
root: .
paths: [coverage]
sonar:
docker:
- image: cimg/go:1.16
steps:
- checkout
- attach_workspace:
at: .
#- sq/scanner

production_only: &production_only
filters:
Expand All @@ -46,10 +37,6 @@ workflows:
jobs:
- build-and-test:
<<: *ci_only
- sonar:
context: sonarqube
requires: [build-and-test]
<<: *ci_only
production:
jobs:
- build-and-test:
Expand Down
70 changes: 70 additions & 0 deletions logger/adapters/logrus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package adapters

import (
"os"

"github.com/escaletech/go-escale/logger"
"github.com/sirupsen/logrus"
)

var LogrusDataDogFormatter = &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "timestamp",
logrus.FieldKeyLevel: "level",
logrus.FieldKeyMsg: "message",
},
}

var levelLog = map[logger.Level]logrus.Level{
logger.DEBUG: logrus.DebugLevel,
logger.INFO: logrus.InfoLevel,
logger.WARN: logrus.WarnLevel,
logger.ERROR: logrus.ErrorLevel,
logger.FATAL: logrus.FatalLevel,
}

type logrusAdapter struct {
log *logrus.Logger
}

func NewLogrusAdapter(env string, level logger.Level) logger.Adapter {
var formatter logrus.Formatter = LogrusDataDogFormatter
if env == "dev" {
formatter = new(logrus.TextFormatter)
}

log := logrus.New()
log.SetFormatter(formatter)
log.SetLevel(levelLog[level])

return &logrusAdapter{log: log}
}

func (la *logrusAdapter) Deprecated() *logrus.Logger {
return la.log
}

func (la *logrusAdapter) Error(msg string) {
la.log.SetOutput(os.Stderr)
la.log.Error(msg)
}

func (la *logrusAdapter) Warn(msg string) {
la.log.SetOutput(os.Stderr)
la.log.Warn(msg)
}

func (la *logrusAdapter) Info(msg string) {
la.log.SetOutput(os.Stdout)
la.log.Info(msg)
}

func (la *logrusAdapter) Debug(msg string) {
la.log.SetOutput(os.Stderr)
la.log.Debug(msg)
}

func (la *logrusAdapter) Fatal(msg string) {
la.log.SetOutput(os.Stderr)
la.log.Fatal(msg)
}
59 changes: 41 additions & 18 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,54 @@
package logger

import (
"io/ioutil"
"context"
"fmt"

"github.com/sirupsen/logrus"
)

var dataDogFormatter = &logrus.JSONFormatter{
FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "timestamp",
logrus.FieldKeyLevel: "level",
logrus.FieldKeyMsg: "message",
},
type keyContext string

const (
keyTrackingId keyContext = "trackingId"
)

func NewLogger(adp Adapter, ctx context.Context) *Logger {
return &Logger{adapter: adp, ctx: ctx}
}

func (l *Logger) HandleError(err error) {
l.adapter.Error(l.prepareMessage(err.Error()))
}

func (l *Logger) Error(msg string) {
l.adapter.Error(l.prepareMessage(msg))
}

func (l *Logger) Warn(msg string) {
l.adapter.Warn(l.prepareMessage(msg))
}

func (l *Logger) Info(msg string) {
l.adapter.Info(l.prepareMessage(msg))
}

func (l *Logger) Fatal(msg string) {
l.adapter.Fatal(l.prepareMessage(msg))
}

func New(env string) *logrus.Logger {
var formatter logrus.Formatter = new(logrus.TextFormatter)
if env != "dev" {
formatter = dataDogFormatter
}
func (l *Logger) Debug(msg string) {
l.adapter.Debug(l.prepareMessage(msg))
}

logger := logrus.New()
logger.SetFormatter(formatter)
func (l *Logger) prepareMessage(msg string) string {
return fmt.Sprintf("%v [trackingId: %v]", msg, l.ctx.Value(keyTrackingId))
}

if env == "test" {
logger.Out = ioutil.Discard
}
func (l *Logger) SetTrackingId(trackingId string) {
l.ctx = context.WithValue(l.ctx, keyTrackingId, trackingId)
}

return logger
func (l *Logger) Deprecated() *logrus.Logger {
return l.adapter.Deprecated()
}
97 changes: 0 additions & 97 deletions logger/middleware.go

This file was deleted.

106 changes: 106 additions & 0 deletions logger/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package middleware

import (
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"

"github.com/escaletech/go-escale/logger"
"github.com/escaletech/go-escale/requestid"
)

type RequestLogger struct {
logger *logger.Logger
start time.Time
ResponseWriter *ResponseWriter
}

func NewRequestLogger(w http.ResponseWriter, log *logger.Logger) *RequestLogger {
tracking := requestid.GenerateTrackingId()
log.SetTrackingId(tracking)
return &RequestLogger{
logger: log,
start: time.Now(),
ResponseWriter: NewLoggerResponseWriter(w),
}
}

func (rl *RequestLogger) WriteRequestLog(r *http.Request) {
ip, _ := rl.getIP(r)

msg := fmt.Sprintf(
"[ip:%v] [iss:%v] %v %v - %v duration: %vms",
ip,
r.Host,
r.Method,
r.URL.Path,
rl.ResponseWriter.status,
time.Since(rl.start).Milliseconds(),
)

rl.logger.Info(msg)

requestInfo := rl.getRequestInfo(r)
msgLogInfoRequest := fmt.Sprintf(
"[header:%v] [request:%v]",
requestInfo["header"],
requestInfo["payload"],
)

if rl.ResponseWriter.status < http.StatusBadRequest {
rl.logger.Debug(msgLogInfoRequest)
return
}

if rl.ResponseWriter.status >= http.StatusInternalServerError {
rl.logger.Error(msgLogInfoRequest)
return
}

if rl.ResponseWriter.status < http.StatusInternalServerError {
rl.logger.Warn(msgLogInfoRequest)
}
}

func (rl *RequestLogger) getIP(r *http.Request) (string, error) {
ips := r.Header.Get("X-Forwarded-For")
splitIps := strings.Split(ips, ",")

if len(splitIps) > 0 {
netIP := net.ParseIP(splitIps[len(splitIps)-1])
if netIP != nil {
return netIP.String(), nil
}
}

ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}

netIP := net.ParseIP(ip)
if netIP == nil {
return "", errors.New("IP not found")
}

ip = netIP.String()
if ip == "::1" {
return "127.0.0.1", nil
}
return ip, nil
}

func (rl *RequestLogger) getRequestInfo(r *http.Request) logger.Fields {
headers := r.Header

if headers.Get("Authorization") != "" {
headers.Set("Authorization", "*****")
}
return logger.Fields{
"header": r.Header,
"payload": r.Body,
}
}
Loading