-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #42 from linkdata/logerror
Logerror
- Loading branch information
Showing
3 changed files
with
80 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package jaws | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
"strings" | ||
) | ||
|
||
type printlner interface { | ||
Println(v ...any) | ||
} | ||
|
||
type errorer interface { | ||
Error(msg string, args ...any) | ||
} | ||
|
||
// LogError is an adapter allowing logging an informational message | ||
// to a log.Logger, slog.Logger or io.Writer. | ||
func LogError(logger any, format string, args ...any) { | ||
msg := fmt.Sprintf(strings.TrimRight(format, "\n"), args...) | ||
switch x := logger.(type) { | ||
case printlner: | ||
x.Println(msg) | ||
case errorer: | ||
x.Error(msg) | ||
case io.Writer: | ||
_, _ = fmt.Fprintln(x, msg) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package jaws | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"testing" | ||
) | ||
|
||
type printlnerImpl struct { | ||
str string | ||
} | ||
|
||
func (x *printlnerImpl) Println(args ...any) { | ||
x.str += fmt.Sprint(args...) | ||
} | ||
|
||
type errorerImpl struct { | ||
str string | ||
} | ||
|
||
func (x *errorerImpl) Error(msg string, args ...any) { | ||
x.str += msg | ||
} | ||
|
||
func TestLogError(t *testing.T) { | ||
a := printlnerImpl{} | ||
LogError(&a, "a") | ||
LogError(&a, "\na\n") | ||
if a.str != "a\na" { | ||
t.Errorf("%q", a.str) | ||
} | ||
|
||
b := errorerImpl{} | ||
LogError(&b, "b") | ||
LogError(&b, "\nb\n") | ||
if b.str != "b\nb" { | ||
t.Errorf("%q", b.str) | ||
} | ||
|
||
var c bytes.Buffer | ||
LogError(&c, "c") | ||
LogError(&c, "\nc\n") | ||
if c.String() != "c\n\nc\n" { | ||
t.Errorf("%q", c.String()) | ||
} | ||
} |