Skip to content

Commit

Permalink
log_test: add ztest internal pakcage
Browse files Browse the repository at this point in the history
- added to provide methods to define a discarder in logger config
  • Loading branch information
Reza Kamalifard committed Jul 23, 2020
1 parent 1e475e5 commit 1575cbb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 33 deletions.
34 changes: 34 additions & 0 deletions internal/ztest/discarder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ztest

import "io/ioutil"

// A Syncer is a spy for the Sync portion of zapcore.WriteSyncer.
type Syncer struct {
err error
called bool
}

// SetError sets the error that the Sync method will return.
func (s *Syncer) SetError(err error) {
s.err = err
}

// Sync records that it was called, then returns the user-supplied error (if
// any).
func (s *Syncer) Sync() error {
s.called = true
return s.err
}

// Called reports whether the Sync method was called.
func (s *Syncer) Called() bool {
return s.called
}

// A Discarder sends all writes to ioutil.Discard.
type Discarder struct{ Syncer }

// Write implements io.Writer.
func (d *Discarder) Write(b []byte) (int, error) {
return ioutil.Discard.Write(b)
}
35 changes: 2 additions & 33 deletions log_test.go
Original file line number Diff line number Diff line change
@@ -1,52 +1,21 @@
package main

import (
"io/ioutil"
"github.com/rezakamalifard/TestLoggingWithZap/internal/ztest"
"testing"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

// A Syncer is a spy for the Sync portion of zapcore.WriteSyncer.
type Syncer struct {
err error
called bool
}

// SetError sets the error that the Sync method will return.
func (s *Syncer) SetError(err error) {
s.err = err
}

// Sync records that it was called, then returns the user-supplied error (if
// any).
func (s *Syncer) Sync() error {
s.called = true
return s.err
}

// Called reports whether the Sync method was called.
func (s *Syncer) Called() bool {
return s.called
}

// A Discarder sends all writes to ioutil.Discard.
type Discarder struct{ Syncer }

// Write implements io.Writer.
func (d *Discarder) Write(b []byte) (int, error) {
return ioutil.Discard.Write(b)
}

func newZapLogger(lvl zapcore.Level) *zap.Logger {
ec := zap.NewProductionEncoderConfig()
ec.EncodeDuration = zapcore.NanosDurationEncoder
ec.EncodeTime = zapcore.EpochNanosTimeEncoder
enc := zapcore.NewJSONEncoder(ec)
return zap.New(zapcore.NewCore(
enc,
&Discarder{},
&ztest.Discarder{},
lvl,
))
}
Expand Down

0 comments on commit 1575cbb

Please sign in to comment.