From 229299805093a4f2e5f21fa1caeee0e6ea84011d Mon Sep 17 00:00:00 2001 From: GUO YANKE Date: Thu, 22 Aug 2024 11:35:33 +0800 Subject: [PATCH] refactor: cleanup logic for MINIT_LOG_DIR parsing (#19) --- internal/mlog/logger.go | 22 ++++++++++++++++++++++ main.go | 39 +++------------------------------------ 2 files changed, 25 insertions(+), 36 deletions(-) diff --git a/internal/mlog/logger.go b/internal/mlog/logger.go index 988783d..2a15753 100644 --- a/internal/mlog/logger.go +++ b/internal/mlog/logger.go @@ -117,3 +117,25 @@ func (pl *procLogger) Out() Output { func (pl *procLogger) Err() Output { return pl.err } + +const ( + dirNone = "none" +) + +func CreateSimpleLogger(dir string, name string, pfx string) (ProcLogger, error) { + var fo *RotatingFileOptions + + if dir != "" && dir != dirNone { + if err := os.MkdirAll(dir, 0755); err == nil { + fo = &RotatingFileOptions{ + Dir: dir, + Filename: name, + } + } + } + + return NewProcLogger(ProcLoggerOptions{ + ConsolePrefix: pfx, + FileOptions: fo, + }) +} diff --git a/main.go b/main.go index a2acade..ec57ad1 100644 --- a/main.go +++ b/main.go @@ -27,19 +27,6 @@ var ( AppVersion = "unknown" ) -const ( - dirNone = "none" -) - -func mkdirUnlessNone(dir *string) { - if *dir == dirNone { - return - } - if err := os.MkdirAll(*dir, 0755); err != nil { - *dir = dirNone - } -} - func exit(err *error) { if *err != nil { _, _ = fmt.Fprintf(os.Stderr, "%s: exited with error: %s\n", "minit", (*err).Error()) @@ -69,7 +56,7 @@ func main() { var ( optPprofPort = "" optUnitDir = "/etc/minit.d" - optLogDir = dirNone + optLogDir = "" optQuickExit bool ) @@ -80,31 +67,11 @@ func main() { }() } - // unit dir, be careful, empty string should be treated as current directory envStr("MINIT_UNIT_DIR", &optUnitDir) - - // log dir envStr("MINIT_LOG_DIR", &optLogDir) - mkdirUnlessNone(&optLogDir) - - // quick exit envBool("MINIT_QUICK_EXIT", &optQuickExit) - createLogger := func(name string, pfx string) (mlog.ProcLogger, error) { - var rfo *mlog.RotatingFileOptions - if optLogDir != dirNone { - rfo = &mlog.RotatingFileOptions{ - Dir: optLogDir, - Filename: name, - } - } - return mlog.NewProcLogger(mlog.ProcLoggerOptions{ - ConsolePrefix: pfx, - FileOptions: rfo, - }) - } - - log := rg.Must(createLogger("minit", "minit: ")) + log := rg.Must(mlog.CreateSimpleLogger(optLogDir, "minit", "minit: ")) exem := mexec.NewManager() @@ -144,7 +111,7 @@ func main() { rg.Must(mrunners.Create(mrunners.RunnerOptions{ Unit: unit, Exec: exem, - Logger: rg.Must(createLogger(unit.Name, "")), + Logger: rg.Must(mlog.CreateSimpleLogger(optLogDir, unit.Name, "")), })), ) }