Skip to content

Commit

Permalink
fix: improve log support
Browse files Browse the repository at this point in the history
Signed-off-by: closetool <[email protected]>
  • Loading branch information
kilosonc committed Apr 28, 2021
1 parent 40a8c16 commit e5dd073
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ import (
"github.com/jackc/pgconn"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"

//"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

const (
Expand Down Expand Up @@ -278,6 +280,11 @@ func (a *Adapter) open() error {
return a.createTable()
}

// AddLogger adds logger to db
func (a *Adapter) AddLogger(l logger.Interface) {
a.db = a.db.Session(&gorm.Session{Logger: l, Context: a.db.Statement.Context})
}

func (a *Adapter) close() error {
a.db = nil
return nil
Expand Down
14 changes: 14 additions & 0 deletions adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package gormadapter

import (
"log"
"os"
"testing"

"github.com/casbin/casbin/v2"
Expand All @@ -27,6 +28,7 @@ import (
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

func testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) {
Expand Down Expand Up @@ -428,7 +430,19 @@ func TestAdapters(t *testing.T) {
testUpdatePolicies(t, a)
testUpdateFilteredPolicies(t, a)

a = initAdapter(t, "mysql", "root:@tcp(127.0.0.1:3306)/", "casbin", "casbin_rule")
a.AddLogger(logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{}))
testUpdatePolicy(t, a)
testUpdatePolicies(t, a)
testUpdateFilteredPolicies(t, a)

a = initAdapter(t, "postgres", "user=postgres password=postgres host=127.0.0.1 port=5432 sslmode=disable")
testUpdatePolicy(t, a)
testUpdatePolicies(t, a)
testUpdateFilteredPolicies(t, a)

a = initAdapter(t, "postgres", "user=postgres password=postgres host=127.0.0.1 port=5432 sslmode=disable")
a.AddLogger(logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{}))
testUpdatePolicy(t, a)
testUpdatePolicies(t, a)
testUpdateFilteredPolicies(t, a)
Expand Down

0 comments on commit e5dd073

Please sign in to comment.