add logging level prefix with color or not config

This commit is contained in:
wanna 2021-06-28 00:58:35 +08:00
parent a2771c7558
commit 03928f1977
3 changed files with 5 additions and 4 deletions

View File

@ -43,7 +43,7 @@ const (
defaultFilePerm = os.FileMode(0666) defaultFilePerm = os.FileMode(0666)
defaultFileExpire = time.Minute defaultFileExpire = time.Minute
pathFilterKey = "/os/glog/glog" pathFilterKey = "/os/glog/glog"
bufferStdOut = "stdOut" mustWithColor = true
) )
const ( const (
@ -228,7 +228,7 @@ func (l *Logger) printToWriter(ctx context.Context, input *HandlerInput) {
} }
// Allow output to stdout? // Allow output to stdout?
if l.config.StdoutPrint { if l.config.StdoutPrint {
if _, err := os.Stdout.Write(input.Buffer(bufferStdOut).Bytes()); err != nil { if _, err := os.Stdout.Write(input.Buffer(mustWithColor).Bytes()); err != nil {
intlog.Error(err) intlog.Error(err)
} }
} }

View File

@ -42,6 +42,7 @@ type Config struct {
RotateBackupExpire time.Duration `json:"rotateBackupExpire"` // Max expire for rotated files, which is 0 in default, means no expiration. RotateBackupExpire time.Duration `json:"rotateBackupExpire"` // Max expire for rotated files, which is 0 in default, means no expiration.
RotateBackupCompress int `json:"rotateBackupCompress"` // Compress level for rotated files using gzip algorithm. It's 0 in default, means no compression. RotateBackupCompress int `json:"rotateBackupCompress"` // Compress level for rotated files using gzip algorithm. It's 0 in default, means no compression.
RotateCheckInterval time.Duration `json:"rotateCheckInterval"` // Asynchronizely checks the backups and expiration at intervals. It's 1 hour in default. RotateCheckInterval time.Duration `json:"rotateCheckInterval"` // Asynchronizely checks the backups and expiration at intervals. It's 1 hour in default.
FileColor bool `json:"fileColor"` // Logging level prefix with color or not (false in default).
color logColor `json:"-"` color logColor `json:"-"`
} }

View File

@ -43,11 +43,11 @@ func (i *HandlerInput) addStringToBuffer(buffer *bytes.Buffer, s string) {
buffer.WriteString(s) buffer.WriteString(s)
} }
func (i *HandlerInput) Buffer(bufferType ...string) *bytes.Buffer { func (i *HandlerInput) Buffer(withColor ...bool) *bytes.Buffer {
buffer := bytes.NewBuffer(nil) buffer := bytes.NewBuffer(nil)
buffer.WriteString(i.TimeFormat) buffer.WriteString(i.TimeFormat)
if i.LevelFormat != "" { if i.LevelFormat != "" {
if len(bufferType) > 0 && bufferType[0] == bufferStdOut { if i.logger.config.FileColor || (len(withColor) > 0 && withColor[0] == mustWithColor) {
i.addStringToBuffer(buffer, i.getLevelFormatWithColor()) i.addStringToBuffer(buffer, i.getLevelFormatWithColor())
} else { } else {
i.addStringToBuffer(buffer, i.LevelFormat) i.addStringToBuffer(buffer, i.LevelFormat)