int.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package hclog
  2. import (
  3. "bufio"
  4. "encoding"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "os"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. )
  15. var (
  16. _levelToBracket = map[Level]string{
  17. Debug: "[DEBUG]",
  18. Trace: "[TRACE]",
  19. Info: "[INFO ]",
  20. Warn: "[WARN ]",
  21. Error: "[ERROR]",
  22. }
  23. )
  24. // Given the options (nil for defaults), create a new Logger
  25. func New(opts *LoggerOptions) Logger {
  26. if opts == nil {
  27. opts = &LoggerOptions{}
  28. }
  29. output := opts.Output
  30. if output == nil {
  31. output = os.Stderr
  32. }
  33. level := opts.Level
  34. if level == NoLevel {
  35. level = DefaultLevel
  36. }
  37. mtx := opts.Mutex
  38. if mtx == nil {
  39. mtx = new(sync.Mutex)
  40. }
  41. ret := &intLogger{
  42. m: mtx,
  43. json: opts.JSONFormat,
  44. caller: opts.IncludeLocation,
  45. name: opts.Name,
  46. timeFormat: TimeFormat,
  47. w: bufio.NewWriter(output),
  48. level: level,
  49. }
  50. if opts.TimeFormat != "" {
  51. ret.timeFormat = opts.TimeFormat
  52. }
  53. return ret
  54. }
  55. // The internal logger implementation. Internal in that it is defined entirely
  56. // by this package.
  57. type intLogger struct {
  58. json bool
  59. caller bool
  60. name string
  61. timeFormat string
  62. // this is a pointer so that it's shared by any derived loggers, since
  63. // those derived loggers share the bufio.Writer as well.
  64. m *sync.Mutex
  65. w *bufio.Writer
  66. level Level
  67. implied []interface{}
  68. }
  69. // Make sure that intLogger is a Logger
  70. var _ Logger = &intLogger{}
  71. // The time format to use for logging. This is a version of RFC3339 that
  72. // contains millisecond precision
  73. const TimeFormat = "2006-01-02T15:04:05.000Z0700"
  74. // Log a message and a set of key/value pairs if the given level is at
  75. // or more severe that the threshold configured in the Logger.
  76. func (z *intLogger) Log(level Level, msg string, args ...interface{}) {
  77. if level < z.level {
  78. return
  79. }
  80. t := time.Now()
  81. z.m.Lock()
  82. defer z.m.Unlock()
  83. if z.json {
  84. z.logJson(t, level, msg, args...)
  85. } else {
  86. z.log(t, level, msg, args...)
  87. }
  88. z.w.Flush()
  89. }
  90. // Cleanup a path by returning the last 2 segments of the path only.
  91. func trimCallerPath(path string) string {
  92. // lovely borrowed from zap
  93. // nb. To make sure we trim the path correctly on Windows too, we
  94. // counter-intuitively need to use '/' and *not* os.PathSeparator here,
  95. // because the path given originates from Go stdlib, specifically
  96. // runtime.Caller() which (as of Mar/17) returns forward slashes even on
  97. // Windows.
  98. //
  99. // See https://github.com/golang/go/issues/3335
  100. // and https://github.com/golang/go/issues/18151
  101. //
  102. // for discussion on the issue on Go side.
  103. //
  104. // Find the last separator.
  105. //
  106. idx := strings.LastIndexByte(path, '/')
  107. if idx == -1 {
  108. return path
  109. }
  110. // Find the penultimate separator.
  111. idx = strings.LastIndexByte(path[:idx], '/')
  112. if idx == -1 {
  113. return path
  114. }
  115. return path[idx+1:]
  116. }
  117. // Non-JSON logging format function
  118. func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) {
  119. z.w.WriteString(t.Format(z.timeFormat))
  120. z.w.WriteByte(' ')
  121. s, ok := _levelToBracket[level]
  122. if ok {
  123. z.w.WriteString(s)
  124. } else {
  125. z.w.WriteString("[UNKN ]")
  126. }
  127. if z.caller {
  128. if _, file, line, ok := runtime.Caller(3); ok {
  129. z.w.WriteByte(' ')
  130. z.w.WriteString(trimCallerPath(file))
  131. z.w.WriteByte(':')
  132. z.w.WriteString(strconv.Itoa(line))
  133. z.w.WriteByte(':')
  134. }
  135. }
  136. z.w.WriteByte(' ')
  137. if z.name != "" {
  138. z.w.WriteString(z.name)
  139. z.w.WriteString(": ")
  140. }
  141. z.w.WriteString(msg)
  142. args = append(z.implied, args...)
  143. var stacktrace CapturedStacktrace
  144. if args != nil && len(args) > 0 {
  145. if len(args)%2 != 0 {
  146. cs, ok := args[len(args)-1].(CapturedStacktrace)
  147. if ok {
  148. args = args[:len(args)-1]
  149. stacktrace = cs
  150. } else {
  151. args = append(args, "<unknown>")
  152. }
  153. }
  154. z.w.WriteByte(':')
  155. FOR:
  156. for i := 0; i < len(args); i = i + 2 {
  157. var val string
  158. switch st := args[i+1].(type) {
  159. case string:
  160. val = st
  161. case int:
  162. val = strconv.FormatInt(int64(st), 10)
  163. case int64:
  164. val = strconv.FormatInt(int64(st), 10)
  165. case int32:
  166. val = strconv.FormatInt(int64(st), 10)
  167. case int16:
  168. val = strconv.FormatInt(int64(st), 10)
  169. case int8:
  170. val = strconv.FormatInt(int64(st), 10)
  171. case uint:
  172. val = strconv.FormatUint(uint64(st), 10)
  173. case uint64:
  174. val = strconv.FormatUint(uint64(st), 10)
  175. case uint32:
  176. val = strconv.FormatUint(uint64(st), 10)
  177. case uint16:
  178. val = strconv.FormatUint(uint64(st), 10)
  179. case uint8:
  180. val = strconv.FormatUint(uint64(st), 10)
  181. case CapturedStacktrace:
  182. stacktrace = st
  183. continue FOR
  184. default:
  185. val = fmt.Sprintf("%v", st)
  186. }
  187. z.w.WriteByte(' ')
  188. z.w.WriteString(args[i].(string))
  189. z.w.WriteByte('=')
  190. if strings.ContainsAny(val, " \t\n\r") {
  191. z.w.WriteByte('"')
  192. z.w.WriteString(val)
  193. z.w.WriteByte('"')
  194. } else {
  195. z.w.WriteString(val)
  196. }
  197. }
  198. }
  199. z.w.WriteString("\n")
  200. if stacktrace != "" {
  201. z.w.WriteString(string(stacktrace))
  202. }
  203. }
  204. // JSON logging function
  205. func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) {
  206. vals := map[string]interface{}{
  207. "@message": msg,
  208. "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"),
  209. }
  210. var levelStr string
  211. switch level {
  212. case Error:
  213. levelStr = "error"
  214. case Warn:
  215. levelStr = "warn"
  216. case Info:
  217. levelStr = "info"
  218. case Debug:
  219. levelStr = "debug"
  220. case Trace:
  221. levelStr = "trace"
  222. default:
  223. levelStr = "all"
  224. }
  225. vals["@level"] = levelStr
  226. if z.name != "" {
  227. vals["@module"] = z.name
  228. }
  229. if z.caller {
  230. if _, file, line, ok := runtime.Caller(3); ok {
  231. vals["@caller"] = fmt.Sprintf("%s:%d", file, line)
  232. }
  233. }
  234. if args != nil && len(args) > 0 {
  235. if len(args)%2 != 0 {
  236. cs, ok := args[len(args)-1].(CapturedStacktrace)
  237. if ok {
  238. args = args[:len(args)-1]
  239. vals["stacktrace"] = cs
  240. } else {
  241. args = append(args, "<unknown>")
  242. }
  243. }
  244. for i := 0; i < len(args); i = i + 2 {
  245. if _, ok := args[i].(string); !ok {
  246. // As this is the logging function not much we can do here
  247. // without injecting into logs...
  248. continue
  249. }
  250. val := args[i+1]
  251. // Check if val is of type error. If error type doesn't
  252. // implement json.Marshaler or encoding.TextMarshaler
  253. // then set val to err.Error() so that it gets marshaled
  254. if err, ok := val.(error); ok {
  255. switch err.(type) {
  256. case json.Marshaler, encoding.TextMarshaler:
  257. default:
  258. val = err.Error()
  259. }
  260. }
  261. vals[args[i].(string)] = val
  262. }
  263. }
  264. err := json.NewEncoder(z.w).Encode(vals)
  265. if err != nil {
  266. panic(err)
  267. }
  268. }
  269. // Emit the message and args at DEBUG level
  270. func (z *intLogger) Debug(msg string, args ...interface{}) {
  271. z.Log(Debug, msg, args...)
  272. }
  273. // Emit the message and args at TRACE level
  274. func (z *intLogger) Trace(msg string, args ...interface{}) {
  275. z.Log(Trace, msg, args...)
  276. }
  277. // Emit the message and args at INFO level
  278. func (z *intLogger) Info(msg string, args ...interface{}) {
  279. z.Log(Info, msg, args...)
  280. }
  281. // Emit the message and args at WARN level
  282. func (z *intLogger) Warn(msg string, args ...interface{}) {
  283. z.Log(Warn, msg, args...)
  284. }
  285. // Emit the message and args at ERROR level
  286. func (z *intLogger) Error(msg string, args ...interface{}) {
  287. z.Log(Error, msg, args...)
  288. }
  289. // Indicate that the logger would emit TRACE level logs
  290. func (z *intLogger) IsTrace() bool {
  291. return z.level == Trace
  292. }
  293. // Indicate that the logger would emit DEBUG level logs
  294. func (z *intLogger) IsDebug() bool {
  295. return z.level <= Debug
  296. }
  297. // Indicate that the logger would emit INFO level logs
  298. func (z *intLogger) IsInfo() bool {
  299. return z.level <= Info
  300. }
  301. // Indicate that the logger would emit WARN level logs
  302. func (z *intLogger) IsWarn() bool {
  303. return z.level <= Warn
  304. }
  305. // Indicate that the logger would emit ERROR level logs
  306. func (z *intLogger) IsError() bool {
  307. return z.level <= Error
  308. }
  309. // Return a sub-Logger for which every emitted log message will contain
  310. // the given key/value pairs. This is used to create a context specific
  311. // Logger.
  312. func (z *intLogger) With(args ...interface{}) Logger {
  313. var nz intLogger = *z
  314. nz.implied = append(nz.implied, args...)
  315. return &nz
  316. }
  317. // Create a new sub-Logger that a name decending from the current name.
  318. // This is used to create a subsystem specific Logger.
  319. func (z *intLogger) Named(name string) Logger {
  320. var nz intLogger = *z
  321. if nz.name != "" {
  322. nz.name = nz.name + "." + name
  323. } else {
  324. nz.name = name
  325. }
  326. return &nz
  327. }
  328. // Create a new sub-Logger with an explicit name. This ignores the current
  329. // name. This is used to create a standalone logger that doesn't fall
  330. // within the normal hierarchy.
  331. func (z *intLogger) ResetNamed(name string) Logger {
  332. var nz intLogger = *z
  333. nz.name = name
  334. return &nz
  335. }
  336. // Create a *log.Logger that will send it's data through this Logger. This
  337. // allows packages that expect to be using the standard library log to actually
  338. // use this logger.
  339. func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
  340. if opts == nil {
  341. opts = &StandardLoggerOptions{}
  342. }
  343. return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0)
  344. }