logs_test.go 6.2 KB

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