forked from gitea/gitea
1
0
Fork 0
gitea/modules/log/console.go

81 lines
1.8 KiB
Go
Raw Normal View History

2014-07-26 12:24:27 +08:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"log"
"os"
"runtime"
)
2016-11-26 19:53:29 +08:00
// Brush brush type
2014-07-26 12:24:27 +08:00
type Brush func(string) string
2016-11-26 19:53:29 +08:00
// NewBrush create a brush according color
2014-07-26 12:24:27 +08:00
func NewBrush(color string) Brush {
pre := "\033["
reset := "\033[0m"
return func(text string) string {
return pre + color + "m" + text + reset
}
}
var colors = []Brush{
NewBrush("1;36"), // Trace cyan
NewBrush("1;34"), // Debug blue
NewBrush("1;32"), // Info green
NewBrush("1;33"), // Warn yellow
NewBrush("1;31"), // Error red
NewBrush("1;35"), // Critical purple
NewBrush("1;31"), // Fatal red
}
// ConsoleWriter implements LoggerInterface and writes messages to terminal.
type ConsoleWriter struct {
lg *log.Logger
Level int `json:"level"`
}
2016-11-26 19:53:29 +08:00
// NewConsole create ConsoleWriter returning as LoggerInterface.
2014-07-26 12:24:27 +08:00
func NewConsole() LoggerInterface {
return &ConsoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
Level: TRACE,
}
}
2016-11-26 19:53:29 +08:00
// Init inits connection writer with json config.
// json config only need key "level".
2014-07-26 12:24:27 +08:00
func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw)
}
2016-11-26 19:53:29 +08:00
// WriteMsg writes message in console.
// if OS is windows, ignore colors.
2014-07-26 12:24:27 +08:00
func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
}
if runtime.GOOS == "windows" {
cw.lg.Println(msg)
} else {
cw.lg.Println(colors[level](msg))
}
return nil
}
2016-11-26 19:53:29 +08:00
// Flush when log should be flushed
func (cw *ConsoleWriter) Flush() {
2014-07-26 12:24:27 +08:00
}
2016-11-26 19:53:29 +08:00
// Destroy when writer is destroy
func (cw *ConsoleWriter) Destroy() {
}
2014-07-26 12:24:27 +08:00
func init() {
Register("console", NewConsole)
}