logs.go 10.0 KB

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