beego_logger.go 2.7 KB
package log

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strconv"

	"github.com/beego/beego/v2/core/logs"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
)

type LoggerConfig struct {
	Level      int    `json:"level,omitempty"`
	Filename   string `json:"filename,omitempty"`
	MaxSize    int    `json:"maxsize,omitempty"`
	MaxBackups int    `json:"max_backups,omitempty"`
	MaxAge     int    `json:"max_age,omitempty"`
	Compress   bool   `json:"compress,omitempty"`
}

type BeegoLog struct {
	serviceName string
	beeLogger   *logs.BeeLogger
}

func (logger *BeegoLog) AddHook(write io.Writer) {

}

func (logger *BeegoLog) SetServiceName(serviceName string) {
	logger.serviceName = serviceName
}

func (logger *BeegoLog) SetLevel(level string) {
	ilv, err := strconv.Atoi(level)
	if err != nil {
		ilv = logs.LevelDebug
	}
	logger.beeLogger.SetLevel(ilv)
}

func (logger *BeegoLog) Trace(msg string, appends ...map[string]interface{}) {
	logs.Trace(msg, appends)
}

func (logger *BeegoLog) Debug(msg string, appends ...map[string]interface{}) {
	appendsJson, _ := json.Marshal(appends)
	if appendsJson == nil {
		logs.Debug(msg, make(map[string]interface{}, 0))
	} else {
		var out bytes.Buffer
		err := json.Indent(&out, appendsJson, "", "  ")
		if err != nil {
			fmt.Println(msg)
			return
		}
		logs.Debug(msg, out.String())
	}
}

func (logger *BeegoLog) Info(msg string, appends ...map[string]interface{}) {
	appendsJson, _ := json.Marshal(appends)
	if appendsJson == nil {
		logs.Info(msg, make(map[string]interface{}, 0))
	} else {
		var out bytes.Buffer
		err := json.Indent(&out, appendsJson, "", "  ")
		if err != nil {
			fmt.Println(msg)
			return
		}
		logs.Info(msg, out.String())
	}
}

func (logger *BeegoLog) Warn(msg string, appends ...map[string]interface{}) {
	logs.Warn(msg, appends)
}

func (logger *BeegoLog) Error(msg string, appends ...map[string]interface{}) {
	logs.Error(msg, appends)
}

func (logger *BeegoLog) Fatal(msg string, appends ...map[string]interface{}) {
	logs.Error(msg, appends)
}

func (logger *BeegoLog) Panic(msg string, appends ...map[string]interface{}) {
	logs.Error(msg, appends)
}

func NewBeegoLog(conf LoggerConfig) *BeegoLog {
	logger := logs.GetBeeLogger()
	logger.SetLevel(conf.Level)
	if os.Getenv("LOG_FILE") == "true" {
		confByte, _ := json.Marshal(conf)
		err := logger.SetLogger(logs.AdapterFile, string(confByte))
		if err != nil {
			fmt.Println(err.Error())
			return nil
		}
	} else {
		err := logger.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`)
		if err != nil {
			fmt.Println(err.Error())
			return nil
		}
	}
	logger.SetPrefix(constant.SERVICE_NAME)
	logger.EnableFuncCallDepth(true)
	logger.SetLogFuncCallDepth(5)
	return &BeegoLog{
		beeLogger: logger,
	}
}