Skip to content

Commit

Permalink
feat(logger): create own logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Wittano committed Nov 23, 2023
1 parent af96d65 commit 42484e2
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 24 deletions.
2 changes: 2 additions & 0 deletions cmd/filebot/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ var (

func init() {
rootCmd.PersistentFlags().StringVarP(&setting.Flags.ConfigPath, "setting", "c", setting.DefaultConfigPath(), "Specific path for filebot configuration")
rootCmd.PersistentFlags().StringVarP(&setting.Flags.LogFilePath, "log", "l", "", "Path to log file")
rootCmd.PersistentFlags().StringVarP(&setting.Flags.LogLevelName, "logLevel", "ll", "INFO", "Log level")
rootCmd.PersistentFlags().DurationVarP(&setting.Flags.UpdateInterval, "updateInterval", "u", setting.DefaultUpdateInterval(), "Set time after filebot should be refresh watched file state")
}
3 changes: 1 addition & 2 deletions cmd/filebot/filebot.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"github.com/wittano/filebot/cron"
"github.com/wittano/filebot/setting"
"github.com/wittano/filebot/watcher"
"log"
)

func runMainCommand(_ *cobra.Command, _ []string) {
Expand All @@ -26,6 +25,6 @@ func runMainCommand(_ *cobra.Command, _ []string) {

func main() {
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
setting.Logger().Fatal("Failed to start FileBot", err)
}
}
4 changes: 2 additions & 2 deletions cron/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package cron

import (
"github.com/go-co-op/gocron"
"log"
"github.com/wittano/filebot/setting"
"time"
)

Expand All @@ -11,7 +11,7 @@ func NewScheduler() *gocron.Scheduler {

_, err := s.Every(1).Hours().Do(moveToTrashTask)
if err != nil {
log.Fatal(err)
setting.Logger().Fatal("Failed to register 'moveToTrash' task", err)
}

return s
Expand Down
6 changes: 2 additions & 4 deletions cron/trash.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package cron

import (
"fmt"
"github.com/wittano/filebot/file"
"github.com/wittano/filebot/setting"
"golang.org/x/exp/slices"
"log"
"os"
"path/filepath"
"time"
Expand All @@ -27,7 +25,7 @@ func moveToTrashTask() {
func moveFileToTrash(dir setting.Directory) {
paths, err := dir.RealPaths()
if err != nil {
log.Printf("Failed to get file paths. %s", err)
setting.Logger().Error("Failed to get file paths", err)
return
}

Expand All @@ -45,7 +43,7 @@ func moveFileToTrash(dir setting.Directory) {
func isAfterDateOfRemovingFile(path string, after uint) bool {
stat, err := os.Stat(path)
if err != nil {
log.Println(fmt.Sprintf("Failed to load file info from %s: %s", path, err))
setting.Logger().Warn("Failed to load file info from "+path, err)
return false
}

Expand Down
8 changes: 4 additions & 4 deletions file/move.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package file

import (
"errors"
"log"
"github.com/wittano/filebot/setting"
"os"
"path/filepath"
)

func MoveToDestination(dest string, paths ...string) {
if _, err := os.Stat(dest); errors.Is(err, os.ErrNotExist) {
log.Printf("Destination directory %s doesn't exist", dest)
setting.Logger().Errorf("Destination directory %s doesn't exist", err, dest)
return
}

Expand All @@ -19,11 +19,11 @@ func MoveToDestination(dest string, paths ...string) {
if _, err := os.Stat(src); !errors.Is(err, os.ErrNotExist) {
err := os.Rename(src, newPath)
if err != nil {
log.Printf("Failed to move file from %s to %s. %s", src, newPath, err)
setting.Logger().Errorf("Failed to move file from %s to %s", err, src, newPath)
return
}

log.Printf("Moved file from %s to %s", src, dest)
setting.Logger().Info("Moved file from %s to %s", src, dest)
}
}
}
104 changes: 102 additions & 2 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,106 @@
package logger

// TODO Create logger settings
func init() {
import (
"fmt"
"log"
"os"
)

type LogLevel uint

const (
ALL LogLevel = 0
DEBUG LogLevel = 1
WARN LogLevel = 2
INFO LogLevel = 2
)

const errorPrefix = "[ERROR] "

type Logger interface {
Info(msg string, args ...any)
Warn(msg string, err error)
Warnf(msg string, err error, args ...any)
Error(msg string, err error)
Errorf(msg string, err error, args ...any)
Debug(msg string, err error)
Fatal(msg string, err error)
}

type fileStdWriter struct {
filePath string
}

func (f fileStdWriter) Write(p []byte) (n int, err error) {
if f.filePath != "" {
go writeToLogFile(f.filePath, p)
}

return os.Stdout.Write(p)
}

func writeToLogFile(path string, p []byte) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
log.Fatalf("Failed to open log file")
}
defer f.Close()

_, err = f.Write(p)
if err != nil {
log.Fatalf("Failed to log into file. %s", err)
}
}

type myLogger struct {
log *log.Logger
level LogLevel
}

func (m myLogger) Fatal(msg string, err error) {
m.log.Fatalf("[ERROR]: %s. %s", msg, err)
}

func (m myLogger) Info(msg string, args ...any) {
m.log.Println(fmt.Sprintf("[INFO] %s", fmt.Sprintf(msg, args...)))
}

func (m myLogger) Warn(msg string, err error) {
if m.level == WARN || m.level == ALL {
m.log.Println(appendError(fmt.Sprintf("[WARN] %s", msg), err))
}
}

func (m myLogger) Warnf(msg string, err error, args ...any) {
if m.level == WARN || m.level == ALL {
m.log.Println(appendError(fmt.Sprintf("[WARN] %s", fmt.Sprintf(msg, args...)), err))
}
}

func (m myLogger) Error(msg string, err error) {
m.log.Println(appendError(errorPrefix+msg, err))
}

func (m myLogger) Errorf(msg string, err error, args ...any) {
m.log.Println(appendError(fmt.Sprintf(errorPrefix+fmt.Sprintf(msg, args)), err))
}

func (m myLogger) Debug(msg string, err error) {
if m.level == DEBUG || m.level == ALL {
m.log.Println(appendError(errorPrefix+msg, err))
}
}

func appendError(msg string, err error) string {
if err != nil {
return msg + ", " + err.Error()
}

return msg
}

func NewLogger(filePath string, level LogLevel) Logger {
logger := log.New(fileStdWriter{filePath}, "[FileBot]", log.LstdFlags|log.Lmsgprefix)

return myLogger{logger, level}
}
6 changes: 3 additions & 3 deletions setting/config_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"github.com/wittano/filebot/path"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"log"
"os"
"path/filepath"
"regexp"
)

// TODO Add validation
type Config struct {
Dirs []Directory
}
Expand All @@ -33,7 +33,7 @@ func (d Directory) RealPaths() (paths []string, err error) {
}

if err != nil {
log.Printf("Failed get files from pattern '%s'\n", exp)
Logger().Errorf("Failed get files from pattern '%s'", err, exp)
return
}

Expand Down Expand Up @@ -63,7 +63,7 @@ func (d Directory) filterRealPaths(paths []string) (res []string) {
for _, exp := range d.Exceptions {
reg, err := regexp.Compile(exp)
if err != nil {
log.Printf("Failed to compile regex: '%s'", exp)
Logger().Warnf("Failed to compile regex: '%s'", nil, exp)
continue
}

Expand Down
25 changes: 23 additions & 2 deletions setting/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package setting

import (
"github.com/mitchellh/go-homedir"
"github.com/wittano/filebot/logger"
"log"
"path/filepath"
"time"
Expand All @@ -10,11 +11,15 @@ import (
type Flag struct {
ConfigPath string
UpdateInterval time.Duration
LogFilePath string
LogLevelName string
}

var Flags = Flag{
DefaultConfigPath(),
DefaultUpdateInterval(),
"",
"",
}

func (f Flag) Config() *Config {
Expand All @@ -24,13 +29,29 @@ func (f Flag) Config() *Config {

c, err := load(f.ConfigPath)
if err != nil {
// TODO Add debug logs
log.Fatalf("Failed to load config file: %s", f.ConfigPath)
Logger().Fatal("Failed to load config file", err)
}

return c
}

func (f Flag) LogLevel() logger.LogLevel {
var level logger.LogLevel

switch f.LogLevelName {
case "ALL":
level = logger.ALL
case "DEBUG":
level = logger.DEBUG
case "WARN":
level = logger.WARN
default:
level = logger.INFO
}

return level
}

func DefaultConfigPath() string {
homeDir, err := homedir.Dir()
if err != nil {
Expand Down
13 changes: 13 additions & 0 deletions setting/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package setting

import "github.com/wittano/filebot/logger"

var myLogger logger.Logger

func Logger() logger.Logger {
if myLogger == nil {
myLogger = logger.NewLogger(Flags.LogFilePath, Flags.LogLevel())
}

return myLogger
}
9 changes: 4 additions & 5 deletions watcher/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/wittano/filebot/cron"
"github.com/wittano/filebot/file"
"github.com/wittano/filebot/setting"
"log"
"os"
"sync"
"time"
Expand All @@ -23,7 +22,7 @@ type MyWatcher struct {
func NewWatcher() MyWatcher {
w, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Failed initialized file system w: %s", err)
setting.Logger().Fatal("Failed initialized system file watcher", err)
}

blocker := make(chan bool)
Expand Down Expand Up @@ -55,7 +54,7 @@ func (w MyWatcher) ObserveFiles() {
return
}

log.Printf("Error %s", err)
setting.Logger().Error("Watcher got unexpected error", err)
}
}
}
Expand All @@ -70,7 +69,7 @@ func (w *MyWatcher) AddFilesToObservable(config setting.Config) {
for _, dir := range config.Dirs {
paths, err := dir.RealPaths()
if err != nil {
log.Printf("Failed to get path for files")
setting.Logger().Error("Failed to get path for files", err)
continue
}

Expand Down Expand Up @@ -99,7 +98,7 @@ func (w *MyWatcher) fillFileObservedMap(src []string, dest string) {
func (w *MyWatcher) addFilesToObservable(paths ...string) {
for _, p := range paths {
if err := w.Add(p); err != nil {
log.Printf("Cannot add %s file/directory to tracing list: %s", p, err)
setting.Logger().Errorf("Cannot add %s file/directory to tracing list", err, p)
}
}
}
Expand Down

0 comments on commit 42484e2

Please sign in to comment.