logger.go 2.2 KB
package log

import (
	"encoding/json"
	"fmt"

	"github.com/astaxie/beego/logs"
)

type SetLoggerConfig interface {
	MarshalString() string
	Name() string
}

//LoggerConsole 日志输出到命令行
type LoggerConsole struct {
	Level int  `json:"level,omitempty"`
	Color bool `json:"color,omitempty"`
}

//LoggerFile 日志输出到文件
type LoggerFile struct {
	FileName string `json:"filename,omitempty"`
	Maxlines int    `json:"maxlines,omitempty"`
	Maxsize  int    `json:"maxsize,omitempty"`
	Daily    bool   `json:"daily,omitempty"`
	MaxDays  int    `json:"maxdays,omitempty"`
	Rotate   bool   `json:"rotate,omitempty"`
	Level    int    `json:"level,omitempty"`
}

var (
	_ SetLoggerConfig = &LoggerConsole{}
	_ SetLoggerConfig = &LoggerFile{}
)

// log level
const (
	LogLevelError int = logs.LevelError
	LogLevelWarn  int = logs.LevelWarning
	LogLevelInfo  int = logs.LevelInformational
	LogLevelDebug int = logs.LevelDebug
)

func (config LoggerConsole) MarshalString() string {
	bytedata, err := json.Marshal(config)
	if err != nil {
		return ""
	}
	return string(bytedata)
}

func (config LoggerConsole) Name() string {
	return logs.AdapterConsole
}

func (config LoggerFile) MarshalString() string {
	bytedata, err := json.Marshal(config)
	if err != nil {
		return ""
	}
	return string(bytedata)
}
func (config LoggerFile) Name() string {
	return logs.AdapterFile
}

var logger *logs.BeeLogger

func ResetLog(config SetLoggerConfig, funcCall bool) {
	fmt.Println("初始化log")
	logger = logs.GetBeeLogger()
	out := config.Name()
	logconf := config.MarshalString()
	logger.EnableFuncCallDepth(funcCall)
	logger.SetLogFuncCallDepth(3)
	logger.SetLogger(out, logconf)
	return
}

//LogLevel ...
func LogLevel(s string) (i int) {
	switch s {
	case "info":
		i = LogLevelInfo
	case "debug":
		i = LogLevelDebug
	case "warning":
		i = LogLevelWarn
	case "error":
		i = LogLevelError
	default:
		i = LogLevelDebug
	}
	return
}

func Info(format string, v ...interface{}) {
	logger.Info(format, v...)
}

func Debug(format string, v ...interface{}) {
	logger.Debug(format, v...)
}

func Error(format string, v ...interface{}) {
	logger.Error(format, v...)
}

func Warn(format string, v ...interface{}) {
	logger.Warn(format, v...)
}