Skip to content

Commit

Permalink
chore(console): support IsTerminal (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy authored Jan 23, 2022
1 parent 8448be2 commit 0b1bbbb
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.13

require (
github.com/gin-gonic/gin v1.7.2
github.com/mattn/go-isatty v0.0.12
github.com/rs/zerolog v1.23.0
github.com/stretchr/testify v1.7.0
)
12 changes: 11 additions & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,25 @@ package logger
import (
"io"
"net/http"
"os"
"regexp"
"time"

"github.com/gin-gonic/gin"
"github.com/mattn/go-isatty"
"github.com/rs/zerolog"
)

func defaultLogger(c *gin.Context, out io.Writer, latency time.Duration) zerolog.Logger {
logger := zerolog.New(out).With().
isTerm := isatty.IsTerminal(os.Stdout.Fd())
logger := zerolog.New(out).
Output(
zerolog.ConsoleWriter{
Out: out,
NoColor: !isTerm,
},
).
With().
Timestamp().
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Expand Down
4 changes: 2 additions & 2 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ func TestLogger(t *testing.T) {
assert.Contains(t, buffer.String(), "400")
assert.Contains(t, buffer.String(), "POST")
assert.Contains(t, buffer.String(), "/example")
assert.Contains(t, buffer.String(), "warn")
assert.Contains(t, buffer.String(), "WRN")

buffer.Reset()
performRequest(r, "PUT", "/example?a=100")
assert.Contains(t, buffer.String(), "502")
assert.Contains(t, buffer.String(), "PUT")
assert.Contains(t, buffer.String(), "/example")
assert.Contains(t, buffer.String(), "error")
assert.Contains(t, buffer.String(), "ERR")
}

func TestLoggerWithLogger(t *testing.T) {
Expand Down

0 comments on commit 0b1bbbb

Please sign in to comment.