int.go 8.6 KB

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