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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
package loggocolor
import (
"fmt"
"io"
"path/filepath"
"github.com/juju/ansiterm"
"github.com/juju/loggo/v2"
)
var (
// SeverityColor defines the colors for the levels output by the ColorWriter.
SeverityColor = map[loggo.Level]*ansiterm.Context{
loggo.TRACE: ansiterm.Foreground(ansiterm.Default),
loggo.DEBUG: ansiterm.Foreground(ansiterm.Green),
loggo.INFO: ansiterm.Foreground(ansiterm.BrightBlue),
loggo.WARNING: ansiterm.Foreground(ansiterm.Yellow),
loggo.ERROR: ansiterm.Foreground(ansiterm.BrightRed),
loggo.CRITICAL: {
Foreground: ansiterm.White,
Background: ansiterm.Red,
},
}
// LocationColor defines the colors for the location output by the ColorWriter.
LocationColor = ansiterm.Foreground(ansiterm.BrightBlue)
)
type colorWriter struct {
writer *ansiterm.Writer
}
// NewColorWriter will write out colored severity levels if the writer is
// outputting to a terminal.
func NewWriter(writer io.Writer) loggo.Writer {
return &colorWriter{ansiterm.NewWriter(writer)}
}
// NewcolorWriter will write out colored severity levels whether or not the
// writer is outputting to a terminal.
func NewColorWriter(writer io.Writer) loggo.Writer {
w := ansiterm.NewWriter(writer)
w.SetColorCapable(true)
return &colorWriter{w}
}
// Write implements Writer.
func (w *colorWriter) Write(entry loggo.Entry) {
ts := entry.Timestamp.Format(loggo.TimeFormat)
// Just get the basename from the filename
filename := filepath.Base(entry.Filename)
fmt.Fprintf(w.writer, "%s ", ts)
SeverityColor[entry.Level].Fprintf(w.writer, entry.Level.Short())
fmt.Fprintf(w.writer, " %s ", entry.Module)
LocationColor.Fprintf(w.writer, "%s:%d ", filename, entry.Line)
fmt.Fprintln(w.writer, entry.Message)
}
|