package log

import (
	"github.com/go-kratos/kratos/v2/log"
	"os"
	"strings"
	"sync"
)

var businessLogger log.Logger
var businessLoggerOnce sync.Once

// NewBusinessLogger 获取业务日志logger
func NewBusinessLogger(path string, id, name, version string) log.Logger {
	businessLoggerOnce.Do(func() {
		filePath := ""
		if path != "" {
			filePath = strings.Trim(path, " ")
		}
		writeIO := os.Stdout
		if filePath != "" {
			f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
			if err != nil {
				panic("打开日志失败，注意读写权限：" + filePath)
			}
			writeIO = f
		}
		businessLogger = log.With(
			log.NewStdLogger(writeIO),
			"ts", log.DefaultTimestamp,
			"caller", log.DefaultCaller,
			"service.id", id,
			"service.name", name,
			"service.version", version,
		)
	})
	return businessLogger
}
