123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- package logging
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/kptyun/KPTCOMM/pkg/file"
- "io"
- "log"
- "os"
- "path/filepath"
- "runtime"
- "time"
- )
- type Level int
- var (
- F *os.File
- DefaultPrefix = ""
- DefaultCallerDepth = 2
- logger *log.Logger
- logPrefix = ""
- levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
- )
- const (
- DEBUG Level = iota
- INFO
- WARNING
- ERROR
- FATAL
- )
- func Setup() {
- var err error
- //tchan :=time.Tick(24*time.Hour)
- filePath := getLogFilePath()
- fileName := getLogFileName()
- F, err = file.MustOpen(fileName, filePath)
- if err != nil {
- log.Fatalf("logging.Setup err: %v", err)
- }
- logger = log.New(F, DefaultPrefix, log.LstdFlags)
- //gin.DefaultWriter = io.MultiWriter(F, os.Stdout)
- go func() {
- tchan := time.Tick(24 * time.Hour)
- for {
- select {
- case <-tchan:
- F.Close()
- fmt.Println("t1定时器")
- filePath := getLogFilePath()
- fileName := getLogFileName()
- F, err = file.MustOpen(fileName, filePath)
- if err != nil {
- log.Fatalf("logging.Setup err: %v", err)
- }
- logger = log.New(F, DefaultPrefix, log.LstdFlags)
- gin.DefaultWriter = io.MultiWriter(F, os.Stdout)
- }
- }
- }()
- //// gin log设置
- //gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
- //
- // // 你的自定义格式
- // return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"%s\n",
- // param.ClientIP,
- // param.TimeStamp.Format(time.RFC1123),
- // param.Method,
- // param.Path,
- // param.Request.Proto,
- // param.StatusCode,
- // param.Latency,
- // param.Request.UserAgent(),
- // param.ErrorMessage,
- // param.Request.Form,
- // )
- //})
- }
- func Debug(v ...interface{}) {
- setPrefix(DEBUG)
- logger.Println(v)
- }
- func Info(v ...interface{}) {
- setPrefix(INFO)
- logger.Println(v)
- }
- func Warn(v ...interface{}) {
- setPrefix(WARNING)
- logger.Println(v)
- }
- func Error(v ...interface{}) {
- setPrefix(ERROR)
- logger.Println(v)
- }
- func Fatal(v ...interface{}) {
- setPrefix(FATAL)
- logger.Fatalln(v)
- }
- func setPrefix(level Level) {
- _, file, line, ok := runtime.Caller(DefaultCallerDepth)
- if ok {
- logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
- } else {
- logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
- }
- logger.SetPrefix(logPrefix)
- }
|