Debian Codegraph @

logger/log.go

raw
1 // Copyright 2012-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package logger provides logging facilities for the NATS server
15 package logger
16
17 import (
18 "fmt"
19 "log"
20 "os"
21 "path/filepath"
22 "strings"
23 "sync"
24 "sync/atomic"
25 "time"
26 )
27
28 // Default file permissions for log files.
29 const defaultLogPerms = os.FileMode(0640)
30
31 // Logger is the server logger
32 type Logger struct {
33 sync.Mutex
34 logger *log.Logger
35 debug bool
36 trace bool
37 infoLabel string
38 warnLabel string
39 errorLabel string
40 fatalLabel string
41 debugLabel string
42 traceLabel string
43 fl *fileLogger
44 }
45
46 type LogOption interface {
47 isLoggerOption()
48 }
49
50 // LogUTC controls whether timestamps in the log output should be UTC or local time.
51 type LogUTC bool
52
53 func (l LogUTC) isLoggerOption() {}
54
55 func logFlags(time bool, opts ...LogOption) int {
56 flags := 0
57 if time {
58 flags = log.LstdFlags | log.Lmicroseconds
59 }
60
61 for _, opt := range opts {
62 switch v := opt.(type) {
63 case LogUTC:
64 if time && bool(v) {
65 flags |= log.LUTC
66 }
67 }
68 }
69
70 return flags
71 }
72
73 // NewStdLogger creates a logger with output directed to Stderr
74 func NewStdLogger(time, debug, trace, colors, pid bool, opts ...LogOption) *Logger {
75 flags := logFlags(time, opts...)
76
77 pre := ""
78 if pid {
79 pre = pidPrefix()
80 }
81
82 l := &Logger{
83 logger: log.New(os.Stderr, pre, flags),
84 debug: debug,
85 trace: trace,
86 }
87
88 if colors {
89 setColoredLabelFormats(l)
90 } else {
91 setPlainLabelFormats(l)
92 }
93
94 return l
95 }
96
97 // NewFileLogger creates a logger with output directed to a file
98 func NewFileLogger(filename string, time, debug, trace, pid bool, opts ...LogOption) *Logger {
99 flags := logFlags(time, opts...)
100
101 pre := ""
102 if pid {
103 pre = pidPrefix()
104 }
105
106 fl, err := newFileLogger(filename, pre, time)
107 if err != nil {
108 log.Fatalf("error opening file: %v", err)
109 return nil
110 }
111
112 l := &Logger{
113 logger: log.New(fl, pre, flags),
114 debug: debug,
115 trace: trace,
116 fl: fl,
117 }
118 fl.Lock()
119 fl.l = l
120 fl.Unlock()
121
122 setPlainLabelFormats(l)
123 return l
124 }
125
126 type writerAndCloser interface {
127 Write(b []byte) (int, error)
128 Close() error
129 Name() string
130 }
131
132 type fileLogger struct {
133 out int64
134 canRotate int32
135 sync.Mutex
136 l *Logger
137 f writerAndCloser
138 limit int64
139 olimit int64
140 pid string
141 time bool
142 closed bool
143 maxNumFiles int
144 }
145
146 func newFileLogger(filename, pidPrefix string, time bool) (*fileLogger, error) {
147 fileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
148 f, err := os.OpenFile(filename, fileflags, defaultLogPerms)
149 if err != nil {
150 return nil, err
151 }
152 stats, err := f.Stat()
153 if err != nil {
154 f.Close()
155 return nil, err
156 }
157 fl := &fileLogger{
158 canRotate: 0,
159 f: f,
160 out: stats.Size(),
161 pid: pidPrefix,
162 time: time,
163 }
164 return fl, nil
165 }
166
167 func (l *fileLogger) setLimit(limit int64) {
168 l.Lock()
169 l.olimit, l.limit = limit, limit
170 atomic.StoreInt32(&l.canRotate, 1)
171 rotateNow := l.out > l.limit
172 l.Unlock()
173 if rotateNow {
174 l.l.Noticef("Rotating logfile...")
175 }
176 }
177
178 func (l *fileLogger) setMaxNumFiles(max int) {
179 l.Lock()
180 l.maxNumFiles = max
181 l.Unlock()
182 }
183
184 func (l *fileLogger) logDirect(label, format string, v ...any) int {
185 var entrya = [256]byte{}
186 var entry = entrya[:0]
187 if l.pid != "" {
188 entry = append(entry, l.pid...)
189 }
190 if l.time {
191 now := time.Now()
192 year, month, day := now.Date()
193 hour, min, sec := now.Clock()
194 microsec := now.Nanosecond() / 1000
195 entry = append(entry, fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d.%06d ",
196 year, month, day, hour, min, sec, microsec)...)
197 }
198 entry = append(entry, label...)
199 entry = append(entry, fmt.Sprintf(format, v...)...)
200 entry = append(entry, '\r', '\n')
201 l.f.Write(entry)
202 return len(entry)
203 }
204
205 func (l *fileLogger) logPurge(fname string) {
206 var backups []string
207 lDir := filepath.Dir(fname)
208 lBase := filepath.Base(fname)
209 entries, err := os.ReadDir(lDir)
210 if err != nil {
211 l.logDirect(l.l.errorLabel, "Unable to read directory %q for log purge (%v), will attempt next rotation", lDir, err)
212 return
213 }
214 for _, entry := range entries {
215 if entry.IsDir() || entry.Name() == lBase || !strings.HasPrefix(entry.Name(), lBase) {
216 continue
217 }
218 if stamp, found := strings.CutPrefix(entry.Name(), fmt.Sprintf("%s%s", lBase, ".")); found {
219 _, err := time.Parse("2006:01:02:15:04:05.999999999", strings.Replace(stamp, ".", ":", 5))
220 if err == nil {
221 backups = append(backups, entry.Name())
222 }
223 }
224 }
225 currBackups := len(backups)
226 maxBackups := l.maxNumFiles - 1
227 if currBackups > maxBackups {
228 // backups sorted oldest to latest based on timestamped lexical filename (ReadDir)
229 for i := 0; i < currBackups-maxBackups; i++ {
230 if err := os.Remove(filepath.Join(lDir, string(os.PathSeparator), backups[i])); err != nil {
231 l.logDirect(l.l.errorLabel, "Unable to remove backup log file %q (%v), will attempt next rotation", backups[i], err)
232 // Bail fast, we'll try again next rotation
233 return
234 }
235 l.logDirect(l.l.infoLabel, "Purged log file %q", backups[i])
236 }
237 }
238 }
239
240 func (l *fileLogger) Write(b []byte) (int, error) {
241 if atomic.LoadInt32(&l.canRotate) == 0 {
242 n, err := l.f.Write(b)
243 if err == nil {
244 atomic.AddInt64(&l.out, int64(n))
245 }
246 return n, err
247 }
248 l.Lock()
249 n, err := l.f.Write(b)
250 if err == nil {
251 l.out += int64(n)
252 if l.out > l.limit {
253 if err := l.f.Close(); err != nil {
254 l.limit *= 2
255 l.logDirect(l.l.errorLabel, "Unable to close logfile for rotation (%v), will attempt next rotation at size %v", err, l.limit)
256 l.Unlock()
257 return n, err
258 }
259 fname := l.f.Name()
260 now := time.Now()
261 bak := fmt.Sprintf("%s.%04d.%02d.%02d.%02d.%02d.%02d.%09d", fname,
262 now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(),
263 now.Second(), now.Nanosecond())
264 os.Rename(fname, bak)
265 fileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
266 f, err := os.OpenFile(fname, fileflags, defaultLogPerms)
267 if err != nil {
268 l.Unlock()
269 panic(fmt.Sprintf("Unable to re-open the logfile %q after rotation: %v", fname, err))
270 }
271 l.f = f
272 n := l.logDirect(l.l.infoLabel, "Rotated log, backup saved as %q", bak)
273 l.out = int64(n)
274 l.limit = l.olimit
275 if l.maxNumFiles > 0 {
276 l.logPurge(fname)
277 }
278 }
279 }
280 l.Unlock()
281 return n, err
282 }
283
284 func (l *fileLogger) close() error {
285 l.Lock()
286 if l.closed {
287 l.Unlock()
288 return nil
289 }
290 l.closed = true
291 l.Unlock()
292 return l.f.Close()
293 }
294
295 // SetSizeLimit sets the size of a logfile after which a backup
296 // is created with the file name + "year.month.day.hour.min.sec.nanosec"
297 // and the current log is truncated.
298 func (l *Logger) SetSizeLimit(limit int64) error {
299 l.Lock()
300 if l.fl == nil {
301 l.Unlock()
302 return fmt.Errorf("can set log size limit only for file logger")
303 }
304 fl := l.fl
305 l.Unlock()
306 fl.setLimit(limit)
307 return nil
308 }
309
310 // SetMaxNumFiles sets the number of archived log files that will be retained
311 func (l *Logger) SetMaxNumFiles(max int) error {
312 l.Lock()
313 if l.fl == nil {
314 l.Unlock()
315 return fmt.Errorf("can set log max number of files only for file logger")
316 }
317 fl := l.fl
318 l.Unlock()
319 fl.setMaxNumFiles(max)
320 return nil
321 }
322
323 // NewTestLogger creates a logger with output directed to Stderr with a prefix.
324 // Useful for tracing in tests when multiple servers are in the same pid
325 func NewTestLogger(prefix string, time bool) *Logger {
326 flags := 0
327 if time {
328 flags = log.LstdFlags | log.Lmicroseconds
329 }
330 l := &Logger{
331 logger: log.New(os.Stderr, prefix, flags),
332 debug: true,
333 trace: true,
334 }
335 setColoredLabelFormats(l)
336 return l
337 }
338
339 // Close implements the io.Closer interface to clean up
340 // resources in the server's logger implementation.
341 // Caller must ensure threadsafety.
342 func (l *Logger) Close() error {
343 if l.fl != nil {
344 return l.fl.close()
345 }
346 return nil
347 }
348
349 // Generate the pid prefix string
350 func pidPrefix() string {
351 return fmt.Sprintf("[%d] ", os.Getpid())
352 }
353
354 func setPlainLabelFormats(l *Logger) {
355 l.infoLabel = "[INF] "
356 l.debugLabel = "[DBG] "
357 l.warnLabel = "[WRN] "
358 l.errorLabel = "[ERR] "
359 l.fatalLabel = "[FTL] "
360 l.traceLabel = "[TRC] "
361 }
362
363 func setColoredLabelFormats(l *Logger) {
364 colorFormat := "[\x1b[%sm%s\x1b[0m] "
365 l.infoLabel = fmt.Sprintf(colorFormat, "32", "INF")
366 l.debugLabel = fmt.Sprintf(colorFormat, "36", "DBG")
367 l.warnLabel = fmt.Sprintf(colorFormat, "0;93", "WRN")
368 l.errorLabel = fmt.Sprintf(colorFormat, "31", "ERR")
369 l.fatalLabel = fmt.Sprintf(colorFormat, "31", "FTL")
370 l.traceLabel = fmt.Sprintf(colorFormat, "33", "TRC")
371 }
372
373 // Noticef logs a notice statement
374 func (l *Logger) Noticef(format string, v ...any) {
375 l.logger.Printf(l.infoLabel+format, v...)
376 }
377
378 // Warnf logs a notice statement
379 func (l *Logger) Warnf(format string, v ...any) {
380 l.logger.Printf(l.warnLabel+format, v...)
381 }
382
383 // Errorf logs an error statement
384 func (l *Logger) Errorf(format string, v ...any) {
385 l.logger.Printf(l.errorLabel+format, v...)
386 }
387
388 // Fatalf logs a fatal error
389 func (l *Logger) Fatalf(format string, v ...any) {
390 l.logger.Fatalf(l.fatalLabel+format, v...)
391 }
392
393 // Debugf logs a debug statement
394 func (l *Logger) Debugf(format string, v ...any) {
395 if l.debug {
396 l.logger.Printf(l.debugLabel+format, v...)
397 }
398 }
399
400 // Tracef logs a trace statement
401 func (l *Logger) Tracef(format string, v ...any) {
402 if l.trace {
403 l.logger.Printf(l.traceLabel+format, v...)
404 }
405 }