另客网go项目公用的代码库

logger.go 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package logrus
  2. import (
  3. "io"
  4. "os"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. )
  9. type Logger struct {
  10. // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
  11. // file, or leave it default which is `os.Stderr`. You can also set this to
  12. // something more adventurous, such as logging to Kafka.
  13. Out io.Writer
  14. // Hooks for the logger instance. These allow firing events based on logging
  15. // levels and log entries. For example, to send errors to an error tracking
  16. // service, log to StatsD or dump the core on fatal errors.
  17. Hooks LevelHooks
  18. // All log entries pass through the formatter before logged to Out. The
  19. // included formatters are `TextFormatter` and `JSONFormatter` for which
  20. // TextFormatter is the default. In development (when a TTY is attached) it
  21. // logs with colors, but to a file it wouldn't. You can easily implement your
  22. // own that implements the `Formatter` interface, see the `README` or included
  23. // formatters for examples.
  24. Formatter Formatter
  25. // Flag for whether to log caller info (off by default)
  26. ReportCaller bool
  27. // The logging level the logger should log at. This is typically (and defaults
  28. // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
  29. // logged.
  30. Level Level
  31. // Used to sync writing to the log. Locking is enabled by Default
  32. mu MutexWrap
  33. // Reusable empty entry
  34. entryPool sync.Pool
  35. // Function to exit the application, defaults to `os.Exit()`
  36. ExitFunc exitFunc
  37. }
  38. type exitFunc func(int)
  39. type MutexWrap struct {
  40. lock sync.Mutex
  41. disabled bool
  42. }
  43. func (mw *MutexWrap) Lock() {
  44. if !mw.disabled {
  45. mw.lock.Lock()
  46. }
  47. }
  48. func (mw *MutexWrap) Unlock() {
  49. if !mw.disabled {
  50. mw.lock.Unlock()
  51. }
  52. }
  53. func (mw *MutexWrap) Disable() {
  54. mw.disabled = true
  55. }
  56. // Creates a new logger. Configuration should be set by changing `Formatter`,
  57. // `Out` and `Hooks` directly on the default logger instance. You can also just
  58. // instantiate your own:
  59. //
  60. // var log = &Logger{
  61. // Out: os.Stderr,
  62. // Formatter: new(JSONFormatter),
  63. // Hooks: make(LevelHooks),
  64. // Level: logrus.DebugLevel,
  65. // }
  66. //
  67. // It's recommended to make this a global instance called `log`.
  68. func New() *Logger {
  69. return &Logger{
  70. Out: os.Stderr,
  71. Formatter: new(TextFormatter),
  72. Hooks: make(LevelHooks),
  73. Level: InfoLevel,
  74. ExitFunc: os.Exit,
  75. ReportCaller: false,
  76. }
  77. }
  78. func (logger *Logger) newEntry() *Entry {
  79. entry, ok := logger.entryPool.Get().(*Entry)
  80. if ok {
  81. return entry
  82. }
  83. return NewEntry(logger)
  84. }
  85. func (logger *Logger) releaseEntry(entry *Entry) {
  86. entry.Data = map[string]interface{}{}
  87. logger.entryPool.Put(entry)
  88. }
  89. // Adds a field to the log entry, note that it doesn't log until you call
  90. // Debug, Print, Info, Warn, Error, Fatal or Panic. It only creates a log entry.
  91. // If you want multiple fields, use `WithFields`.
  92. func (logger *Logger) WithField(key string, value interface{}) *Entry {
  93. entry := logger.newEntry()
  94. defer logger.releaseEntry(entry)
  95. return entry.WithField(key, value)
  96. }
  97. // Adds a struct of fields to the log entry. All it does is call `WithField` for
  98. // each `Field`.
  99. func (logger *Logger) WithFields(fields Fields) *Entry {
  100. entry := logger.newEntry()
  101. defer logger.releaseEntry(entry)
  102. return entry.WithFields(fields)
  103. }
  104. // Add an error as single field to the log entry. All it does is call
  105. // `WithError` for the given `error`.
  106. func (logger *Logger) WithError(err error) *Entry {
  107. entry := logger.newEntry()
  108. defer logger.releaseEntry(entry)
  109. return entry.WithError(err)
  110. }
  111. // Overrides the time of the log entry.
  112. func (logger *Logger) WithTime(t time.Time) *Entry {
  113. entry := logger.newEntry()
  114. defer logger.releaseEntry(entry)
  115. return entry.WithTime(t)
  116. }
  117. func (logger *Logger) Logf(level Level, format string, args ...interface{}) {
  118. if logger.IsLevelEnabled(level) {
  119. entry := logger.newEntry()
  120. entry.Logf(level, format, args...)
  121. logger.releaseEntry(entry)
  122. }
  123. }
  124. func (logger *Logger) Tracef(format string, args ...interface{}) {
  125. logger.Logf(TraceLevel, format, args...)
  126. }
  127. func (logger *Logger) Debugf(format string, args ...interface{}) {
  128. logger.Logf(DebugLevel, format, args...)
  129. }
  130. func (logger *Logger) Infof(format string, args ...interface{}) {
  131. logger.Logf(InfoLevel, format, args...)
  132. }
  133. func (logger *Logger) Printf(format string, args ...interface{}) {
  134. entry := logger.newEntry()
  135. entry.Printf(format, args...)
  136. logger.releaseEntry(entry)
  137. }
  138. func (logger *Logger) Warnf(format string, args ...interface{}) {
  139. logger.Logf(WarnLevel, format, args...)
  140. }
  141. func (logger *Logger) Warningf(format string, args ...interface{}) {
  142. logger.Warnf(format, args...)
  143. }
  144. func (logger *Logger) Errorf(format string, args ...interface{}) {
  145. logger.Logf(ErrorLevel, format, args...)
  146. }
  147. func (logger *Logger) Fatalf(format string, args ...interface{}) {
  148. logger.Logf(FatalLevel, format, args...)
  149. logger.Exit(1)
  150. }
  151. func (logger *Logger) Panicf(format string, args ...interface{}) {
  152. logger.Logf(PanicLevel, format, args...)
  153. }
  154. func (logger *Logger) Log(level Level, args ...interface{}) {
  155. if logger.IsLevelEnabled(level) {
  156. entry := logger.newEntry()
  157. entry.Log(level, args...)
  158. logger.releaseEntry(entry)
  159. }
  160. }
  161. func (logger *Logger) Trace(args ...interface{}) {
  162. logger.Log(TraceLevel, args...)
  163. }
  164. func (logger *Logger) Debug(args ...interface{}) {
  165. logger.Log(DebugLevel, args...)
  166. }
  167. func (logger *Logger) Info(args ...interface{}) {
  168. logger.Log(InfoLevel, args...)
  169. }
  170. func (logger *Logger) Print(args ...interface{}) {
  171. entry := logger.newEntry()
  172. entry.Info(args...)
  173. logger.releaseEntry(entry)
  174. }
  175. func (logger *Logger) Warn(args ...interface{}) {
  176. logger.Log(WarnLevel, args...)
  177. }
  178. func (logger *Logger) Warning(args ...interface{}) {
  179. logger.Warn(args...)
  180. }
  181. func (logger *Logger) Error(args ...interface{}) {
  182. logger.Log(ErrorLevel, args...)
  183. }
  184. func (logger *Logger) Fatal(args ...interface{}) {
  185. logger.Log(FatalLevel, args...)
  186. logger.Exit(1)
  187. }
  188. func (logger *Logger) Panic(args ...interface{}) {
  189. logger.Log(PanicLevel, args...)
  190. }
  191. func (logger *Logger) Logln(level Level, args ...interface{}) {
  192. if logger.IsLevelEnabled(level) {
  193. entry := logger.newEntry()
  194. entry.Logln(level, args...)
  195. logger.releaseEntry(entry)
  196. }
  197. }
  198. func (logger *Logger) Traceln(args ...interface{}) {
  199. logger.Logln(TraceLevel, args...)
  200. }
  201. func (logger *Logger) Debugln(args ...interface{}) {
  202. logger.Logln(DebugLevel, args...)
  203. }
  204. func (logger *Logger) Infoln(args ...interface{}) {
  205. logger.Logln(InfoLevel, args...)
  206. }
  207. func (logger *Logger) Println(args ...interface{}) {
  208. entry := logger.newEntry()
  209. entry.Println(args...)
  210. logger.releaseEntry(entry)
  211. }
  212. func (logger *Logger) Warnln(args ...interface{}) {
  213. logger.Logln(WarnLevel, args...)
  214. }
  215. func (logger *Logger) Warningln(args ...interface{}) {
  216. logger.Warn(args...)
  217. }
  218. func (logger *Logger) Errorln(args ...interface{}) {
  219. logger.Logln(ErrorLevel, args...)
  220. }
  221. func (logger *Logger) Fatalln(args ...interface{}) {
  222. logger.Logln(FatalLevel, args...)
  223. logger.Exit(1)
  224. }
  225. func (logger *Logger) Panicln(args ...interface{}) {
  226. logger.Logln(PanicLevel, args...)
  227. }
  228. func (logger *Logger) Exit(code int) {
  229. runHandlers()
  230. if logger.ExitFunc == nil {
  231. logger.ExitFunc = os.Exit
  232. }
  233. logger.ExitFunc(code)
  234. }
  235. //When file is opened with appending mode, it's safe to
  236. //write concurrently to a file (within 4k message on Linux).
  237. //In these cases user can choose to disable the lock.
  238. func (logger *Logger) SetNoLock() {
  239. logger.mu.Disable()
  240. }
  241. func (logger *Logger) level() Level {
  242. return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
  243. }
  244. // SetLevel sets the logger level.
  245. func (logger *Logger) SetLevel(level Level) {
  246. atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
  247. }
  248. // GetLevel returns the logger level.
  249. func (logger *Logger) GetLevel() Level {
  250. return logger.level()
  251. }
  252. // AddHook adds a hook to the logger hooks.
  253. func (logger *Logger) AddHook(hook Hook) {
  254. logger.mu.Lock()
  255. defer logger.mu.Unlock()
  256. logger.Hooks.Add(hook)
  257. }
  258. // IsLevelEnabled checks if the log level of the logger is greater than the level param
  259. func (logger *Logger) IsLevelEnabled(level Level) bool {
  260. return logger.level() >= level
  261. }
  262. // SetFormatter sets the logger formatter.
  263. func (logger *Logger) SetFormatter(formatter Formatter) {
  264. logger.mu.Lock()
  265. defer logger.mu.Unlock()
  266. logger.Formatter = formatter
  267. }
  268. // SetOutput sets the logger output.
  269. func (logger *Logger) SetOutput(output io.Writer) {
  270. logger.mu.Lock()
  271. defer logger.mu.Unlock()
  272. logger.Out = output
  273. }
  274. func (logger *Logger) SetReportCaller(reportCaller bool) {
  275. logger.mu.Lock()
  276. defer logger.mu.Unlock()
  277. logger.ReportCaller = reportCaller
  278. }
  279. // ReplaceHooks replaces the logger hooks and returns the old ones
  280. func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
  281. logger.mu.Lock()
  282. oldHooks := logger.Hooks
  283. logger.Hooks = hooks
  284. logger.mu.Unlock()
  285. return oldHooks
  286. }