logs.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. }
  37. // LogField is a key-value pair that will be added to the log entry.
  38. LogField struct {
  39. Key string
  40. Value interface{}
  41. }
  42. // LogOption defines the method to customize the logging.
  43. LogOption func(options *logOptions)
  44. )
  45. // Alert alerts v in alert level, and the message is written to error log.
  46. func Alert(v string) {
  47. getWriter().Alert(v)
  48. }
  49. // Close closes the logging.
  50. func Close() error {
  51. if w := writer.Swap(nil); w != nil {
  52. return w.(io.Closer).Close()
  53. }
  54. return nil
  55. }
  56. // Disable disables the logging.
  57. func Disable() {
  58. writer.Store(nopWriter{})
  59. }
  60. // DisableStat disables the stat logs.
  61. func DisableStat() {
  62. atomic.StoreUint32(&disableStat, 1)
  63. }
  64. // Error writes v into error log.
  65. func Error(v ...interface{}) {
  66. errorTextSync(fmt.Sprint(v...))
  67. }
  68. // Errorf writes v with format into error log.
  69. func Errorf(format string, v ...interface{}) {
  70. errorTextSync(fmt.Errorf(format, v...).Error())
  71. }
  72. // ErrorStack writes v along with call stack into error log.
  73. func ErrorStack(v ...interface{}) {
  74. // there is newline in stack string
  75. stackSync(fmt.Sprint(v...))
  76. }
  77. // ErrorStackf writes v along with call stack in format into error log.
  78. func ErrorStackf(format string, v ...interface{}) {
  79. // there is newline in stack string
  80. stackSync(fmt.Sprintf(format, v...))
  81. }
  82. // Errorv writes v into error log with json content.
  83. // No call stack attached, because not elegant to pack the messages.
  84. func Errorv(v interface{}) {
  85. errorAnySync(v)
  86. }
  87. // Errorw writes msg along with fields into error log.
  88. func Errorw(msg string, fields ...LogField) {
  89. errorFieldsSync(msg, fields...)
  90. }
  91. // Field returns a LogField for the given key and value.
  92. func Field(key string, value interface{}) LogField {
  93. switch val := value.(type) {
  94. case error:
  95. return LogField{Key: key, Value: val.Error()}
  96. case []error:
  97. var errs []string
  98. for _, err := range val {
  99. errs = append(errs, err.Error())
  100. }
  101. return LogField{Key: key, Value: errs}
  102. case time.Duration:
  103. return LogField{Key: key, Value: fmt.Sprint(val)}
  104. case []time.Duration:
  105. var durs []string
  106. for _, dur := range val {
  107. durs = append(durs, fmt.Sprint(dur))
  108. }
  109. return LogField{Key: key, Value: durs}
  110. case []time.Time:
  111. var times []string
  112. for _, t := range val {
  113. times = append(times, fmt.Sprint(t))
  114. }
  115. return LogField{Key: key, Value: times}
  116. case fmt.Stringer:
  117. return LogField{Key: key, Value: val.String()}
  118. case []fmt.Stringer:
  119. var strs []string
  120. for _, str := range val {
  121. strs = append(strs, str.String())
  122. }
  123. return LogField{Key: key, Value: strs}
  124. default:
  125. return LogField{Key: key, Value: val}
  126. }
  127. }
  128. // Info writes v into access log.
  129. func Info(v ...interface{}) {
  130. infoTextSync(fmt.Sprint(v...))
  131. }
  132. // Infof writes v with format into access log.
  133. func Infof(format string, v ...interface{}) {
  134. infoTextSync(fmt.Sprintf(format, v...))
  135. }
  136. // Infov writes v into access log with json content.
  137. func Infov(v interface{}) {
  138. infoAnySync(v)
  139. }
  140. // Infow writes msg along with fields into access log.
  141. func Infow(msg string, fields ...LogField) {
  142. infoFieldsSync(msg, fields...)
  143. }
  144. // Must checks if err is nil, otherwise logs the error and exits.
  145. func Must(err error) {
  146. if err == nil {
  147. return
  148. }
  149. msg := err.Error()
  150. log.Print(msg)
  151. getWriter().Severe(msg)
  152. os.Exit(1)
  153. }
  154. // MustSetup sets up logging with given config c. It exits on error.
  155. func MustSetup(c LogConf) {
  156. Must(SetUp(c))
  157. }
  158. // Reset clears the writer and resets the log level.
  159. func Reset() Writer {
  160. SetLevel(InfoLevel)
  161. return writer.Swap(nil)
  162. }
  163. // SetLevel sets the logging level. It can be used to suppress some logs.
  164. func SetLevel(level uint32) {
  165. atomic.StoreUint32(&logLevel, level)
  166. }
  167. // SetWriter sets the logging writer. It can be used to customize the logging.
  168. // Call Reset before calling SetWriter again.
  169. func SetWriter(w Writer) {
  170. if writer.Load() == nil {
  171. writer.Store(w)
  172. }
  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. func createOutput(path string) (io.WriteCloser, error) {
  250. if len(path) == 0 {
  251. return nil, ErrLogPathNotSet
  252. }
  253. return NewLogger(path, DefaultRotateRule(path, backupFileDelimiter, options.keepDays,
  254. options.gzipEnabled), options.gzipEnabled)
  255. }
  256. func errorAnySync(v interface{}) {
  257. if shallLog(ErrorLevel) {
  258. getWriter().Error(v)
  259. }
  260. }
  261. func errorFieldsSync(content string, fields ...LogField) {
  262. if shallLog(ErrorLevel) {
  263. getWriter().Error(content, fields...)
  264. }
  265. }
  266. func errorTextSync(msg string) {
  267. if shallLog(ErrorLevel) {
  268. getWriter().Error(msg)
  269. }
  270. }
  271. func getWriter() Writer {
  272. w := writer.Load()
  273. if w == nil {
  274. w = newConsoleWriter()
  275. writer.Store(w)
  276. }
  277. return w
  278. }
  279. func handleOptions(opts []LogOption) {
  280. for _, opt := range opts {
  281. opt(&options)
  282. }
  283. }
  284. func infoAnySync(val interface{}) {
  285. if shallLog(InfoLevel) {
  286. getWriter().Info(val)
  287. }
  288. }
  289. func infoFieldsSync(content string, fields ...LogField) {
  290. if shallLog(InfoLevel) {
  291. getWriter().Info(content, fields...)
  292. }
  293. }
  294. func infoTextSync(msg string) {
  295. if shallLog(InfoLevel) {
  296. getWriter().Info(msg)
  297. }
  298. }
  299. func setupLogLevel(c LogConf) {
  300. switch c.Level {
  301. case levelInfo:
  302. SetLevel(InfoLevel)
  303. case levelError:
  304. SetLevel(ErrorLevel)
  305. case levelSevere:
  306. SetLevel(SevereLevel)
  307. }
  308. }
  309. func setupWithConsole() {
  310. SetWriter(newConsoleWriter())
  311. }
  312. func setupWithFiles(c LogConf) error {
  313. w, err := newFileWriter(c)
  314. if err != nil {
  315. return err
  316. }
  317. SetWriter(w)
  318. return nil
  319. }
  320. func setupWithVolume(c LogConf) error {
  321. if len(c.ServiceName) == 0 {
  322. return ErrLogServiceNameNotSet
  323. }
  324. c.Path = path.Join(c.Path, c.ServiceName, sysx.Hostname())
  325. return setupWithFiles(c)
  326. }
  327. func severeSync(msg string) {
  328. if shallLog(SevereLevel) {
  329. getWriter().Severe(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
  330. }
  331. }
  332. func shallLog(level uint32) bool {
  333. return atomic.LoadUint32(&logLevel) <= level
  334. }
  335. func shallLogStat() bool {
  336. return atomic.LoadUint32(&disableStat) == 0
  337. }
  338. func slowAnySync(v interface{}) {
  339. if shallLog(ErrorLevel) {
  340. getWriter().Slow(v)
  341. }
  342. }
  343. func slowFieldsSync(content string, fields ...LogField) {
  344. if shallLog(ErrorLevel) {
  345. getWriter().Slow(content, fields...)
  346. }
  347. }
  348. func slowTextSync(msg string) {
  349. if shallLog(ErrorLevel) {
  350. getWriter().Slow(msg)
  351. }
  352. }
  353. func stackSync(msg string) {
  354. if shallLog(ErrorLevel) {
  355. getWriter().Stack(fmt.Sprintf("%s\n%s", msg, string(debug.Stack())))
  356. }
  357. }
  358. func statSync(msg string) {
  359. if shallLogStat() && shallLog(InfoLevel) {
  360. getWriter().Stat(msg)
  361. }
  362. }