修改日志写入文件内

This commit is contained in:
bjdgyc
2021-02-22 14:35:29 +08:00
parent 665732fc03
commit 0baab68bb2
20 changed files with 166 additions and 70 deletions

View File

@@ -40,7 +40,8 @@ type ServerConfig struct {
CertFile string `toml:"cert_file" info:"证书文件"`
CertKey string `toml:"cert_key" info:"证书密钥"`
UiPath string `toml:"ui_path" info:"ui文件路径"`
DownFilesPath string `toml:"down_files_path" info:"外部下载文件路径"`
FilesPath string `toml:"files_path" info:"外部下载文件路径"`
LogPath string `toml:"log_path" info:"日志文件路径"`
LogLevel string `toml:"log_level" info:"日志等级"`
Issuer string `toml:"issuer" info:"系统名称"`
AdminUser string `toml:"admin_user" info:"管理用户名"`
@@ -83,7 +84,8 @@ func initServerCfg() {
Cfg.CertFile = getAbsPath(base, Cfg.CertFile)
Cfg.CertKey = getAbsPath(base, Cfg.CertKey)
Cfg.UiPath = getAbsPath(base, Cfg.UiPath)
Cfg.DownFilesPath = getAbsPath(base, Cfg.DownFilesPath)
Cfg.FilesPath = getAbsPath(base, Cfg.FilesPath)
Cfg.LogPath = getAbsPath(base, Cfg.LogPath)
if len(Cfg.JwtSecret) < 20 {
fmt.Println("请设置 jwt_secret 长度20位以上")
@@ -94,6 +96,10 @@ func initServerCfg() {
}
func getAbsPath(base, cfile string) string {
if cfile == "" {
return ""
}
abs := filepath.IsAbs(cfile)
if abs {
return cfile

View File

@@ -26,7 +26,7 @@ var (
)
func initFlag() {
flag.StringVar(&serverFile, "conf", "./conf/server.toml", "server config file path")
flag.StringVar(&serverFile, "conf", "./conf/server.toml", "server config files path")
flag.StringVar(&passwd, "passwd", "", "convert the password plaintext")
flag.BoolVar(&secret, "secret", false, "generate a random jwt secret")
flag.BoolVar(&rev, "rev", false, "display version info")

View File

@@ -4,7 +4,9 @@ import (
"fmt"
"log"
"os"
"path"
"strings"
"time"
)
const (
@@ -19,11 +21,65 @@ var (
baseLog *log.Logger
baseLevel int
levels map[int]string
dateFormat = "2006-01-02"
logName = "anylink.log"
)
// 实现 os.Writer 接口
type logWriter struct {
UseStdout bool
FileName string
File *os.File
NowDate string
}
// 实现日志文件的切割
func (lw *logWriter) Write(p []byte) (n int, err error) {
if !lw.UseStdout {
return lw.File.Write(p)
}
date := time.Now().Format(dateFormat)
if lw.NowDate != date {
_ = lw.File.Close()
_ = os.Rename(lw.FileName, lw.FileName+"."+lw.NowDate)
lw.NowDate = date
lw.newFile()
}
return lw.File.Write(p)
}
// 创建新文件
func (lw *logWriter) newFile() {
if lw.UseStdout {
lw.File = os.Stdout
return
}
f, err := os.OpenFile(lw.FileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
lw.File = f
}
func initLog() {
baseLog = log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile)
// 初始化 baseLog
baseLw := &logWriter{
UseStdout: Cfg.LogPath == "",
FileName: path.Join(Cfg.LogPath, logName),
NowDate: time.Now().Format(dateFormat),
}
baseLw.newFile()
baseLevel = logLevel2Int(Cfg.LogLevel)
baseLog = log.New(baseLw, "", log.LstdFlags|log.Lshortfile)
}
// 获取 log.Logger
func GetBaseLog() *log.Logger {
return baseLog
}
func logLevel2Int(l string) int {