-
Notifications
You must be signed in to change notification settings - Fork 617
/
logging.go
38 lines (29 loc) · 906 Bytes
/
logging.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package mid
import (
"context"
"fmt"
"time"
"github.com/ardanlabs/service/app/api/errs"
"github.com/ardanlabs/service/foundation/logger"
)
// Logger writes information about the request to the logs.
func Logger(ctx context.Context, log *logger.Logger, path string, rawQuery string, method string, remoteAddr string, next Handler) (Encoder, error) {
now := time.Now()
if rawQuery != "" {
path = fmt.Sprintf("%s?%s", path, rawQuery)
}
log.Info(ctx, "request started", "method", method, "path", path, "remoteaddr", remoteAddr)
resp, err := next(ctx)
var statusCode = errs.OK
if err != nil {
switch v := err.(type) {
case *errs.Error:
statusCode = v.Code
default:
statusCode = errs.Internal
}
}
log.Info(ctx, "request completed", "method", method, "path", path, "remoteaddr", remoteAddr,
"statuscode", statusCode, "since", time.Since(now).String())
return resp, err
}