-
Notifications
You must be signed in to change notification settings - Fork 38
/
main.go
89 lines (74 loc) · 2.25 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"fmt"
"io" // This is used to enable the multiwritter and be able to write to the log file and the console at the same time
"log/slog"
"os"
"path" // This is used to create the path where the log files will be stored
"strings" // This is required to conpare the evironment variables
"time" // This is used to get the current date and create the log file
"github.com/joshmedeski/sesh/seshcli"
)
var version = "dev"
func main() {
slog.Debug("Debug")
slog.Info("Information")
slog.Warn("Warning")
slog.Error("Error")
app := seshcli.App(version)
if err := app.Run(os.Args); err != nil {
slog.Error("main file: ", "error", err)
os.Exit(1)
}
}
func init() {
var f *os.File
var err error
fileOnly := false
if f, err = createLoggerFile(); err != nil {
slog.Error("Unable to create logger file", "error", err)
os.Exit(1)
}
env := os.Getenv("ENV")
handlerOptions := &slog.HandlerOptions{}
switch strings.ToLower(env) {
case "debug":
handlerOptions.Level = slog.LevelDebug
case "info":
handlerOptions.Level = slog.LevelInfo
case "error":
handlerOptions.Level = slog.LevelError
default:
handlerOptions.Level = slog.LevelWarn
fileOnly = true
}
var loggerHandler *slog.JSONHandler
if !fileOnly {
multiWriter := io.MultiWriter(os.Stdout, f)
loggerHandler = slog.NewJSONHandler(multiWriter, handlerOptions)
} else {
loggerHandler = slog.NewJSONHandler(f, handlerOptions)
}
slog.SetDefault(slog.New(loggerHandler))
}
func createLoggerFile() (*os.File, error) {
now := time.Now()
date := fmt.Sprintf("%s.log", now.Format("2006-01-02"))
// TempDir returns the default directory to use for temporary files.
//
// On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
// On Windows, it uses GetTempPath, returning the first non-empty
// value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
// On Plan 9, it returns /tmp.
userTempDir := os.TempDir()
slog.Debug("createLoggerFile:", "userTempDir", userTempDir)
if err := os.MkdirAll(path.Join(userTempDir, "sesh"), 0755); err != nil {
return nil, err
}
fileFullPath := path.Join(userTempDir, "sesh", date)
file, err := os.OpenFile(fileFullPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
return file, nil
}