package log

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

// AccessLogger 访问日志对象
type AccessLogger log.Logger

var accessLogger AccessLogger
var accessLoggerOnce = sync.Once{}

func NewAccessLogger(path, id, name, version string) *AccessLogger {
	accessLoggerOnce.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
		}
		logger := log.With(log.NewStdLogger(writeIO),
			"ts", log.DefaultTimestamp,
			"caller", log.DefaultCaller,
			"id", id,
			"name", name,
			"version", version,
		)
		accessLogger = logger
	})
	return &accessLogger
}
