Skip to content

Commit

Permalink
Clear dependencies. Move to sentry-go. Some refactoring, lints, tests. (
Browse files Browse the repository at this point in the history
#2)

* Clear dependencies
* Move to sentry-go
* Some refactoring, lints, tests
* circleci fixes
  • Loading branch information
smgladkovskiy authored May 8, 2021
1 parent 9680bee commit 1a83227
Show file tree
Hide file tree
Showing 13 changed files with 452 additions and 225 deletions.
5 changes: 3 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ jobs:
- checkout
- run: go mod vendor
- run:
name: "Create a temp directory for artifacts"
name: "Create a temp directory for linter and artifacts"
command: |
mkdir -p /tmp/artifacts
mkdir ./bin
- run:
command: |
make lint
make test
make tests_html
mv coverage.html /tmp/artifacts
mv c.out /tmp/artifacts
- store_artifacts:
Expand Down
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
vendor
c.out
coverage.html
.golangci.yml
golangci-lint
.golangci*.yml
bin/
linter.mk
tests.mk
38 changes: 14 additions & 24 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,41 +1,31 @@
# ----
## LINTER stuff start
LINTER_VERSION=v1.27.0

get_lint_binary:
@[ -f ./golangci-lint ] && echo "golangci-lint exists" || ( echo "getting golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b ./ $(LINTER_VERSION) && ./golangci-lint --version )
.PHONY: get_lint_binary
linter_include_check:
@[ -f linter.mk ] && echo "linter.mk include exists" || (echo "getting linter.mk from github.com" && curl -sO https://raw.githubusercontent.com/spacetab-io/makefiles/master/golang/linter.mk)

get_lint_config:
@[ -f .golangci.yml ] && echo ".golangci.yml exists" || ( echo "getting .golangci.yml" && curl -O https://raw.githubusercontent.com/microparts/docker-golang/master/.golangci.yml )
.PHONY: get_lint_config

lint: get_lint_binary get_lint_config
./golangci-lint run -v
.PHONY: lint

lint_quiet: get_lint_binary get_lint_config
@./golangci-lint run
.PHONY: lint_quiet
lint: linter_include_check
make -f linter.mk go_lint

## LINTER stuff end
# ----

# ----
## TEST stuff start
## TESTS stuff start

test-unit:
go test $$(go list ./...) --race --cover -count=1 -timeout 1s -coverprofile=c.out -v
.PHONY: test-unit
tests_include_check:
@[ -f tests.mk ] && echo "tests.mk include exists" || (echo "getting tests.mk from github.com" && curl -sO https://raw.githubusercontent.com/spacetab-io/makefiles/master/golang/tests.mk)

coverage-html:
go tool cover -html=c.out -o coverage.html
.PHONE: coverage-html
tests: tests_include_check
@make -f tests.mk go_tests
.PHONY: tests

test: test-unit coverage-html
.PHONY: test
tests_html: tests_include_check
@make -f tests.mk go_tests_html
.PHONY: tests_html

## TEST stuff end
## TESTS stuff end
# ----

circle:
Expand Down
1 change: 1 addition & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ type Config struct {
type SentryConfig struct {
DSN string `yaml:"dsn"`
Enable bool `yaml:"enable"`
Debug bool `yaml:"debug"`
}
7 changes: 5 additions & 2 deletions fasthttp_test.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package log
package log_test

import (
"bytes"
"testing"

log "github.com/spacetab-io/logs-go/v2"
"github.com/stretchr/testify/assert"
)

func TestFHLogger_Printf(t *testing.T) {
t.Parallel()

out := &bytes.Buffer{}
_ = initLog(out)
fhl := FHLogger{}
fhl := log.FHLogger{}
fhl.Printf("some %s", "data")

exp := "DBG |> some data <|"
Expand Down
11 changes: 4 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@ module github.com/spacetab-io/logs-go/v2
go 1.14

require (
github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054 // indirect
github.com/getsentry/raven-go v0.2.0
github.com/google/uuid v1.1.5
github.com/json-iterator/go v1.1.10
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.20.0
github.com/stretchr/testify v1.3.0
github.com/getsentry/sentry-go v0.10.0
github.com/json-iterator/go v1.1.11
github.com/rs/zerolog v1.21.0
github.com/stretchr/testify v1.7.0
)
200 changes: 189 additions & 11 deletions go.sum

Large diffs are not rendered by default.

70 changes: 34 additions & 36 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import (
"os"
"time"

"github.com/getsentry/raven-go"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/getsentry/sentry-go"
"github.com/rs/zerolog"
)

Expand All @@ -23,7 +21,7 @@ const (
standAloneCallerSkipFrames = 6
)

type zLogger struct {
type ZLogger struct {
zerolog.Logger
cfg Config
}
Expand All @@ -38,7 +36,7 @@ var logger, _ = newZerolog(
os.Stdout,
)

// set global Zerolog logger
// set global Zerolog logger.
func Init(stage string, cfg Config, serviceAlias string, serviceVersion string, w io.Writer) (err error) {
if w == nil {
w = os.Stdout
Expand All @@ -56,47 +54,42 @@ func Init(stage string, cfg Config, serviceAlias string, serviceVersion string,

if cfg.Sentry == nil || !cfg.Sentry.Enable || cfg.Sentry.DSN == "" {
logger, err = newZerolog(cfg, w)
return err
if err != nil {
return fmt.Errorf("logger init newZerolog error: %w", err)
}

return nil
}

client, err := raven.New(cfg.Sentry.DSN)
sentrySyncTransport := sentry.NewHTTPSyncTransport()
sentrySyncTransport.Timeout = time.Second * 2 //nolint:gomnd // 2 second transport timeout

client, err := sentry.NewClient(sentry.ClientOptions{
Dsn: cfg.Sentry.DSN,
DebugWriter: os.Stderr,
Debug: cfg.Sentry.Debug,
ServerName: serviceAlias,
Release: serviceVersion,
Environment: stage,
Transport: sentrySyncTransport,
})
if err != nil {
return err
return fmt.Errorf("logger init raven.New error: %w", err)
}

h := sentry.NewHub(client, sentry.NewScope())

pr, pw := io.Pipe()

go sentryPush(stage, serviceAlias, serviceVersion, client, pr)
go sentryPush(h, pr)

cfg.Format = FormatJSON
logger, err = newZerolog(cfg, io.MultiWriter(w, pw))

return err
}

func newZerolog(cfg Config, w io.Writer) (logger zLogger, err error) {
// setup a global function that transforms any error passed to
// zerolog to an error with stack strace.
zerolog.ErrorMarshalFunc = func(err error) interface{} {
if cfg.Sentry == nil {
return err
}

es := errWithStackTrace{
Err: err.Error(),
}

if _, ok := err.(stackTracer); !ok {
err = errors.WithStack(err)
}

if cfg.Sentry != nil && cfg.Sentry.Enable {
es.Stacktrace = stackTraceToSentry(err.(stackTracer).StackTrace())
}

return &es
}

func newZerolog(cfg Config, w io.Writer) (logger ZLogger, err error) {
// UNIX Time is faster and smaller than most timestamps
// If you set zerolog.TimeFieldFormat to an empty string,
// logs will write with UNIX time
Expand Down Expand Up @@ -159,19 +152,20 @@ func getLevel(lvl string) (zerolog.Level, error) {

level, err := zerolog.ParseLevel(lvl)
if err != nil {
return zerolog.DebugLevel, err
return zerolog.DebugLevel, fmt.Errorf("get level error: %w", err)
}

return level, nil
}

func Logger() zerolog.Logger {
return logger.Logger
func Logger() ZLogger {
return logger
}

// Output duplicates the global logger and sets w as its output.
func Output(w io.Writer) zerolog.Logger {
l, _ := newZerolog(logger.cfg, w)

return l.Logger
}

Expand Down Expand Up @@ -296,7 +290,11 @@ func Ctx(ctx context.Context) *zerolog.Logger {

func contextFields(ctx context.Context) (fields map[string]interface{}) {
fields = make(map[string]interface{})
if requestID, ok := ctx.Value(ctxRequestIDKey).(uuid.UUID); ok && requestID != uuid.Nil {
if requestID, ok := ctx.Value(ctxRequestIDKey).(fmt.Stringer); ok && requestID.String() != "00000000-0000-0000-0000-000000000000" {
fields[ctxRequestIDKey] = requestID.String()
}

if requestID, ok := ctx.Value(ctxRequestIDKey).(string); ok && requestID != "00000000-0000-0000-0000-000000000000" {
fields[ctxRequestIDKey] = requestID
}

Expand Down
61 changes: 61 additions & 0 deletions logger_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package log

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
)

func Test_contextFields(t *testing.T) {
type tc struct {
name string
in context.Context
exp map[string]interface{}
}

rID := newTestUUID("45bf025d-9e46-45a4-8562-c37c4d48a9ca")

tcs := []tc{
{
name: "context with requers_id",
in: context.WithValue(context.Background(), ctxRequestIDKey, rID), //nolint:staticcheck // да ладно!
exp: map[string]interface{}{ctxRequestIDKey: rID.String()},
},
{
name: "empty context",
in: context.Background(),
exp: map[string]interface{}{},
},
{
name: "string equest id",
in: context.WithValue(context.Background(), ctxRequestIDKey, rID.String()), //nolint:staticcheck // ну хорош!
exp: map[string]interface{}{ctxRequestIDKey: rID.String()},
},
}

t.Parallel()

for _, tc := range tcs {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

out := contextFields(tc.in)

assert.Equal(t, tc.exp, out)
})
}
}

type testUUID struct {
str string
}

func (t testUUID) String() string {
return t.str
}

func newTestUUID(str string) testUUID {
return testUUID{str: str}
}
Loading

0 comments on commit 1a83227

Please sign in to comment.