Skip to content

Commit c0cb834

Browse files
committed
refactor: change xlog constructor to functional options
1 parent 73c7d9a commit c0cb834

17 files changed

+219
-97
lines changed

cmd/texd/main.go

+7-12
Original file line numberDiff line numberDiff line change
@@ -272,19 +272,14 @@ func printVersion() {
272272
}
273273

274274
func setupLogger() (xlog.Logger, error) {
275-
lvl, err := xlog.ParseLevel(logLevel)
276-
if err != nil {
277-
return nil, err
278-
}
279-
280-
o := &slog.HandlerOptions{
281-
AddSource: true,
282-
// XXX: provide ReplaceAttr callback to normalize Source locations?
283-
Level: lvl,
275+
o := []xlog.Option{
276+
xlog.LeveledString(logLevel),
277+
xlog.WithSource(),
284278
}
285-
286279
if texd.Development() {
287-
return xlog.New(xlog.TypeText, os.Stderr, o)
280+
o = append(o, xlog.WriteTo(os.Stderr), xlog.AsText())
281+
} else {
282+
o = append(o, xlog.WriteTo(os.Stdout), xlog.AsJSON())
288283
}
289-
return xlog.New(xlog.TypeJSON, os.Stdout, o)
284+
return xlog.New(o...)
290285
}

exec/docker_client.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func NewDockerClient(log xlog.Logger, baseDir string) (h *DockerClient, err erro
4848
}
4949

5050
if log == nil {
51-
log = xlog.NewNop()
51+
log = xlog.NewDiscard()
5252
}
5353
dc := &DockerClient{
5454
log: log,

exec/docker_client_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ func (s *dockerClientSuite) SetupTest() {
115115
s.cli = &apiMock{}
116116
s.subject = &DockerClient{
117117
cli: s.cli,
118-
log: xlog.NewNop(),
118+
log: xlog.NewDiscard(),
119119
}
120120
}
121121

exec/docker_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func (m *dockerClientMock) Run(ctx context.Context, tag, wd string, cmd []string
2424

2525
func TestDockerClient_Executor(t *testing.T) {
2626
subject := (&DockerClient{
27-
log: xlog.NewNop(),
27+
log: xlog.NewDiscard(),
2828
cli: &apiMock{},
2929
}).Executor(&mockDocument{})
3030
require.NotNil(t, subject)
@@ -37,7 +37,7 @@ func TestDockerExec_invalidDocument(t *testing.T) {
3737
cli: nil, // not accessed
3838
}
3939

40-
err := exec.Run(bg, xlog.NewNop())
40+
err := exec.Run(bg, xlog.NewDiscard())
4141
require.EqualError(t, err, "invalid document: "+io.ErrClosedPipe.Error())
4242
}
4343

@@ -55,7 +55,7 @@ func TestDockerExec_latexmkFailed(t *testing.T) {
5555
cli: cli,
5656
}
5757

58-
err := exec.Run(bg, xlog.NewNop())
58+
err := exec.Run(bg, xlog.NewDiscard())
5959
require.EqualError(t, err, "compilation failed: "+errStart.Error())
6060
assert.True(t, tex.IsCompilationError(err))
6161

@@ -78,6 +78,6 @@ func TestDockerExec_success(t *testing.T) {
7878
cli: cli,
7979
}
8080

81-
err := exec.Run(bg, xlog.NewNop())
81+
err := exec.Run(bg, xlog.NewDiscard())
8282
require.NoError(t, err)
8383
}

exec/local_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ func TestLocalExec_Run(t *testing.T) {
5858
// create local exec
5959
exec := LocalExec(tt.doc).(*localExec)
6060
exec.path = tt.path
61-
err := exec.Run(context.Background(), xlog.NewNop())
61+
err := exec.Run(context.Background(), xlog.NewDiscard())
6262

6363
if tt.expectedErr == "" {
6464
assert.NoError(t, err)

exec/mock_test.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func TestMock_Run_extractError(t *testing.T) {
2525
doc := &mockDocument{"/", io.ErrClosedPipe, "a", nil}
2626
subject := Mock(true, "content")(doc)
2727

28-
err := subject.Run(bg, xlog.NewNop())
28+
err := subject.Run(bg, xlog.NewDiscard())
2929
require.EqualError(t, err, "invalid document: "+io.ErrClosedPipe.Error())
3030
}
3131

@@ -34,15 +34,15 @@ func TestMock_Run_invalidMainfilePanics(t *testing.T) {
3434
subject := Mock(true, "content")(doc)
3535

3636
require.PanicsWithValue(t, "malformed input file: missing extension",
37-
func() { _ = subject.Run(bg, xlog.NewNop()) })
37+
func() { _ = subject.Run(bg, xlog.NewDiscard()) })
3838
}
3939

4040
func TestMock_Run_noAddFilePanics(t *testing.T) {
4141
doc := &mockDocument{"/", nil, "a.tex", nil} // doesn't implement AddFile
4242
subject := Mock(true, "content")(doc)
4343

4444
require.PanicsWithValue(t, "can't add files to document",
45-
func() { _ = subject.Run(bg, xlog.NewNop()) })
45+
func() { _ = subject.Run(bg, xlog.NewDiscard()) })
4646
}
4747

4848
type mockDockumentWithAddFile struct {
@@ -64,7 +64,7 @@ func TestMock_Run_errorOnAddFilePanics(t *testing.T) {
6464
doc.On("AddFile", "a.log", "content").Return(io.ErrClosedPipe)
6565

6666
require.PanicsWithError(t, "failed to store result file: "+io.ErrClosedPipe.Error(),
67-
func() { _ = subject.Run(bg, xlog.NewNop()) })
67+
func() { _ = subject.Run(bg, xlog.NewDiscard()) })
6868
}
6969

7070
func TestMock_Run_shouldFailCapturesLog(t *testing.T) {
@@ -75,7 +75,7 @@ func TestMock_Run_shouldFailCapturesLog(t *testing.T) {
7575

7676
doc.On("AddFile", "a.log", "content").Return(nil)
7777

78-
err := subject.Run(bg, xlog.NewNop())
78+
err := subject.Run(bg, xlog.NewDiscard())
7979
require.EqualError(t, err, "compilation failed")
8080
}
8181

@@ -87,6 +87,6 @@ func TestMock_Run_shouldFailCapturesResult(t *testing.T) {
8787

8888
doc.On("AddFile", "a.pdf", "%PDF/1.5").Return(nil)
8989

90-
err := subject.Run(bg, xlog.NewNop())
90+
err := subject.Run(bg, xlog.NewDiscard())
9191
require.NoError(t, err)
9292
}

refstore/dir/dir_store_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func TestNew_dirNotWritable(t *testing.T) {
8484

8585
func TestDirAdapter_keepFiles(t *testing.T) {
8686
require := require.New(t)
87-
log := xlog.NewNop()
87+
log := xlog.NewDiscard()
8888

8989
subject, err := NewMemory(nil, &refstore.KeepForever{})
9090
require.NoError(err)
@@ -121,7 +121,7 @@ func TestDirAdapter_purgeFiles(t *testing.T) {
121121

122122
func TestDirAdapter_accessMap(t *testing.T) {
123123
require := require.New(t)
124-
log := xlog.NewNop()
124+
log := xlog.NewDiscard()
125125
f := dummyFile("01234567890")
126126

127127
for _, q := range []struct{ n, sz int }{

service/middleware/logging_test.go

+17-11
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@ package middleware
22

33
import (
44
"bytes"
5-
"log/slog"
65
"net/http"
76
"net/http/httptest"
7+
"strings"
88
"testing"
9+
"time"
910

1011
"github.com/digineo/texd/xlog"
1112
"github.com/stretchr/testify/assert"
@@ -23,20 +24,25 @@ func TestLogging(t *testing.T) {
2324
h = RequestID(h)
2425

2526
var buf bytes.Buffer
26-
log, err := xlog.New(xlog.TypeText, &buf, &slog.HandlerOptions{
27-
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
28-
if a.Key == slog.TimeKey {
29-
return slog.Attr{}
30-
}
31-
return a
32-
},
33-
})
27+
log, err := xlog.New(
28+
xlog.AsText(),
29+
xlog.WriteTo(&buf),
30+
xlog.MockClock(time.Unix(1650000000, 0)),
31+
)
3432
require.NoError(t, err)
3533

3634
w := httptest.NewRecorder()
3735
WithLogging(log)(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/", nil))
3836
require.Equal(t, http.StatusOK, w.Code)
3937

40-
msg := `level=INFO msg="" method=GET status=200 bytes=0 host=192.0.2.1 url=/` + "\n"
41-
assert.Equal(t, msg, buf.String())
38+
assert.Equal(t, strings.Join([]string{
39+
"time=2022-04-15T07:20:00.000+02:00",
40+
"level=INFO",
41+
`msg=""`,
42+
"method=GET",
43+
"status=200",
44+
"bytes=0",
45+
"host=192.0.2.1",
46+
"url=/",
47+
}, " ")+"\n", buf.String())
4248
}

service/service.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ func Start(opts Options, log xlog.Logger) (func(context.Context) error, error) {
140140
return newService(opts, log).start(opts.Addr)
141141
}
142142

143-
var discardlog = xlog.NewNop()
143+
var discardlog = xlog.NewDiscard()
144144

145145
func (svc *service) Logger() xlog.Logger {
146146
if svc.log == nil {

service/service_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func TestSuite(t *testing.T) {
4848
func (suite *testSuite) SetupSuite() {
4949
require := suite.Require()
5050

51-
logger, err := xlog.New(xlog.TypeText, os.Stderr, nil)
51+
logger, err := xlog.New(xlog.AsText(), xlog.WriteTo(os.Stderr))
5252
suite.Require().NoError(err)
5353
suite.logger = logger
5454

@@ -260,7 +260,7 @@ func (suite *testSuite) TestService_refstore_useKnownRef() {
260260
if err != nil {
261261
panic(err)
262262
}
263-
if err = refs.Store(xlog.NewNop(), contents); err != nil {
263+
if err = refs.Store(xlog.NewDiscard(), contents); err != nil {
264264
panic(err)
265265
}
266266
contents.Close()

service/status_test.go

+13-13
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ import (
44
"bytes"
55
"encoding/json"
66
"io"
7-
"log/slog"
87
"net/http"
98
"net/http/httptest"
9+
"strings"
1010
"testing"
1111
"time"
1212

@@ -29,7 +29,7 @@ func TestHandleStatus(t *testing.T) {
2929
mode: "local",
3030
compileTimeout: 3 * time.Second,
3131
jobs: make(chan struct{}, 2),
32-
log: xlog.NewNop(),
32+
log: xlog.NewDiscard(),
3333
}
3434

3535
req := httptest.NewRequest(http.MethodGet, "/status", nil)
@@ -60,14 +60,11 @@ func TestHandleStatus(t *testing.T) {
6060

6161
func TestHandleStatus_withFailIO(t *testing.T) {
6262
var buf bytes.Buffer
63-
log, err := xlog.New(xlog.TypeText, &buf, &slog.HandlerOptions{
64-
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
65-
if a.Key == slog.TimeKey {
66-
return slog.Attr{}
67-
}
68-
return a
69-
},
70-
})
63+
log, err := xlog.New(
64+
xlog.AsText(),
65+
xlog.WriteTo(&buf),
66+
xlog.MockClock(time.Unix(1650000000, 0)),
67+
)
7168
require.NoError(t, err)
7269

7370
svc := &service{
@@ -87,7 +84,10 @@ func TestHandleStatus_withFailIO(t *testing.T) {
8784

8885
assert.Equal(t, http.StatusOK, rec.code)
8986
assert.Equal(t, mimeTypeJSON, rec.h.Get("Content-Type"))
90-
91-
msg := `level=ERROR msg="failed to write response" error="io: read/write on closed pipe"` + "\n"
92-
assert.Equal(t, msg, buf.String())
87+
assert.Equal(t, strings.Join([]string{
88+
"time=2022-04-15T07:20:00.000+02:00",
89+
"level=ERROR",
90+
`msg="failed to write response"`,
91+
`error="io: read/write on closed pipe"`,
92+
}, " ")+"\n", buf.String())
9393
}

tex/document_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func testFileWriter(t *testing.T, s string, candidate bool) {
5757
}
5858

5959
subject := fileWriter{
60-
log: xlog.NewNop(),
60+
log: xlog.NewDiscard(),
6161
file: f,
6262
wc: &nopCloser{Writer: &buf},
6363
buf: make([]byte, 4),
@@ -224,7 +224,7 @@ func TestDocument(t *testing.T) {
224224
subject := documentHelper{ //nolint:forcetypeassert
225225
t: t,
226226
fs: afero.Afero{Fs: afero.NewMemMapFs()},
227-
document: NewDocument(xlog.NewNop(), DefaultEngine, "").(*document),
227+
document: NewDocument(xlog.NewDiscard(), DefaultEngine, "").(*document),
228228
}
229229
subject.document.fs = subject.fs
230230

@@ -279,7 +279,7 @@ func TestDocument_MainInput(t *testing.T) {
279279
subject := documentHelper{ //nolint:forcetypeassert
280280
t: t,
281281
fs: afero.Afero{Fs: afero.NewMemMapFs()},
282-
document: NewDocument(xlog.NewNop(), DefaultEngine, "").(*document),
282+
document: NewDocument(xlog.NewDiscard(), DefaultEngine, "").(*document),
283283
}
284284
subject.document.fs = subject.fs
285285

@@ -335,7 +335,7 @@ func TestNewDocument(t *testing.T) {
335335
engine := NewEngine("foo")
336336
image := "bar"
337337

338-
subject := NewDocument(xlog.NewNop(), engine, image)
338+
subject := NewDocument(xlog.NewDiscard(), engine, image)
339339
require.NotNil(t, subject)
340340

341341
assert.Equal(t, engine, subject.Engine())

tex/metrics_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func TestFileCategory_String(t *testing.T) {
5252
func TestMetrics(t *testing.T) {
5353
assert, require := assert.New(t), require.New(t)
5454

55-
doc := NewDocument(xlog.NewNop(), DefaultEngine, "")
55+
doc := NewDocument(xlog.NewDiscard(), DefaultEngine, "")
5656
doc.(*document).fs = afero.NewMemMapFs()
5757
for name, size := range map[string]int{
5858
"input.tex": 10,

xlog/discard.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package xlog
2+
3+
import "os"
4+
5+
type discard struct{}
6+
7+
// NewDiscard produces basically the same logger as
8+
//
9+
// xlog.New(xlog.Discard(), otheroptions...)
10+
//
11+
// but without the option overhead.
12+
func NewDiscard() Logger {
13+
return &discard{}
14+
}
15+
16+
func (*discard) Debug(msg string, args ...any) {}
17+
func (*discard) Info(msg string, args ...any) {}
18+
func (*discard) Warn(msg string, args ...any) {}
19+
func (*discard) Error(msg string, args ...any) {}
20+
func (*discard) Fatal(msg string, args ...any) { os.Exit(1) }
21+
func (d *discard) With(args ...any) Logger { return d }

0 commit comments

Comments
 (0)