Skip to content

Commit

Permalink
log: Add File method (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunshineplan authored May 26, 2024
1 parent 7ec5ece commit 0e3b218
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
7 changes: 6 additions & 1 deletion log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@ import (
"io"
"log"
"log/slog"
"os"
)

var std = newLogger(log.Default(), nil)
var std = newLogger(log.Default(), os.Stderr)

func Default() *Logger { return std }

func File() string {
return std.File()
}

func SetOutput(file string, extra io.Writer) {
std.SetOutput(file, extra)
}
Expand Down
7 changes: 7 additions & 0 deletions log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ func New(file, prefix string, flag int) *Logger {
return newLogger(log.New(f, prefix, flag), f)
}

func (l *Logger) File() string {
if l.file != nil {
return l.file.Name()
}
return ""
}

func (l *Logger) setOutput(file *os.File, extra io.Writer) {
var writers []io.Writer
if file != nil {
Expand Down
13 changes: 11 additions & 2 deletions log/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,18 @@ import (
func TestLogger(t *testing.T) {
logger := New("test1", "", 0)
defer os.Remove("test1")
if file := logger.File(); file != "test1" {
t.Errorf("expected test1; got %q", file)
}
logger.Print("test1")
if err := os.Rename("test1", "test2"); err != nil {
t.Fatal(err)
}
defer os.Remove("test2")
logger.Rotate()
if file := logger.File(); file != "test1" {
t.Errorf("expected test1; got %q", file)
}
logger.Print("test2")
b1, err := os.ReadFile("test1")
if err != nil {
Expand All @@ -27,16 +33,19 @@ func TestLogger(t *testing.T) {
t.Fatal(err)
}
if s := string(b1); s != "test2\n" {
t.Errorf("expected test2; got %s", s)
t.Errorf("expected test2; got %q", s)
}
if s := string(b2); s != "test1\n" {
t.Errorf("expected test1; got %s", s)
t.Errorf("expected test1; got %q", s)
}
}

func TestSLogger(t *testing.T) {
var buf bytes.Buffer
l := newLogger(log.New(&buf, "", 0), nil)
if file := l.File(); file != "" {
t.Errorf("expected empty string; got %q", file)
}
l.Info("test")
if s, expected := buf.String(), "INFO test\n"; s != expected {
t.Errorf("expected %q; got %q", expected, s)
Expand Down

0 comments on commit 0e3b218

Please sign in to comment.