logs.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package logx
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "os"
  7. "path"
  8. "runtime/debug"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/zeromicro/go-zero/core/sysx"
  13. )
  14. const callerDepth = 4
  15. var (
  16. timeFormat = "2006-01-02T15:04:05.000Z07:00"
  17. logLevel uint32
  18. encoding uint32 = jsonEncodingType
  19. // maxContentLength is used to truncate the log content, 0 for not truncating.
  20. maxContentLength uint32
  21. // use uint32 for atomic operations
  22. disableLog uint32
  23. disableStat uint32
  24. options logOptions
  25. writer = new(atomicWriter)
  26. setupOnce sync.Once
  27. )
  28. type (
  29. // LogField is a key-value pair that will be added to the log entry.
  30. LogField struct {
  31. Key string
  32. Value any
  33. }
  34. // LogOption defines the method to customize the logging.
  35. LogOption func(options *logOptions)
  36. logEntry map[string]any
  37. logOptions struct {
  38. gzipEnabled bool
  39. logStackCooldownMills int
  40. keepDays int
  41. maxBackups int
  42. maxSize int
  43. rotationRule string
  44. }
  45. )
  46. // Alert alerts v in alert level, and the message is written to error log.
  47. func Alert(v string) {
  48. getWriter().Alert(v)
  49. }
  50. // Close closes the logging.
  51. func Close() error {
  52. if w := writer.Swap(nil); w != nil {
  53. return w.(io.Closer).Close()
  54. }
  55. return nil
  56. }
  57. // Debug writes v into access log.
  58. func Debug(v ...any) {
  59. writeDebug(fmt.Sprint(v...))
  60. }
  61. // Debugf writes v with format into access log.
  62. func Debugf(format string, v ...any) {
  63. writeDebug(fmt.Sprintf(format, v...))
  64. }
  65. // Debugv writes v into access log with json content.
  66. func Debugv(v any) {
  67. writeDebug(v)
  68. }
  69. // Debugw writes msg along with fields into access log.
  70. func Debugw(msg string, fields ...LogField) {
  71. writeDebug(msg, fields...)
  72. }
  73. // Disable disables the logging.
  74. func Disable() {
  75. atomic.StoreUint32(&disableLog, 1)
  76. writer.Store(nopWriter{})
  77. }
  78. // DisableStat disables the stat logs.
  79. func DisableStat() {
  80. atomic.StoreUint32(&disableStat, 1)
  81. }
  82. // Error writes v into error log.
  83. func Error(v ...any) {
  84. writeError(fmt.Sprint(v...))
  85. }
  86. // Errorf writes v with format into error log.
  87. func Errorf(format string, v ...any) {
  88. writeError(fmt.Errorf(format, v...).Error())
  89. }
  90. // ErrorStack writes v along with call stack into error log.
  91. func ErrorStack(v ...any) {
  92. // there is newline in stack string
  93. writeStack(fmt.Sprint(v...))
  94. }
  95. // ErrorStackf writes v along with call stack in format into error log.
  96. func ErrorStackf(format string, v ...any) {
  97. // there is newline in stack string
  98. writeStack(fmt.Sprintf(format, v...))
  99. }
  100. // Errorv writes v into error log with json content.
  101. // No call stack attached, because not elegant to pack the messages.
  102. func Errorv(v any) {
  103. writeError(v)
  104. }
  105. // Errorw writes msg along with fields into error log.
  106. func Errorw(msg string, fields ...LogField) {
  107. writeError(msg, fields...)
  108. }
  109. // Field returns a LogField for the given key and value.
  110. func Field(key string, value any) LogField {
  111. switch val := value.(type) {
  112. case error:
  113. return LogField{Key: key, Value: val.Error()}
  114. case []error:
  115. var errs []string
  116. for _, err := range val {
  117. errs = append(errs, err.Error())
  118. }
  119. return LogField{Key: key, Value: errs}
  120. case time.Duration:
  121. return LogField{Key: key, Value: fmt.Sprint(val)}
  122. case []time.Duration:
  123. var durs []string
  124. for _, dur := range val {
  125. durs = append(durs, fmt.Sprint(dur))
  126. }
  127. return LogField{Key: key, Value: durs}
  128. case []time.Time:
  129. var times []string
  130. for _, t := range val {
  131. times = append(times, fmt.Sprint(t))
  132. }
  133. return LogField{Key: key, Value: times}
  134. case fmt.Stringer:
  135. return LogField{Key: key, Value: val.String()}
  136. case []fmt.Stringer:
  137. var strs []string
  138. for _, str := range val {
  139. strs = append(strs, str.String())
  140. }
  141. return LogField{Key: key, Value: strs}
  142. default:
  143. return LogField{Key: key, Value: val}
  144. }
  145. }
  146. // Info writes v into access log.
  147. func Info(v ...any) {
  148. writeInfo(fmt.Sprint(v...))
  149. }
  150. // Infof writes v with format into access log.
  151. func Infof(format string, v ...any) {
  152. writeInfo(fmt.Sprintf(format, v...))
  153. }
  154. // Infov writes v into access log with json content.
  155. func Infov(v any) {
  156. writeInfo(v)
  157. }
  158. // Infow writes msg along with fields into access log.
  159. func Infow(msg string, fields ...LogField) {
  160. writeInfo(msg, fields...)
  161. }
  162. // Must checks if err is nil, otherwise logs the error and exits.
  163. func Must(err error) {
  164. if err == nil {
  165. return
  166. }
  167. msg := err.Error()
  168. log.Print(msg)
  169. getWriter().Severe(msg)
  170. os.Exit(1)
  171. }
  172. // MustSetup sets up logging with given config c. It exits on error.
  173. func MustSetup(c LogConf) {
  174. Must(SetUp(c))
  175. }
  176. // Reset clears the writer and resets the log level.
  177. func Reset() Writer {
  178. return writer.Swap(nil)
  179. }
  180. // SetLevel sets the logging level. It can be used to suppress some logs.
  181. func SetLevel(level uint32) {
  182. atomic.StoreUint32(&logLevel, level)
  183. }
  184. // SetWriter sets the logging writer. It can be used to customize the logging.
  185. func SetWriter(w Writer) {
  186. if atomic.LoadUint32(&disableLog) == 0 {
  187. writer.Store(w)
  188. }
  189. }
  190. // SetUp sets up the logx. If already set up, just return nil.
  191. // we allow SetUp to be called multiple times, because for example
  192. // we need to allow different service frameworks to initialize logx respectively.
  193. func SetUp(c LogConf) (err error) {
  194. // Just ignore the subsequent SetUp calls.
  195. // Because multiple services in one process might call SetUp respectively.
  196. // Need to wait for the first caller to complete the execution.
  197. setupOnce.Do(func() {
  198. setupLogLevel(c)
  199. if !c.Stat {
  200. DisableStat()
  201. }
  202. if len(c.TimeFormat) > 0 {
  203. timeFormat = c.TimeFormat
  204. }
  205. atomic.StoreUint32(&maxContentLength, c.MaxContentLength)
  206. switch c.Encoding {
  207. case plainEncoding:
  208. atomic.StoreUint32(&encoding, plainEncodingType)
  209. default:
  210. atomic.StoreUint32(&encoding, jsonEncodingType)
  211. }
  212. switch c.Mode {
  213. case fileMode:
  214. err = setupWithFiles(c)
  215. case volumeMode:
  216. err = setupWithVolume(c)
  217. default:
  218. setupWithConsole()
  219. }
  220. })
  221. return
  222. }
  223. // Severe writes v into severe log.
  224. func Severe(v ...any) {
  225. writeSevere(fmt.Sprint(v...))
  226. }
  227. // Severef writes v with format into severe log.
  228. func Severef(format string, v ...any) {
  229. writeSevere(fmt.Sprintf(format, v...))
  230. }
  231. // Slow writes v into slow log.
  232. func Slow(v ...any) {
  233. writeSlow(fmt.Sprint(v...))
  234. }
  235. // Slowf writes v with format into slow log.
  236. func Slowf(format string, v ...any) {
  237. writeSlow(fmt.Sprintf(format, v...))
  238. }
  239. // Slowv writes v into slow log with json content.
  240. func Slowv(v any) {
  241. writeSlow(v)
  242. }
  243. // Sloww writes msg along with fields into slow log.
  244. func Sloww(msg string, fields ...LogField) {
  245. writeSlow(msg, fields...)
  246. }
  247. // Stat writes v into stat log.
  248. func Stat(v ...any) {
  249. writeStat(fmt.Sprint(v...))
  250. }
  251. // Statf writes v with format into stat log.
  252. func Statf(format string, v ...any) {
  253. writeStat(fmt.Sprintf(format, v...))
  254. }
  255. // WithCooldownMillis customizes logging on writing call stack interval.
  256. func WithCooldownMillis(millis int) LogOption {
  257. return func(opts *logOptions) {
  258. opts.logStackCooldownMills = millis
  259. }
  260. }
  261. // WithKeepDays customizes logging to keep logs with days.
  262. func WithKeepDays(days int) LogOption {
  263. return func(opts *logOptions) {
  264. opts.keepDays = days
  265. }
  266. }
  267. // WithGzip customizes logging to automatically gzip the log files.
  268. func WithGzip() LogOption {
  269. return func(opts *logOptions) {
  270. opts.gzipEnabled = true
  271. }
  272. }
  273. // WithMaxBackups customizes how many log files backups will be kept.
  274. func WithMaxBackups(count int) LogOption {
  275. return func(opts *logOptions) {
  276. opts.maxBackups = count
  277. }
  278. }
  279. // WithMaxSize customizes how much space the writing log file can take up.
  280. func WithMaxSize(size int) LogOption {
  281. return func(opts *logOptions) {
  282. opts.maxSize = size
  283. }
  284. }
  285. // WithRotation customizes which log rotation rule to use.
  286. func WithRotation(r string) LogOption {
  287. return func(opts *logOptions) {
  288. opts.rotationRule = r
  289. }
  290. }
  291. func addCaller(fields ...LogField) []LogField {
  292. return append(fields, Field(callerKey, getCaller(callerDepth)))
  293. }
  294. func createOutput(path string) (io.WriteCloser, error) {
  295. if len(path) == 0 {
  296. return nil, ErrLogPathNotSet
  297. }
  298. switch options.rotationRule {
  299. case sizeRotationRule:
  300. return NewLogger(path, NewSizeLimitRotateRule(path, backupFileDelimiter, options.keepDays,
  301. options.maxSize, options.maxBackups, options.gzipEnabled), options.gzipEnabled)
  302. default:
  303. return NewLogger(path, DefaultRotateRule(path, backupFileDelimiter, options.keepDays,
  304. options.gzipEnabled), options.gzipEnabled)
  305. }
  306. }
  307. func getWriter() Writer {
  308. w := writer.Load()
  309. if w == nil {
  310. w = writer.StoreIfNil(newConsoleWriter())
  311. }
  312. return w
  313. }
  314. func handleOptions(opts []LogOption) {
  315. for _, opt := range opts {
  316. opt(&options)
  317. }
  318. }
  319. func setupLogLevel(c LogConf) {
  320. switch c.Level {
  321. case levelDebug:
  322. SetLevel(DebugLevel)
  323. case levelInfo:
  324. SetLevel(InfoLevel)
  325. case levelError:
  326. SetLevel(ErrorLevel)
  327. case levelSevere:
  328. SetLevel(SevereLevel)
  329. }
  330. }
  331. func setupWithConsole() {
  332. SetWriter(newConsoleWriter())
  333. }
  334. func setupWithFiles(c LogConf) error {
  335. w, err := newFileWriter(c)
  336. if err != nil {
  337. return err
  338. }
  339. SetWriter(w)
  340. return nil
  341. }
  342. func setupWithVolume(c LogConf) error {
  343. if len(c.ServiceName) == 0 {
  344. return ErrLogServiceNameNotSet
  345. }
  346. c.Path = path.Join(c.Path, c.ServiceName, sysx.Hostname())
  347. return setupWithFiles(c)
  348. }
  349. func shallLog(level uint32) bool {
  350. return atomic.LoadUint32(&logLevel) <= level
  351. }
  352. func shallLogStat() bool {
  353. return atomic.LoadUint32(&disableStat) == 0
  354. }
  355. func writeDebug(val any, fields ...LogField) {
  356. if shallLog(DebugLevel) {
  357. getWriter().Debug(val, addCaller(fields...)...)
  358. }
  359. }
  360. func writeError(val any, fields ...LogField) {
  361. if shallLog(ErrorLevel) {
  362. getWriter().Error(val, addCaller(fields...)...)
  363. }
  364. }
  365. func writeInfo(val any, fields ...LogField) {
  366. if shallLog(InfoLevel) {
  367. getWriter().Info(val, addCaller(fields...)...)
  368. }
  369. }
  370. func writeSevere(msg string) {
  371. if shallLog(SevereLevel) {
  372. getWriter().Severe(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
  373. }
  374. }
  375. func writeSlow(val any, fields ...LogField) {
  376. if shallLog(ErrorLevel) {
  377. getWriter().Slow(val, addCaller(fields...)...)
  378. }
  379. }
  380. func writeStack(msg string) {
  381. if shallLog(ErrorLevel) {
  382. getWriter().Stack(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
  383. }
  384. }
  385. func writeStat(msg string) {
  386. if shallLogStat() && shallLog(InfoLevel) {
  387. getWriter().Stat(msg, addCaller()...)
  388. }
  389. }