logs.go 9.8 KB

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