logger.go 843 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package logger
  2. import (
  3. "log/slog"
  4. "os"
  5. "path/filepath"
  6. "github.com/ayn2op/discordo/internal/config"
  7. "github.com/lmittmann/tint"
  8. )
  9. // Recursively creates the log directory if it does not exist already and returns the path to the log file.
  10. func initialize() (string, error) {
  11. path, err := os.UserCacheDir()
  12. if err != nil {
  13. return "", err
  14. }
  15. path = filepath.Join(path, config.Name)
  16. if err := os.MkdirAll(path, os.ModePerm); err != nil {
  17. return "", err
  18. }
  19. return filepath.Join(path, "logs.txt"), nil
  20. }
  21. // Opens the log file and configures standard logger.
  22. func Load() error {
  23. path, err := initialize()
  24. if err != nil {
  25. return err
  26. }
  27. file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, os.ModePerm)
  28. if err != nil {
  29. return err
  30. }
  31. h := tint.NewHandler(file, nil)
  32. l := slog.New(h)
  33. slog.SetDefault(l)
  34. return nil
  35. }