Skip to content

Commit

Permalink
feat: add log to file
Browse files Browse the repository at this point in the history
  • Loading branch information
chrispinkney committed Jul 29, 2024
1 parent 84d14df commit 4fe6a9c
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 4 deletions.
16 changes: 14 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package main

import (
"fmt"
"os"
"stump/internal/utils"

"stump/internal/db"
"stump/internal/logger"
Expand All @@ -12,9 +14,19 @@ import (
)

func main() {
err := godotenv.Load()
utils.ParseFlags()

var err error

err = godotenv.Load()
if err != nil {
logger.Error("There was a problem loading the .env file: %v", err)
os.Exit(1)
}

err = logger.Init()
if err != nil {
logger.Error("There was a problem loading the .env file")
fmt.Printf("failed to initialize logger: %v\n", err)
os.Exit(1)
}

Expand Down
31 changes: 29 additions & 2 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,41 @@
package logger

import (
"fmt"
"log"
"os"
"path/filepath"
"stump/internal/utils"
)

var l *log.Logger

func init() {
l = log.New(os.Stdout, "", log.Ldate|log.Ltime)
const logName = "stump.log"

func Init() error {
logToFile := utils.IsFlagSet("log")

var logOutput *os.File

if logToFile {
logPath, err := utils.GetAppPath()
logPath = filepath.Join(logPath, logName)

if err != nil {
return fmt.Errorf("failed to get application data path: %v", err)
}

logOutput, err = os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return fmt.Errorf("failed to open log file: %v", err)
}
} else {
logOutput = os.Stdout
}

l = log.New(logOutput, "", log.Ldate|log.Ltime)

return nil
}

func Info(msg string, args ...any) {
Expand Down
15 changes: 15 additions & 0 deletions internal/utils/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package utils

import (
"flag"
)

func ParseFlags() {
flag.Bool("log", false, "enable logging to a file")
}

func IsFlagSet(name string) bool {
flag.Parse()
flagValue := flag.Lookup(name)
return flagValue != nil
}
File renamed without changes.

0 comments on commit 4fe6a9c

Please sign in to comment.