From 2b84841385a47562799b2e9abb70159ddf5d5b9a Mon Sep 17 00:00:00 2001 From: Wittano Date: Sat, 4 Nov 2023 23:02:35 +0100 Subject: [PATCH] feat(log): added saving logs into file --- README.md | 13 +++++++------ cmd/komputer/main.go | 1 + internal/log/log.go | 24 ++++++++++++++++++++++-- 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index bbcef7d..fedf785 100644 --- a/README.md +++ b/README.md @@ -12,9 +12,10 @@ in `/opt/komputer` directory. Bot is configurable via a few environment variables: -- DISCORD_BOT_TOKEN= # Discord Bot Token (required) -- APPLICATION_ID= # Your bot application id (required) -- SERVER_GUID= # Your server ID, where bot will register commands (required) -- MONGODB_URI= # URI to connect MongoDB database (required) -- MONGODB_DB_NAME= # Name of main collection for komputer bot (required) -- RAPID_API_KEY= # API key for RapidAPIs. In project is use: HumorAP (optional) \ No newline at end of file +- DISCORD_BOT_TOKEN= Discord Bot Token (required) +- APPLICATION_ID= Your bot application id (required) +- SERVER_GUID= Your server ID, where bot will register commands (required) +- MONGODB_URI= URI to connect MongoDB database (required) +- MONGODB_DB_NAME= Name of main collection for komputer bot (required) +- RAPID_API_KEY= API key for RapidAPIs. In project is use: HumorAP (optional) +- LOG_FILE = Localization of your log file (optional). If you don't use this variable, logs will print on STDOUT \ No newline at end of file diff --git a/cmd/komputer/main.go b/cmd/komputer/main.go index 25b8c59..60de33d 100644 --- a/cmd/komputer/main.go +++ b/cmd/komputer/main.go @@ -93,6 +93,7 @@ func main() { defer bot.Close() defer schedule.Scheduler.Stop() defer mongo.CloseDb() + defer log.FileLog.Close() stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) diff --git a/internal/log/log.go b/internal/log/log.go index ae1514d..3f60caf 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -2,12 +2,32 @@ package log import ( "context" + "fmt" "github.com/rs/zerolog" + "io" "os" ) -// TODO Add saving logs into file -var logger = zerolog.New(os.Stdout).With().Ctx(context.Background()).Timestamp().Logger() +var ( + FileLog io.WriteCloser = os.Stdout +) + +var logger zerolog.Logger + +func init() { + logFilePath := os.Getenv("LOG_FILE") + if logFilePath != "" { + var err error + + FileLog, err = os.Open(logFilePath) + if err != nil { + Fatal(context.Background(), fmt.Sprintf("Failed to open file '%s'", logFilePath), err) + return + } + } + + logger = zerolog.New(FileLog).With().Ctx(context.Background()).Timestamp().Logger() +} func Info(ctx context.Context, msg string) { logger.Info().Ctx(ctx).Str("traceID", getTraceID(ctx)).Msg(msg)