int.go 8.7 KB

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