logs_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package logx
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "testing"
  14. "time"
  15. "github.com/stretchr/testify/assert"
  16. )
  17. var (
  18. s = []byte("Sending #11 notification (id: 1451875113812010473) in #1 connection")
  19. pool = make(chan []byte, 1)
  20. )
  21. type mockWriter struct {
  22. lock sync.Mutex
  23. builder strings.Builder
  24. }
  25. func (mw *mockWriter) Write(data []byte) (int, error) {
  26. mw.lock.Lock()
  27. defer mw.lock.Unlock()
  28. return mw.builder.Write(data)
  29. }
  30. func (mw *mockWriter) Close() error {
  31. return nil
  32. }
  33. func (mw *mockWriter) Contains(text string) bool {
  34. mw.lock.Lock()
  35. defer mw.lock.Unlock()
  36. return strings.Contains(mw.builder.String(), text)
  37. }
  38. func (mw *mockWriter) Reset() {
  39. mw.lock.Lock()
  40. defer mw.lock.Unlock()
  41. mw.builder.Reset()
  42. }
  43. func (mw *mockWriter) String() string {
  44. mw.lock.Lock()
  45. defer mw.lock.Unlock()
  46. return mw.builder.String()
  47. }
  48. func TestFileLineFileMode(t *testing.T) {
  49. writer := new(mockWriter)
  50. errorLog = writer
  51. atomic.StoreUint32(&initialized, 1)
  52. file, line := getFileLine()
  53. Error("anything")
  54. assert.True(t, writer.Contains(fmt.Sprintf("%s:%d", file, line+1)))
  55. writer.Reset()
  56. file, line = getFileLine()
  57. Errorf("anything %s", "format")
  58. assert.True(t, writer.Contains(fmt.Sprintf("%s:%d", file, line+1)))
  59. }
  60. func TestFileLineConsoleMode(t *testing.T) {
  61. writer := new(mockWriter)
  62. writeConsole = true
  63. errorLog = newLogWriter(log.New(writer, "[ERROR] ", flags))
  64. atomic.StoreUint32(&initialized, 1)
  65. file, line := getFileLine()
  66. Error("anything")
  67. assert.True(t, writer.Contains(fmt.Sprintf("%s:%d", file, line+1)))
  68. writer.Reset()
  69. file, line = getFileLine()
  70. Errorf("anything %s", "format")
  71. assert.True(t, writer.Contains(fmt.Sprintf("%s:%d", file, line+1)))
  72. }
  73. func TestStructedLogAlert(t *testing.T) {
  74. doTestStructedLog(t, levelAlert, func(writer io.WriteCloser) {
  75. errorLog = writer
  76. }, func(v ...interface{}) {
  77. Alert(fmt.Sprint(v...))
  78. })
  79. }
  80. func TestStructedLogInfo(t *testing.T) {
  81. doTestStructedLog(t, levelInfo, func(writer io.WriteCloser) {
  82. infoLog = writer
  83. }, func(v ...interface{}) {
  84. Info(v...)
  85. })
  86. }
  87. func TestStructedLogSlow(t *testing.T) {
  88. doTestStructedLog(t, levelSlow, func(writer io.WriteCloser) {
  89. slowLog = writer
  90. }, func(v ...interface{}) {
  91. Slow(v...)
  92. })
  93. }
  94. func TestStructedLogSlowf(t *testing.T) {
  95. doTestStructedLog(t, levelSlow, func(writer io.WriteCloser) {
  96. slowLog = writer
  97. }, func(v ...interface{}) {
  98. Slowf(fmt.Sprint(v...))
  99. })
  100. }
  101. func TestStructedLogStat(t *testing.T) {
  102. doTestStructedLog(t, levelStat, func(writer io.WriteCloser) {
  103. statLog = writer
  104. }, func(v ...interface{}) {
  105. Stat(v...)
  106. })
  107. }
  108. func TestStructedLogStatf(t *testing.T) {
  109. doTestStructedLog(t, levelStat, func(writer io.WriteCloser) {
  110. statLog = writer
  111. }, func(v ...interface{}) {
  112. Statf(fmt.Sprint(v...))
  113. })
  114. }
  115. func TestStructedLogSevere(t *testing.T) {
  116. doTestStructedLog(t, levelSevere, func(writer io.WriteCloser) {
  117. severeLog = writer
  118. }, func(v ...interface{}) {
  119. Severe(v...)
  120. })
  121. }
  122. func TestStructedLogSeveref(t *testing.T) {
  123. doTestStructedLog(t, levelSevere, func(writer io.WriteCloser) {
  124. severeLog = writer
  125. }, func(v ...interface{}) {
  126. Severef(fmt.Sprint(v...))
  127. })
  128. }
  129. func TestStructedLogWithDuration(t *testing.T) {
  130. const message = "hello there"
  131. writer := new(mockWriter)
  132. infoLog = writer
  133. atomic.StoreUint32(&initialized, 1)
  134. WithDuration(time.Second).Info(message)
  135. var entry logEntry
  136. if err := json.Unmarshal([]byte(writer.builder.String()), &entry); err != nil {
  137. t.Error(err)
  138. }
  139. assert.Equal(t, levelInfo, entry.Level)
  140. assert.Equal(t, message, entry.Content)
  141. assert.Equal(t, "1000.0ms", entry.Duration)
  142. }
  143. func TestSetLevel(t *testing.T) {
  144. SetLevel(ErrorLevel)
  145. const message = "hello there"
  146. writer := new(mockWriter)
  147. infoLog = writer
  148. atomic.StoreUint32(&initialized, 1)
  149. Info(message)
  150. assert.Equal(t, 0, writer.builder.Len())
  151. }
  152. func TestSetLevelTwiceWithMode(t *testing.T) {
  153. testModes := []string{
  154. "mode",
  155. "console",
  156. "volumn",
  157. }
  158. for _, mode := range testModes {
  159. testSetLevelTwiceWithMode(t, mode)
  160. }
  161. }
  162. func TestSetLevelWithDuration(t *testing.T) {
  163. SetLevel(ErrorLevel)
  164. const message = "hello there"
  165. writer := new(mockWriter)
  166. infoLog = writer
  167. atomic.StoreUint32(&initialized, 1)
  168. WithDuration(time.Second).Info(message)
  169. assert.Equal(t, 0, writer.builder.Len())
  170. }
  171. func TestMustNil(t *testing.T) {
  172. Must(nil)
  173. }
  174. func TestSetup(t *testing.T) {
  175. MustSetup(LogConf{
  176. ServiceName: "any",
  177. Mode: "console",
  178. })
  179. MustSetup(LogConf{
  180. ServiceName: "any",
  181. Mode: "file",
  182. Path: os.TempDir(),
  183. })
  184. MustSetup(LogConf{
  185. ServiceName: "any",
  186. Mode: "volume",
  187. Path: os.TempDir(),
  188. })
  189. assert.NotNil(t, setupWithVolume(LogConf{}))
  190. assert.NotNil(t, setupWithFiles(LogConf{}))
  191. assert.Nil(t, setupWithFiles(LogConf{
  192. ServiceName: "any",
  193. Path: os.TempDir(),
  194. Compress: true,
  195. KeepDays: 1,
  196. }))
  197. setupLogLevel(LogConf{
  198. Level: levelInfo,
  199. })
  200. setupLogLevel(LogConf{
  201. Level: levelError,
  202. })
  203. setupLogLevel(LogConf{
  204. Level: levelSevere,
  205. })
  206. _, err := createOutput("")
  207. assert.NotNil(t, err)
  208. Disable()
  209. }
  210. func TestDisable(t *testing.T) {
  211. Disable()
  212. var opt logOptions
  213. WithKeepDays(1)(&opt)
  214. WithGzip()(&opt)
  215. assert.Nil(t, Close())
  216. writeConsole = false
  217. assert.Nil(t, Close())
  218. }
  219. func TestWithGzip(t *testing.T) {
  220. fn := WithGzip()
  221. var opt logOptions
  222. fn(&opt)
  223. assert.True(t, opt.gzipEnabled)
  224. }
  225. func TestWithKeepDays(t *testing.T) {
  226. fn := WithKeepDays(1)
  227. var opt logOptions
  228. fn(&opt)
  229. assert.Equal(t, 1, opt.keepDays)
  230. }
  231. func BenchmarkCopyByteSliceAppend(b *testing.B) {
  232. for i := 0; i < b.N; i++ {
  233. var buf []byte
  234. buf = append(buf, getTimestamp()...)
  235. buf = append(buf, ' ')
  236. buf = append(buf, s...)
  237. _ = buf
  238. }
  239. }
  240. func BenchmarkCopyByteSliceAllocExactly(b *testing.B) {
  241. for i := 0; i < b.N; i++ {
  242. now := []byte(getTimestamp())
  243. buf := make([]byte, len(now)+1+len(s))
  244. n := copy(buf, now)
  245. buf[n] = ' '
  246. copy(buf[n+1:], s)
  247. }
  248. }
  249. func BenchmarkCopyByteSlice(b *testing.B) {
  250. var buf []byte
  251. for i := 0; i < b.N; i++ {
  252. buf = make([]byte, len(s))
  253. copy(buf, s)
  254. }
  255. fmt.Fprint(ioutil.Discard, buf)
  256. }
  257. func BenchmarkCopyOnWriteByteSlice(b *testing.B) {
  258. var buf []byte
  259. for i := 0; i < b.N; i++ {
  260. size := len(s)
  261. buf = s[:size:size]
  262. }
  263. fmt.Fprint(ioutil.Discard, buf)
  264. }
  265. func BenchmarkCacheByteSlice(b *testing.B) {
  266. for i := 0; i < b.N; i++ {
  267. dup := fetch()
  268. copy(dup, s)
  269. put(dup)
  270. }
  271. }
  272. func BenchmarkLogs(b *testing.B) {
  273. b.ReportAllocs()
  274. log.SetOutput(ioutil.Discard)
  275. for i := 0; i < b.N; i++ {
  276. Info(i)
  277. }
  278. }
  279. func fetch() []byte {
  280. select {
  281. case b := <-pool:
  282. return b
  283. default:
  284. }
  285. return make([]byte, 4096)
  286. }
  287. func getFileLine() (string, int) {
  288. _, file, line, _ := runtime.Caller(1)
  289. short := file
  290. for i := len(file) - 1; i > 0; i-- {
  291. if file[i] == '/' {
  292. short = file[i+1:]
  293. break
  294. }
  295. }
  296. return short, line
  297. }
  298. func put(b []byte) {
  299. select {
  300. case pool <- b:
  301. default:
  302. }
  303. }
  304. func doTestStructedLog(t *testing.T, level string, setup func(writer io.WriteCloser),
  305. write func(...interface{})) {
  306. const message = "hello there"
  307. writer := new(mockWriter)
  308. setup(writer)
  309. atomic.StoreUint32(&initialized, 1)
  310. write(message)
  311. var entry logEntry
  312. if err := json.Unmarshal([]byte(writer.builder.String()), &entry); err != nil {
  313. t.Error(err)
  314. }
  315. assert.Equal(t, level, entry.Level)
  316. assert.True(t, strings.Contains(entry.Content, message))
  317. }
  318. func testSetLevelTwiceWithMode(t *testing.T, mode string) {
  319. SetUp(LogConf{
  320. Mode: mode,
  321. Level: "error",
  322. Path: "/dev/null",
  323. })
  324. SetUp(LogConf{
  325. Mode: mode,
  326. Level: "info",
  327. Path: "/dev/null",
  328. })
  329. const message = "hello there"
  330. writer := new(mockWriter)
  331. infoLog = writer
  332. atomic.StoreUint32(&initialized, 1)
  333. Info(message)
  334. assert.Equal(t, 0, writer.builder.Len())
  335. Infof(message)
  336. assert.Equal(t, 0, writer.builder.Len())
  337. ErrorStack(message)
  338. assert.Equal(t, 0, writer.builder.Len())
  339. ErrorStackf(message)
  340. assert.Equal(t, 0, writer.builder.Len())
  341. }