-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogfile.go
168 lines (157 loc) · 4.63 KB
/
logfile.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package cmd_toolkit
import (
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/majohn-r/output"
"github.com/utahta/go-cronowriter"
)
const (
logDirName = "logs"
logFileExtension = ".log"
symlinkName = "latest" + logFileExtension
maxLogFiles = 10
)
var (
logWriter io.WriteCloser
tmpEnvironmentVariableNames = []string{"TMP", "TEMP"}
)
func initWriter(o output.Bus, applicationName string) (w io.Writer, path string) {
// pre-check!
if !isLegalApplicationName(applicationName) {
o.ErrorPrintf(
"Log initialization is not possible due to a coding error; the application name %q is not valid.\n",
applicationName,
)
return
}
// get the temporary folder values
tmpFolderMap := findTemp()
if len(tmpFolderMap) == 0 {
o.ErrorPrintln(
"Log initialization is not possible because neither the TMP nor TEMP environment variables are defined.")
o.ErrorPrintln("What to do:")
o.ErrorPrintln("Define at least one of TMP and TEMP, setting the value to a directory path, e.g., '/tmp'.")
o.ErrorPrintf(
"Either it should contain a subdirectory named %q, which in turn contains a subdirectory named %q.\n",
applicationName,
logDirName,
)
o.ErrorPrintln("Or, if they do not exist, it must be possible to create those subdirectories.")
return
}
path = findLogFilePath(o, tmpFolderMap, applicationName)
if path != "" {
cleanup(o, path, applicationName)
logWriter = cronowriter.MustNew(
filepath.Join(path, logFilePrefix(applicationName)+"%Y%m%d"+logFileExtension),
cronowriter.WithSymlink(filepath.Join(path, symlinkName)),
cronowriter.WithInit())
w = logWriter
}
return
}
func findLogFilePath(o output.Bus, tmpFolderMap map[string]string, applicationName string) string {
for _, variableName := range tmpEnvironmentVariableNames {
if tmpFolder, found := tmpFolderMap[variableName]; found {
if err := Mkdir(tmpFolder); err != nil {
o.ErrorPrintf(
"The %s environment variable value %q is not a directory, nor can it be created as a directory.\n",
variableName,
tmpFolder,
)
} else {
// this is safe because we know the application name has been validated
tmp, _ := createAppSpecificPath(tmpFolder, applicationName)
path := filepath.Join(tmp, logDirName)
_ = fileSystem.MkdirAll(path, StdDirPermissions)
if DirExists(path) {
return path
}
o.ErrorPrintf(
"The %s environment variable value %q cannot be used to create a directory for log files.\n",
variableName,
tmpFolder,
)
}
}
}
o.ErrorPrintln("What to do:")
o.ErrorPrintln("The values of TMP and TEMP should be a directory path, e.g., '/tmp'.")
o.ErrorPrintf(
"Either it should contain a subdirectory named %q, which in turn contains a subdirectory named %q.\n",
applicationName,
logDirName,
)
o.ErrorPrintln("Or, if they do not exist, it must be possible to create those subdirectories.")
return ""
}
func cleanup(o output.Bus, logPath, applicationName string) (found, deleted int) {
if files, dirRead := ReadDirectory(o, logPath); dirRead {
var fileMap = make(map[time.Time]fs.FileInfo)
times := make([]time.Time, 0, len(files))
for _, file := range files {
if isLogFile(file, applicationName) {
modificationTime := file.ModTime()
fileMap[modificationTime] = file
times = append(times, modificationTime)
}
}
found = len(times)
if found > maxLogFiles && len(times) > 0 {
sort.Slice(times, func(i, j int) bool {
return times[i].Before(times[j])
})
limit := len(times) - maxLogFiles
for k := 0; k < limit; k++ {
entry := fileMap[times[k]]
if entry != nil {
logFile := filepath.Join(logPath, entry.Name())
if deleteLogFile(o, logFile) {
deleted++
}
}
}
}
}
return
}
func deleteLogFile(o output.Bus, logFile string) bool {
if fileErr := fileSystem.Remove(logFile); fileErr != nil {
o.ErrorPrintf("The log file %q cannot be deleted: %s.\n", logFile, ErrorToString(fileErr))
return false
}
return true
}
func findTemp() map[string]string {
result := map[string]string{}
for _, variableName := range tmpEnvironmentVariableNames {
if tmpFolder, found := os.LookupEnv(variableName); found {
result[variableName] = tmpFolder
}
}
return result
}
func isLogFile(file fs.FileInfo, applicationName string) (ok bool) {
if file.Mode().IsRegular() {
fileName := file.Name()
ok = strings.HasPrefix(
fileName,
logFilePrefix(applicationName),
) && strings.HasSuffix(
fileName,
logFileExtension,
)
}
return
}
func logFilePrefix(applicationName string) string {
if isLegalApplicationName(applicationName) {
return applicationName + "."
}
return "_log_."
}