From d41631a2db6d38f9fb0065f4ec369cace47fb408 Mon Sep 17 00:00:00 2001 From: Manfred Touron <94029+moul@users.noreply.github.com> Date: Sat, 27 Jun 2020 00:16:52 +0200 Subject: [PATCH] feat: initial version --- Dockerfile | 31 ---------------- Makefile | 3 -- README.md | 16 +++++---- doc.go | 2 +- go.mod | 6 ++-- go.sum | 42 +++++++++++++++++----- main.go | 25 ------------- main_test.go | 18 ---------- package.json | 21 ----------- zapgorm2.go | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 147 insertions(+), 117 deletions(-) delete mode 100644 Dockerfile delete mode 100644 main.go delete mode 100644 main_test.go delete mode 100644 package.json create mode 100644 zapgorm2.go diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 0fe214e..0000000 --- a/Dockerfile +++ /dev/null @@ -1,31 +0,0 @@ -# dynamic config -ARG BUILD_DATE -ARG VCS_REF -ARG VERSION - -# build -FROM golang:1.14-alpine as builder -RUN apk add --no-cache git gcc musl-dev make -ENV GO111MODULE=on -WORKDIR /go/src/moul.io/zapgorm2 -COPY go.* ./ -RUN go mod download -COPY . ./ -RUN make install - -# minimalist runtime -FROM alpine:3.12 -LABEL org.label-schema.build-date=$BUILD_DATE \ - org.label-schema.name="zapgorm2" \ - org.label-schema.description="" \ - org.label-schema.url="https://moul.io/zapgorm2/" \ - org.label-schema.vcs-ref=$VCS_REF \ - org.label-schema.vcs-url="https://github.com/moul/zapgorm2" \ - org.label-schema.vendor="Manfred Touron" \ - org.label-schema.version=$VERSION \ - org.label-schema.schema-version="1.0" \ - org.label-schema.cmd="docker run -i -t --rm moul/zapgorm2" \ - org.label-schema.help="docker exec -it $CONTAINER zapgorm2 --help" -COPY --from=builder /go/bin/zapgorm2 /bin/ -ENTRYPOINT ["/bin/zapgorm2"] -#CMD [] diff --git a/Makefile b/Makefile index bcb248f..92ab80b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,3 @@ GOPKG ?= moul.io/zapgorm2 -DOCKER_IMAGE ?= moul/zapgorm2 -GOBINS ?= . -NPM_PACKAGES ?= . include rules.mk diff --git a/README.md b/README.md index af7b423..6b81cda 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ # zapgorm2 -:smile: zapgorm2 +:smile: zapgorm2 is a zap logging driver for gorm v2 [![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white)](https://pkg.go.dev/moul.io/zapgorm2) [![License](https://img.shields.io/badge/license-Apache--2.0%20%2F%20MIT-%2397ca00.svg)](https://github.com/moul/zapgorm2/blob/master/COPYRIGHT) [![GitHub release](https://img.shields.io/github/release/moul/zapgorm2.svg)](https://github.com/moul/zapgorm2/releases) -[![Docker Metrics](https://images.microbadger.com/badges/image/moul/zapgorm2.svg)](https://microbadger.com/images/moul/zapgorm2) [![Made by Manfred Touron](https://img.shields.io/badge/made%20by-Manfred%20Touron-blue.svg?style=flat)](https://manfred.life/) [![CI](https://github.com/moul/zapgorm2/workflows/CI/badge.svg)](https://github.com/moul/zapgorm2/actions?query=workflow%3ACI) @@ -15,10 +14,17 @@ [![Go Report Card](https://goreportcard.com/badge/moul.io/zapgorm2)](https://goreportcard.com/report/moul.io/zapgorm2) [![CodeFactor](https://www.codefactor.io/repository/github/moul/zapgorm2/badge)](https://www.codefactor.io/repository/github/moul/zapgorm2) +If you're using gorm v1, you can use https://github.com/moul/zapgorm instead. ## Usage -TODO +```go +import "moul.io/zapgorm2" + +logger := zapgorm2.New(zap.L()) +logger.SetAsDefault() // optional: configure gorm to use this zapgorm.Logger for callbacks +db, err = gorm.Open(sqlite.Open("./db.sqlite"), &gorm.Config{Logger: logger}) +``` ## Install @@ -28,10 +34,6 @@ TODO $ go get -u moul.io/zapgorm2 ``` -### Releases - -See https://github.com/moul/zapgorm2/releases - ## Stargazers over time [![Stargazers over time](https://starchart.cc/moul/zapgorm2.svg)](https://starchart.cc/moul/zapgorm2) diff --git a/doc.go b/doc.go index 67d0ef1..48949f0 100644 --- a/doc.go +++ b/doc.go @@ -26,4 +26,4 @@ // |/ | | \ \ / / ' \/ _ \/ // / / | // || | | | | | /_/_/_/\___/\_,_/_/ | // +--------------------------------------------------------------+ -package main // import "moul.io/zapgorm2" +package zapgorm2 diff --git a/go.mod b/go.mod index 656c745..e3d3c51 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module moul.io/zapgorm2 go 1.13 require ( - go.uber.org/goleak v1.0.0 - moul.io/motd v1.0.0 - moul.io/srand v1.4.0 + go.uber.org/zap v1.15.0 + golang.org/x/tools v0.0.0-20191108193012-7d206e10da11 // indirect + gorm.io/gorm v0.2.18 ) diff --git a/go.sum b/go.sum index f4c9b6e..fdea221 100644 --- a/go.sum +++ b/go.sum @@ -1,37 +1,63 @@ +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E= +github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -go.uber.org/goleak v1.0.0 h1:qsup4IcBdlmsnGfqyLl4Ntn3C2XCCuKAE7DwHpScyUo= -go.uber.org/goleak v1.0.0/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.15.0 h1:ZZCA22JRF2gQE5FoNmhmrf7jeJJ2uhqDUNRYKm8dvmM= +go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11 h1:Yq9t9jnGoR+dBuitxdo9l6Q7xh/zOyNnYUtDKaQ3x0E= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -moul.io/banner v1.0.1 h1:+WsemGLhj2pOajw2eR5VYjLhOIqs0XhIRYchzTyMLk0= -moul.io/banner v1.0.1/go.mod h1:XwvIGKkhKRKyN1vIdmR5oaKQLIkMhkMqrsHpS94QzAU= -moul.io/motd v1.0.0 h1:Trk4fPibDfPJf2iCBSQC8ws7Q02sMwivQdVEFAjCPto= -moul.io/motd v1.0.0/go.mod h1:39rvZ0lC2oRhHDY2VoPyZ8r70VKqeJye3QAxjeLDJso= -moul.io/srand v1.4.0 h1:r5ZMiWDN0ni0lTV7KzJR/jx0K7GivJYW5WaXmufgeik= -moul.io/srand v1.4.0/go.mod h1:P2uaZB+GFstFNo8sEj6/U8FRV1n25kD0LLckFpJ+qvc= +gorm.io/gorm v0.2.18 h1:Sij/WJhJFmP8mGbq1Rc2uTZQGExC0kyFQNLKBBUQiDU= +gorm.io/gorm v0.2.18/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/main.go b/main.go deleted file mode 100644 index 3b5cdac..0000000 --- a/main.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "log" - "os" - - "moul.io/motd" - "moul.io/srand" -) - -func main() { - if err := run(os.Args); err != nil { - log.Fatalf("error: %v", err) - os.Exit(1) - } -} - -// nolint:unparam -func run(args []string) error { - srand.Fast() - fmt.Print(motd.Default()) - fmt.Println("Hello World!", args) - return nil -} diff --git a/main_test.go b/main_test.go deleted file mode 100644 index af8507f..0000000 --- a/main_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package main - -import ( - "testing" - - "go.uber.org/goleak" -) - -func TestRun(t *testing.T) { - err := run(nil) - if err != nil { - t.Fatalf("err should be nil: %v", err) - } -} - -func TestMain(m *testing.M) { - goleak.VerifyTestMain(m) -} diff --git a/package.json b/package.json deleted file mode 100644 index 862415e..0000000 --- a/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "_comment": "this project is not a node.js one, package.json is just used to define some metadata", - "name": "@moul.io/zapgorm2", - "version": "0.0.1", - "author": "Manfred Touron (https://manfred.life)", - "contributors": [ - "Manfred Touron (https://manfred.life)" - ], - "license": "(Apache-2.0 OR MIT)", - "scripts": { - "start": "zapgorm2", - "install": "make install", - "test": "make test" - }, - "repository": { - "type": "git", - "url": "https://github.com/moul/zapgorm2.git" - }, - "bugs": "https://github.com/moul/zapgorm2/issues", - "homepage": "https://moul.io/zapgorm2" -} diff --git a/zapgorm2.go b/zapgorm2.go new file mode 100644 index 0000000..f2c32cf --- /dev/null +++ b/zapgorm2.go @@ -0,0 +1,100 @@ +package zapgorm2 + +import ( + "context" + "path/filepath" + "runtime" + "strings" + "time" + + "go.uber.org/zap" + gormlogger "gorm.io/gorm/logger" +) + +type Logger struct { + ZapLogger *zap.Logger + LogLevel gormlogger.LogLevel + SlowThreshold time.Duration + SkipCallerLookup bool +} + +func New(zapLogger *zap.Logger) Logger { + return Logger{ + ZapLogger: zapLogger, + LogLevel: gormlogger.Warn, + SlowThreshold: 100 * time.Millisecond, + SkipCallerLookup: false, + } +} + +func (l Logger) SetAsDefault() { + gormlogger.Default = l +} + +func (l Logger) LogMode(level gormlogger.LogLevel) gormlogger.Interface { + return Logger{ + ZapLogger: l.ZapLogger, + SlowThreshold: l.SlowThreshold, + LogLevel: level, + SkipCallerLookup: l.SkipCallerLookup, + } +} + +func (l Logger) Info(ctx context.Context, str string, args ...interface{}) { + if l.LogLevel < gormlogger.Info { + return + } + l.logger().Sugar().Debugf(str, args...) +} + +func (l Logger) Warn(ctx context.Context, str string, args ...interface{}) { + if l.LogLevel < gormlogger.Warn { + return + } + l.logger().Sugar().Warnf(str, args...) +} + +func (l Logger) Error(ctx context.Context, str string, args ...interface{}) { + if l.LogLevel < gormlogger.Error { + return + } + l.logger().Sugar().Errorf(str, args...) +} + +func (l Logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { + if l.LogLevel <= 0 { + return + } + elapsed := time.Since(begin) + switch { + case err != nil && l.LogLevel >= gormlogger.Error: + sql, rows := fc() + l.logger().Error("trace", zap.Error(err), zap.Duration("elapsed", elapsed), zap.Int64("rows", rows), zap.String("sql", sql)) + case l.SlowThreshold != 0 && elapsed > l.SlowThreshold && l.LogLevel >= gormlogger.Warn: + sql, rows := fc() + l.logger().Warn("trace", zap.Duration("elapsed", elapsed), zap.Int64("rows", rows), zap.String("sql", sql)) + case l.LogLevel >= gormlogger.Info: + sql, rows := fc() + l.logger().Debug("trace", zap.Duration("elapsed", elapsed), zap.Int64("rows", rows), zap.String("sql", sql)) + } +} + +var ( + gormPackage = filepath.Join("gorm.io", "gorm") + zapgormPackage = filepath.Join("moul.io", "zapgorm2") +) + +func (l Logger) logger() *zap.Logger { + for i := 2; i < 15; i++ { + _, file, _, ok := runtime.Caller(i) + switch { + case !ok: + case strings.HasSuffix(file, "_test.go"): + case strings.Contains(file, gormPackage): + case strings.Contains(file, zapgormPackage): + default: + return l.ZapLogger.WithOptions(zap.AddCallerSkip(i)) + } + } + return l.ZapLogger +}