logs_test.go 8.0 KB

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