github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/nlog/api.go (about) 1 // Package nlog - aistore logger, provides buffering, timestamping, writing, and 2 // flushing/syncing/rotating 3 /* 4 * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. 5 */ 6 package nlog 7 8 import ( 9 "fmt" 10 "time" 11 12 "github.com/NVIDIA/aistore/cmn/mono" 13 ) 14 15 const ( 16 ActNone = iota 17 ActExit 18 ActRotate 19 ) 20 21 var LogToStderr bool 22 var MaxSize int64 = 4 * 1024 * 1024 // usually, config.log.max_size 23 24 func InfoDepth(depth int, args ...any) { log(sevInfo, depth, "", args...) } 25 func Infoln(args ...any) { log(sevInfo, 0, "", args...) } 26 func Infof(format string, args ...any) { log(sevInfo, 0, format, args...) } 27 func Warningln(args ...any) { log(sevWarn, 0, "", args...) } 28 func Warningf(format string, args ...any) { log(sevWarn, 0, format, args...) } 29 func ErrorDepth(depth int, args ...any) { log(sevErr, depth, "", args...) } 30 func Errorln(args ...any) { log(sevErr, 0, "", args...) } 31 func Errorf(format string, args ...any) { log(sevErr, 0, format, args...) } 32 33 func Setup(logToStderr bool, maxSize int64) { 34 LogToStderr = logToStderr 35 MaxSize = maxSize 36 if MaxSize > 1024*1024*1024 { 37 Warningf("log.max_size %d exceeds 1GB, setting log.max_size=4MB", MaxSize) 38 MaxSize = 4 * 1024 * 1024 39 } 40 } 41 42 func SetLogDirRole(dir, role string) { 43 if logDir != "" && logDir != dir && unitTests.Load() { 44 msg := fmt.Sprintf("log dir %q != %q (using nlog _prior_ to loading config?)", logDir, dir) 45 assert(false, msg) 46 } 47 logDir, aisrole = dir, role 48 } 49 50 func SetTitle(s string) { title = s } 51 52 func InfoLogName() string { return sname() + ".INFO" } 53 func ErrLogName() string { return sname() + ".ERROR" } 54 55 func Flush(action int) { 56 now := mono.NanoTime() 57 for _, sev := range []severity{sevInfo, sevErr} { 58 var ( 59 nlog = nlogs[sev] 60 oob bool 61 ) 62 63 nlog.mw.Lock() 64 if nlog.file == nil || (nlog.pw.length() == 0 && action != ActRotate) { 65 nlog.mw.Unlock() 66 continue 67 } 68 if action > ActNone || nlog.pw.avail() < maxLineSize || nlog.since(now) > 10*time.Second { 69 nlog.toFlush = append(nlog.toFlush, nlog.pw) 70 nlog.get() 71 } 72 oob = len(nlog.toFlush) > 0 73 nlog.mw.Unlock() 74 75 if oob { 76 nlog.flush() 77 } 78 if action == ActRotate { 79 nlog.rotate(time.Now()) 80 } 81 if action == ActExit { 82 nlog.file.Sync() 83 nlog.file.Close() 84 } 85 } 86 } 87 88 func Since() time.Duration { 89 now := mono.NanoTime() 90 a, b := nlogs[sevInfo].since(now), nlogs[sevErr].since(now) 91 if a > b { 92 return a 93 } 94 return b 95 } 96 97 func OOB() bool { 98 return nlogs[sevInfo].oob.Load() || nlogs[sevErr].oob.Load() 99 } 100 101 func Stopping() bool { return stopping.Load() } 102 func SetStopping() { stopping.Store(true) }