Debian Codegraph @

logerrcapture/do.go

raw symbols SCIP
1 // Copyright (c) The EfficientGo Authors.
2 // Licensed under the Apache License 2.0.
3
4 // Initially copied from Thanos
5 //
6 // Copyright (c) The Thanos Authors.
7 // Licensed under the Apache License 2.0.
8
9 package logerrcapture
10
11 import (
12 "fmt"
13 "io"
14 "os"
15
16 "github.com/efficientgo/core/errors"
17 )
18
19 // Logger interface compatible with go-kit/logger.
20 type Logger interface {
21 Log(keyvals ...interface{}) error
22 }
23
24 type doFunc func() error
25
26 // Do is making sure we log every error, even those from best effort tiny functions.
27 func Do(logger Logger, doer doFunc, format string, a ...interface{}) {
28 derr := doer()
29 if derr == nil {
30 return
31 }
32
33 // For os closers, it's a common case to double close. From reliability purpose this is not a problem it may only indicate
34 // surprising execution path.
35 if errors.Is(derr, os.ErrClosed) {
36 return
37 }
38
39 _ = logger.Log("msg", "detected do error", "err", errors.Wrap(derr, fmt.Sprintf(format, a...)))
40 }
41
42 // ExhaustClose closes the io.ReadCloser with a log message on error but exhausts the reader before.
43 func ExhaustClose(logger Logger, r io.ReadCloser, format string, a ...interface{}) {
44 _, err := io.Copy(io.Discard, r)
45 if err != nil {
46 _ = logger.Log("msg", "failed to exhaust reader, performance may be impeded", "err", err)
47 }
48
49 Do(logger, r.Close, format, a...)
50 }