diff --git a/cmd/root.go b/cmd/root.go index a1c23bd..48d5cd4 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -116,6 +116,7 @@ func init() { rootCmd.Flags().BoolVar(&config.AllowUntrustedTLS, "allow-untrusted-tls", config.AllowUntrustedTLS, "Do not verify HTTPS certificates (link checker & screenshots)") rootCmd.Flags().StringVarP(&config.SMTPCLITags, "tag", "t", config.SMTPCLITags, "Tag new messages matching filters") + rootCmd.Flags().StringVar(&logger.LogFile, "log-file", logger.LogFile, "Log output to file instead of stdout") rootCmd.Flags().BoolVarP(&logger.QuietLogging, "quiet", "q", logger.QuietLogging, "Quiet logging (errors only)") rootCmd.Flags().BoolVarP(&logger.VerboseLogging, "verbose", "v", logger.VerboseLogging, "Verbose logging") @@ -223,6 +224,9 @@ func initConfigFromEnv() { if getEnabledFromEnv("MP_ALLOW_UNTRUSTED_TLS") { config.AllowUntrustedTLS = true } + if len(os.Getenv("MP_LOG_FILE")) > 0 { + logger.LogFile = os.Getenv("MP_LOG_FILE") + } if getEnabledFromEnv("MP_QUIET") { logger.QuietLogging = true } diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 95f23ff..ca21348 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -18,6 +18,8 @@ var ( QuietLogging bool // NoLogging shows only fatal errors NoLogging bool + // LogFile sets a log file + LogFile string ) // Log returns the logger instance @@ -36,11 +38,21 @@ func Log() *logrus.Logger { log.SetLevel(logrus.PanicLevel) } - log.Out = os.Stdout + if LogFile != "" { + file, err := os.OpenFile(LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0664) + if err == nil { + log.Out = file + } else { + log.Out = os.Stdout + log.Warn("Failed to log to file, using default stderr") + } + } else { + log.Out = os.Stdout + } + log.SetFormatter(&logrus.TextFormatter{ FullTimestamp: true, TimestampFormat: "2006/01/02 15:04:05", - ForceColors: true, }) }