mirror of
https://github.com/netfun2000/rttys_zhaojh329.git
synced 2026-02-27 09:53:24 +08:00
+67
@@ -0,0 +1,67 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/dwdcth/consoleEx"
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
||||
type logFileHook struct {
|
||||
err error
|
||||
path string
|
||||
}
|
||||
|
||||
var logFile = &logFileHook{}
|
||||
|
||||
func (h *logFileHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
|
||||
if h.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
h.err = err
|
||||
log.Fatal().Msg(err.Error())
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
f.WriteString(zerolog.TimestampFunc().Format(zerolog.TimeFieldFormat) + " |")
|
||||
f.WriteString(strings.ToUpper(level.String()) + "| ")
|
||||
|
||||
_, file, line, ok := runtime.Caller(3)
|
||||
if ok {
|
||||
f.WriteString(zerolog.CallerMarshalFunc(file, line) + " |")
|
||||
}
|
||||
|
||||
f.WriteString(msg)
|
||||
f.WriteString("\n")
|
||||
}
|
||||
|
||||
func init() {
|
||||
zerolog.CallerMarshalFunc = func(file string, line int) string {
|
||||
return filepath.Base(file) + ":" + strconv.Itoa(line)
|
||||
}
|
||||
|
||||
out := consoleEx.ConsoleWriterEx{Out: colorable.NewColorableStdout()}
|
||||
logger := zerolog.New(out).With().Caller().Timestamp().Logger()
|
||||
|
||||
if !terminal.IsTerminal(int(os.Stdout.Fd())) {
|
||||
logger = logger.Hook(logFile)
|
||||
}
|
||||
|
||||
log.Logger = logger
|
||||
}
|
||||
|
||||
// SetPath set the log file path
|
||||
func SetPath(path string) {
|
||||
logFile.path = path
|
||||
}
|
||||
Reference in New Issue
Block a user