Skip to content

Commit

Permalink
replace the discarding silent logger with noop logger
Browse files Browse the repository at this point in the history
  • Loading branch information
rusq committed Feb 3, 2023
1 parent 69d03ad commit dcac37e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
20 changes: 16 additions & 4 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package logger

import (
"io"
"log"
"os"

"github.com/rusq/dlog"
)

// Interface is the interface for a logger.
type Interface interface {
Debug(...any)
Debugf(fmt string, a ...any)
Expand All @@ -16,8 +16,20 @@ type Interface interface {
Println(...any)
}

// Default is the default logger. It logs to stderr and debug logging can be
// enabled by setting the DEBUG environment variable to 1. For example:
//
// DEBUG=1 slackdump
var Default = dlog.New(log.Default().Writer(), "", log.LstdFlags, os.Getenv("DEBUG") == "1")

// note: previously ioutil.Discard which is not deprecated in favord of io.Discard
// so this is valid only from go1.16
var Silent = dlog.New(io.Discard, "", log.LstdFlags, false)
// Silent is a logger that does not log anything.
var Silent = silent{}

// Silent is a logger that does not log anything.
type silent struct{}

func (s silent) Debug(...any) {}
func (s silent) Debugf(fmt string, a ...any) {}
func (s silent) Print(...any) {}
func (s silent) Printf(fmt string, a ...any) {}
func (s silent) Println(...any) {}
16 changes: 16 additions & 0 deletions logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package logger

import "testing"

func BenchmarkSlientPrintf(b *testing.B) {
var l = Silent
for i := 0; i < b.N; i++ {
l.Printf("hello world, %s, %d", "foo", i)
}
// This benchmark compares the performance of the Silent logger when
// using io.Discard, and when using a no-op function.
// io.Discard: BenchmarkSlientPrintf-16 93075956 12.92 ns/op 8 B/op 0 allocs/op
// no-op func: BenchmarkSlientPrintf-16 1000000000 0.2364 ns/op 0 B/op 0 allocs/op
//
// Oh, look! We have an WINNER. The no-op function wins, no surprises.
}

0 comments on commit dcac37e

Please sign in to comment.