logs_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 TestStructedLogInfo(t *testing.T) {
  74. doTestStructedLog(t, levelInfo, func(writer io.WriteCloser) {
  75. infoLog = writer
  76. }, func(v ...interface{}) {
  77. Info(v...)
  78. })
  79. }
  80. func TestStructedLogSlow(t *testing.T) {
  81. doTestStructedLog(t, levelSlow, func(writer io.WriteCloser) {
  82. slowLog = writer
  83. }, func(v ...interface{}) {
  84. Slow(v...)
  85. })
  86. }
  87. func TestStructedLogSlowf(t *testing.T) {
  88. doTestStructedLog(t, levelSlow, func(writer io.WriteCloser) {
  89. slowLog = writer
  90. }, func(v ...interface{}) {
  91. Slowf(fmt.Sprint(v...))
  92. })
  93. }
  94. func TestStructedLogStat(t *testing.T) {
  95. doTestStructedLog(t, levelStat, func(writer io.WriteCloser) {
  96. statLog = writer
  97. }, func(v ...interface{}) {
  98. Stat(v...)
  99. })
  100. }
  101. func TestStructedLogStatf(t *testing.T) {
  102. doTestStructedLog(t, levelStat, func(writer io.WriteCloser) {
  103. statLog = writer
  104. }, func(v ...interface{}) {
  105. Statf(fmt.Sprint(v...))
  106. })
  107. }
  108. func TestStructedLogSevere(t *testing.T) {
  109. doTestStructedLog(t, levelSevere, func(writer io.WriteCloser) {
  110. severeLog = writer
  111. }, func(v ...interface{}) {
  112. Severe(v...)
  113. })
  114. }
  115. func TestStructedLogSeveref(t *testing.T) {
  116. doTestStructedLog(t, levelSevere, func(writer io.WriteCloser) {
  117. severeLog = writer
  118. }, func(v ...interface{}) {
  119. Severef(fmt.Sprint(v...))
  120. })
  121. }
  122. func TestStructedLogWithDuration(t *testing.T) {
  123. const message = "hello there"
  124. writer := new(mockWriter)
  125. infoLog = writer
  126. atomic.StoreUint32(&initialized, 1)
  127. WithDuration(time.Second).Info(message)
  128. var entry logEntry
  129. if err := json.Unmarshal([]byte(writer.builder.String()), &entry); err != nil {
  130. t.Error(err)
  131. }
  132. assert.Equal(t, levelInfo, entry.Level)
  133. assert.Equal(t, message, entry.Content)
  134. assert.Equal(t, "1000.0ms", entry.Duration)
  135. }
  136. func TestSetLevel(t *testing.T) {
  137. SetLevel(ErrorLevel)
  138. const message = "hello there"
  139. writer := new(mockWriter)
  140. infoLog = writer
  141. atomic.StoreUint32(&initialized, 1)
  142. Info(message)
  143. assert.Equal(t, 0, writer.builder.Len())
  144. }
  145. func TestSetLevelTwiceWithMode(t *testing.T) {
  146. testModes := []string{
  147. "mode",
  148. "console",
  149. "volumn",
  150. }
  151. for _, mode := range testModes {
  152. testSetLevelTwiceWithMode(t, mode)
  153. }
  154. }
  155. func TestSetLevelWithDuration(t *testing.T) {
  156. SetLevel(ErrorLevel)
  157. const message = "hello there"
  158. writer := new(mockWriter)
  159. infoLog = writer
  160. atomic.StoreUint32(&initialized, 1)
  161. WithDuration(time.Second).Info(message)
  162. assert.Equal(t, 0, writer.builder.Len())
  163. }
  164. func TestMustNil(t *testing.T) {
  165. Must(nil)
  166. }
  167. func TestSetup(t *testing.T) {
  168. MustSetup(LogConf{
  169. ServiceName: "any",
  170. Mode: "console",
  171. })
  172. MustSetup(LogConf{
  173. ServiceName: "any",
  174. Mode: "file",
  175. Path: os.TempDir(),
  176. })
  177. MustSetup(LogConf{
  178. ServiceName: "any",
  179. Mode: "volume",
  180. Path: os.TempDir(),
  181. })
  182. assert.NotNil(t, setupWithVolume(LogConf{}))
  183. assert.NotNil(t, setupWithFiles(LogConf{}))
  184. assert.Nil(t, setupWithFiles(LogConf{
  185. ServiceName: "any",
  186. Path: os.TempDir(),
  187. Compress: true,
  188. KeepDays: 1,
  189. }))
  190. setupLogLevel(LogConf{
  191. Level: levelInfo,
  192. })
  193. setupLogLevel(LogConf{
  194. Level: levelError,
  195. })
  196. setupLogLevel(LogConf{
  197. Level: levelSevere,
  198. })
  199. _, err := createOutput("")
  200. assert.NotNil(t, err)
  201. Disable()
  202. }
  203. func TestDisable(t *testing.T) {
  204. Disable()
  205. WithKeepDays(1)
  206. WithGzip()
  207. assert.Nil(t, Close())
  208. writeConsole = false
  209. assert.Nil(t, Close())
  210. }
  211. func TestWithGzip(t *testing.T) {
  212. fn := WithGzip()
  213. var opt logOptions
  214. fn(&opt)
  215. assert.True(t, opt.gzipEnabled)
  216. }
  217. func TestWithKeepDays(t *testing.T) {
  218. fn := WithKeepDays(1)
  219. var opt logOptions
  220. fn(&opt)
  221. assert.Equal(t, 1, opt.keepDays)
  222. }
  223. func BenchmarkCopyByteSliceAppend(b *testing.B) {
  224. for i := 0; i < b.N; i++ {
  225. var buf []byte
  226. buf = append(buf, getTimestamp()...)
  227. buf = append(buf, ' ')
  228. buf = append(buf, s...)
  229. _ = buf
  230. }
  231. }
  232. func BenchmarkCopyByteSliceAllocExactly(b *testing.B) {
  233. for i := 0; i < b.N; i++ {
  234. now := []byte(getTimestamp())
  235. buf := make([]byte, len(now)+1+len(s))
  236. n := copy(buf, now)
  237. buf[n] = ' '
  238. copy(buf[n+1:], s)
  239. }
  240. }
  241. func BenchmarkCopyByteSlice(b *testing.B) {
  242. var buf []byte
  243. for i := 0; i < b.N; i++ {
  244. buf = make([]byte, len(s))
  245. copy(buf, s)
  246. }
  247. fmt.Fprint(ioutil.Discard, buf)
  248. }
  249. func BenchmarkCopyOnWriteByteSlice(b *testing.B) {
  250. var buf []byte
  251. for i := 0; i < b.N; i++ {
  252. size := len(s)
  253. buf = s[:size:size]
  254. }
  255. fmt.Fprint(ioutil.Discard, buf)
  256. }
  257. func BenchmarkCacheByteSlice(b *testing.B) {
  258. for i := 0; i < b.N; i++ {
  259. dup := fetch()
  260. copy(dup, s)
  261. put(dup)
  262. }
  263. }
  264. func BenchmarkLogs(b *testing.B) {
  265. b.ReportAllocs()
  266. log.SetOutput(ioutil.Discard)
  267. for i := 0; i < b.N; i++ {
  268. Info(i)
  269. }
  270. }
  271. func fetch() []byte {
  272. select {
  273. case b := <-pool:
  274. return b
  275. default:
  276. }
  277. return make([]byte, 4096)
  278. }
  279. func getFileLine() (string, int) {
  280. _, file, line, _ := runtime.Caller(1)
  281. short := file
  282. for i := len(file) - 1; i > 0; i-- {
  283. if file[i] == '/' {
  284. short = file[i+1:]
  285. break
  286. }
  287. }
  288. return short, line
  289. }
  290. func put(b []byte) {
  291. select {
  292. case pool <- b:
  293. default:
  294. }
  295. }
  296. func doTestStructedLog(t *testing.T, level string, setup func(writer io.WriteCloser),
  297. write func(...interface{})) {
  298. const message = "hello there"
  299. writer := new(mockWriter)
  300. setup(writer)
  301. atomic.StoreUint32(&initialized, 1)
  302. write(message)
  303. var entry logEntry
  304. if err := json.Unmarshal([]byte(writer.builder.String()), &entry); err != nil {
  305. t.Error(err)
  306. }
  307. assert.Equal(t, level, entry.Level)
  308. assert.True(t, strings.Contains(entry.Content, message))
  309. }
  310. func testSetLevelTwiceWithMode(t *testing.T, mode string) {
  311. SetUp(LogConf{
  312. Mode: mode,
  313. Level: "error",
  314. Path: "/dev/null",
  315. })
  316. SetUp(LogConf{
  317. Mode: mode,
  318. Level: "info",
  319. Path: "/dev/null",
  320. })
  321. const message = "hello there"
  322. writer := new(mockWriter)
  323. infoLog = writer
  324. atomic.StoreUint32(&initialized, 1)
  325. Info(message)
  326. assert.Equal(t, 0, writer.builder.Len())
  327. Infof(message)
  328. assert.Equal(t, 0, writer.builder.Len())
  329. ErrorStack(message)
  330. assert.Equal(t, 0, writer.builder.Len())
  331. ErrorStackf(message)
  332. assert.Equal(t, 0, writer.builder.Len())
  333. }