1
0
mirror of https://github.com/goreleaser/goreleaser.git synced 2025-01-08 03:31:59 +02:00
goreleaser/internal/logext/writer.go
Carlos Alexandro Becker bf19dc1079
feat: moving some cmd logs to debug (#2359)
* feat: moving some cmd logs to debug

Signed-off-by: Carlos Alexandro Becker <caarlos0@gmail.com>

* feat: moving some cmd logs to debug

Signed-off-by: Carlos Alexandro Becker <caarlos0@gmail.com>
2021-07-23 12:09:29 +01:00

73 lines
1.2 KiB
Go

package logext
import (
"bytes"
"io"
"strings"
"github.com/apex/log"
"github.com/apex/log/handlers/cli"
)
// Output type of the log output.
type Output int
const (
// Info usually is used with stdout.
Info Output = iota
// Error usually is used with stderr.
Error
)
// NewWriter creates a new log writer.
func NewWriter(fields log.Fields, out Output) io.Writer {
if isDebug() {
return logWriter{
ctx: newLogger(fields),
out: out,
}
}
return io.Discard
}
type logWriter struct {
ctx *log.Entry
out Output
}
func (w logWriter) Write(p []byte) (int, error) {
for _, line := range strings.Split(toString(p), "\n") {
switch w.out {
case Info:
w.ctx.Info(line)
case Error:
w.ctx.Error(line)
}
}
return len(p), nil
}
func newLogger(fields log.Fields) *log.Entry {
handler := cli.New(cli.Default.Writer)
handler.Padding = cli.Default.Padding + 3
logger := log.WithFields(fields)
logger.Logger.Handler = handler
return logger
}
func isDebug() bool {
return logLevel() == log.DebugLevel
}
func logLevel() log.Level {
if logger, ok := log.Log.(*log.Logger); ok {
return logger.Level
}
return log.InfoLevel
}
func toString(b []byte) string {
return string(bytes.TrimSuffix(b, []byte("\n")))
}