From fed5069ed2eca82a5c3d9a7d086815b0de108645 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 9 Feb 2022 17:46:10 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=84=E8=8C=83=E6=97=A5=E5=BF=97=E8=BE=93?= =?UTF-8?q?=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 ++ config/config.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 042ca184..b79509c8 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,5 @@ tests/data/*/* debug.log yao-test dev.sh +logs +logs/application.log diff --git a/config/config.go b/config/config.go index 90e5616a..5857b9e8 100644 --- a/config/config.go +++ b/config/config.go @@ -5,16 +5,19 @@ import ( "os" "path/filepath" - "github.com/yaoapp/kun/log" - "github.com/caarlos0/env/v6" + "github.com/gin-gonic/gin" "github.com/joho/godotenv" "github.com/yaoapp/kun/exception" + "github.com/yaoapp/kun/log" ) // Conf 配置参数 var Conf Config +// LogOutput 日志输出 +var LogOutput *os.File // 日志文件 + func init() { filename, _ := filepath.Abs(filepath.Join(".", ".env")) if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) { @@ -22,6 +25,11 @@ func init() { return } Conf = LoadFrom(filename) + if Conf.Mode == "production" { + Production() + } else if Conf.Mode == "development" { + Development() + } } // LoadFrom 从配置项中加载 @@ -49,6 +57,74 @@ func Load() Config { return cfg } +// Production 设定为生产环境 +func Production() { + Conf.Mode = "production" + log.SetLevel(log.ErrorLevel) + log.SetFormatter(log.TEXT) + if Conf.LogMode == "JSON" { + log.SetFormatter(log.JSON) + } + gin.SetMode(gin.ReleaseMode) + ReloadLog() +} + +// Development 设定为开发环境 +func Development() { + Conf.Mode = "development" + log.SetLevel(log.TraceLevel) + log.SetFormatter(log.TEXT) + if Conf.LogMode == "JSON" { + log.SetFormatter(log.JSON) + } + gin.SetMode(gin.DebugMode) + ReloadLog() +} + +// ReloadLog 重新打开日志 +func ReloadLog() { + CloseLog() + OpenLog() +} + +// OpenLog 打开日志 +func OpenLog() { + if Conf.Log != "" { + logfile, err := filepath.Abs(Conf.Log) + if err != nil { + log.With(log.F{"file": logfile}).Error(err.Error()) + return + } + + logpath := filepath.Dir(logfile) + if _, err := os.Stat(logpath); os.IsNotExist(err) { + if err := os.MkdirAll(logpath, os.ModePerm); err != nil { + log.With(log.F{"file": logfile}).Error(err.Error()) + return + } + } + LogOutput, err = os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) + if err != nil { + log.With(log.F{"file": logfile}).Error(err.Error()) + return + } + + log.SetOutput(LogOutput) + gin.DefaultWriter = LogOutput + } +} + +// CloseLog 关闭日志 +func CloseLog() { + if LogOutput != nil { + err := LogOutput.Close() + if err != nil { + log.Error(err.Error()) + return + } + } +} + // // Config 系统配置 // type Config struct { // XiangConfig