Skip to content

Commit

Permalink
Add basic logger
Browse files Browse the repository at this point in the history
  • Loading branch information
zMoooooritz committed Nov 18, 2023
1 parent 3933df0 commit 90662eb
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
7 changes: 7 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,24 @@ package cmd

import (
"fmt"
"log"
"os"

tea "github.com/charmbracelet/bubbletea"
"github.com/zMoooooritz/nachrichten/pkg/config"
"github.com/zMoooooritz/nachrichten/pkg/tui"
"github.com/zMoooooritz/nachrichten/pkg/util"
)

func Run() {

cfg := config.Init()
configuration := cfg.Load()
if cfg.LogFile != "" {
err := util.SetLogFile(cfg.LogFile)
log.Fatalln("Error occoured while setting up logger: ", err)
}
util.Logger.Println("Application started.")

p := tea.NewProgram(tui.InitialModel(configuration),
tea.WithAltScreen(),
Expand Down
11 changes: 7 additions & 4 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,24 +51,27 @@ const (
)

type Config struct {
file string
ConfigFile string
LogFile string
}

func Init() Config {

configFile := flag.String("config", "~/.config/nachrichten/config.yaml", "Path to configuration file")
configFile := flag.String("config", "", "Path to configuration file")
logFile := flag.String("debug", "", "Path to log file")

flag.Parse()
cfg := Config{
file: *configFile,
ConfigFile: *configFile,
LogFile: *logFile,
}
return cfg
}

func (c Config) Load() Configuration {
config := defaultConfiguration()

data, err := os.ReadFile(c.file)
data, err := os.ReadFile(c.ConfigFile)
if err != nil {
return config
}
Expand Down
32 changes: 32 additions & 0 deletions pkg/util/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package util

import (
"io"
"log"
"os"
"path/filepath"
)

var Logger *log.Logger

func init() {
Logger = log.New(io.Discard, "LOG: ", log.Ldate|log.Ltime|log.Lshortfile)
}

func SetLogFile(filePath string) error {
directory := filepath.Dir(filePath)
err := os.MkdirAll(directory, os.ModePerm)
if err != nil {
log.Fatalln("Error dir")
return err
}

file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalln("Error file")
return err
}

Logger.SetOutput(file)
return nil
}

0 comments on commit 90662eb

Please sign in to comment.