diff --git a/config.go b/config.go index 4735aa67325315f138441aef689826a8d3f71970..26cb1523f8c12786bae5734c41736c0e3d6bb16c 100644 --- a/config.go +++ b/config.go @@ -1,6 +1,7 @@ package db import ( + "sync" "sync/atomic" ) @@ -20,19 +21,28 @@ type Settings interface { type conf struct { loggingEnabled uint32 - queryLogger atomic.Value - defaultLogger defaultLogger + + queryLogger Logger + queryLoggerMu sync.RWMutex + defaultLogger defaultLogger } func (c *conf) Logger() Logger { - if lg := c.queryLogger.Load(); lg != nil { - return lg.(Logger) + c.queryLoggerMu.RLock() + defer c.queryLoggerMu.RUnlock() + + if c.queryLogger == nil { + return &c.defaultLogger } - return &c.defaultLogger + + return c.queryLogger } func (c *conf) SetLogger(lg Logger) { - c.queryLogger.Store(lg) + c.queryLoggerMu.Lock() + defer c.queryLoggerMu.Unlock() + + c.queryLogger = lg } func (c *conf) SetLogging(value bool) { diff --git a/internal/sqladapter/testing/adapter.go.tpl b/internal/sqladapter/testing/adapter.go.tpl index 37d786e9f522341d1191b1bc29f544a2591c4428..92b2e89974a7cf18ef88c23e1444cbc9f8467527 100644 --- a/internal/sqladapter/testing/adapter.go.tpl +++ b/internal/sqladapter/testing/adapter.go.tpl @@ -20,6 +20,18 @@ import ( "upper.io/db.v2/lib/sqlbuilder" ) +type customLogger struct { +} + +func (*customLogger) Log(q *db.QueryStatus) { + switch q.Err { + case nil, db.ErrNoMoreRows: + return // Don't log successful queries. + } + // Alert of any other error. + log.Printf("Unexpected database error: %v\n%s", q.Err, q.String()) +} + type artistType struct { ID int64 `db:"id,omitempty"` Name string `db:"name"` @@ -83,6 +95,23 @@ func TestTruncateAllCollections(t *testing.T) { } } +func TestCustomQueryLogger(t *testing.T) { + sess, err := Open(settings) + assert.NoError(t, err) + defer sess.Close() + + db.Conf.SetLogger(&customLogger{}) + defer func() { + db.Conf.SetLogger(nil) + }() + + _, err = sess.Collection("artist").Find().Count() + assert.Equal(t, nil, err) + + _, err = sess.Collection("artist_x").Find().Count() + assert.NotEqual(t, nil, err) +} + func TestExpectCursorError(t *testing.T) { sess := mustOpen() defer sess.Close()