logs_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. var opt logOptions
  206. WithKeepDays(1)(&opt)
  207. WithGzip()(&opt)
  208. assert.Nil(t, Close())
  209. writeConsole = false
  210. assert.Nil(t, Close())
  211. }
  212. func TestWithGzip(t *testing.T) {
  213. fn := WithGzip()
  214. var opt logOptions
  215. fn(&opt)
  216. assert.True(t, opt.gzipEnabled)
  217. }
  218. func TestWithKeepDays(t *testing.T) {
  219. fn := WithKeepDays(1)
  220. var opt logOptions
  221. fn(&opt)
  222. assert.Equal(t, 1, opt.keepDays)
  223. }
  224. func BenchmarkCopyByteSliceAppend(b *testing.B) {
  225. for i := 0; i < b.N; i++ {
  226. var buf []byte
  227. buf = append(buf, getTimestamp()...)
  228. buf = append(buf, ' ')
  229. buf = append(buf, s...)
  230. _ = buf
  231. }
  232. }
  233. func BenchmarkCopyByteSliceAllocExactly(b *testing.B) {
  234. for i := 0; i < b.N; i++ {
  235. now := []byte(getTimestamp())
  236. buf := make([]byte, len(now)+1+len(s))
  237. n := copy(buf, now)
  238. buf[n] = ' '
  239. copy(buf[n+1:], s)
  240. }
  241. }
  242. func BenchmarkCopyByteSlice(b *testing.B) {
  243. var buf []byte
  244. for i := 0; i < b.N; i++ {
  245. buf = make([]byte, len(s))
  246. copy(buf, s)
  247. }
  248. fmt.Fprint(ioutil.Discard, buf)
  249. }
  250. func BenchmarkCopyOnWriteByteSlice(b *testing.B) {
  251. var buf []byte
  252. for i := 0; i < b.N; i++ {
  253. size := len(s)
  254. buf = s[:size:size]
  255. }
  256. fmt.Fprint(ioutil.Discard, buf)
  257. }
  258. func BenchmarkCacheByteSlice(b *testing.B) {
  259. for i := 0; i < b.N; i++ {
  260. dup := fetch()
  261. copy(dup, s)
  262. put(dup)
  263. }
  264. }
  265. func BenchmarkLogs(b *testing.B) {
  266. b.ReportAllocs()
  267. log.SetOutput(ioutil.Discard)
  268. for i := 0; i < b.N; i++ {
  269. Info(i)
  270. }
  271. }
  272. func fetch() []byte {
  273. select {
  274. case b := <-pool:
  275. return b
  276. default:
  277. }
  278. return make([]byte, 4096)
  279. }
  280. func getFileLine() (string, int) {
  281. _, file, line, _ := runtime.Caller(1)
  282. short := file
  283. for i := len(file) - 1; i > 0; i-- {
  284. if file[i] == '/' {
  285. short = file[i+1:]
  286. break
  287. }
  288. }
  289. return short, line
  290. }
  291. func put(b []byte) {
  292. select {
  293. case pool <- b:
  294. default:
  295. }
  296. }
  297. func doTestStructedLog(t *testing.T, level string, setup func(writer io.WriteCloser),
  298. write func(...interface{})) {
  299. const message = "hello there"
  300. writer := new(mockWriter)
  301. setup(writer)
  302. atomic.StoreUint32(&initialized, 1)
  303. write(message)
  304. var entry logEntry
  305. if err := json.Unmarshal([]byte(writer.builder.String()), &entry); err != nil {
  306. t.Error(err)
  307. }
  308. assert.Equal(t, level, entry.Level)
  309. assert.True(t, strings.Contains(entry.Content, message))
  310. }
  311. func testSetLevelTwiceWithMode(t *testing.T, mode string) {
  312. SetUp(LogConf{
  313. Mode: mode,
  314. Level: "error",
  315. Path: "/dev/null",
  316. })
  317. SetUp(LogConf{
  318. Mode: mode,
  319. Level: "info",
  320. Path: "/dev/null",
  321. })
  322. const message = "hello there"
  323. writer := new(mockWriter)
  324. infoLog = writer
  325. atomic.StoreUint32(&initialized, 1)
  326. Info(message)
  327. assert.Equal(t, 0, writer.builder.Len())
  328. Infof(message)
  329. assert.Equal(t, 0, writer.builder.Len())
  330. ErrorStack(message)
  331. assert.Equal(t, 0, writer.builder.Len())
  332. ErrorStackf(message)
  333. assert.Equal(t, 0, writer.builder.Len())
  334. }