Files
2026-05-27 08:18:36 +08:00

69 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package forward
import (
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
var (
logMu sync.Mutex
appLogW io.Writer
)
// initAppLog 创建日志目录并打开当日日志文件 app-YYYY-MM-DD.log同时输出到控制台。
func initAppLog() error {
root := resolveLogRoot("forward")
if err := os.MkdirAll(root, 0o755); err != nil {
return err
}
day := time.Now().Format("2006-01-02")
f, err := os.OpenFile(filepath.Join(root, "app-"+day+".log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
appLogW = io.MultiWriter(os.Stdout, f)
return nil
}
// resolveLogRoot 解析日志根目录:优先 LOG_DIR/forward否则 {程序目录}/../log/forward/。
func resolveLogRoot(service string) string {
if v := strings.TrimSpace(os.Getenv("LOG_DIR")); v != "" {
return filepath.Join(v, service)
}
base := programDir()
return filepath.Join(base, "..", "log", service)
}
// programDir 返回程序所在目录go run 临时目录时回退为当前工作目录。
func programDir() string {
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
if strings.Contains(dir, "go-build") {
if wd, err := os.Getwd(); err == nil && wd != "" {
return wd
}
}
return dir
}
if wd, err := os.Getwd(); err == nil && wd != "" {
return wd
}
return "."
}
// appLogf 线程安全地写入应用日志(带 [forward] 前缀)。
func appLogf(format string, args ...any) {
logMu.Lock()
w := appLogW
logMu.Unlock()
if w == nil {
w = os.Stdout
}
log.New(w, "[forward] ", log.LstdFlags).Printf(format, args...)
}