zap_raft_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package logutil
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "testing"
  23. "time"
  24. "go.uber.org/zap"
  25. "go.uber.org/zap/zapcore"
  26. )
  27. func TestNewRaftLogger(t *testing.T) {
  28. logPath := filepath.Join(os.TempDir(), fmt.Sprintf("test-log-%d", time.Now().UnixNano()))
  29. defer os.RemoveAll(logPath)
  30. lcfg := &zap.Config{
  31. Level: zap.NewAtomicLevelAt(zap.DebugLevel),
  32. Development: false,
  33. Sampling: &zap.SamplingConfig{
  34. Initial: 100,
  35. Thereafter: 100,
  36. },
  37. Encoding: "json",
  38. EncoderConfig: DefaultZapLoggerConfig.EncoderConfig,
  39. OutputPaths: []string{logPath},
  40. ErrorOutputPaths: []string{logPath},
  41. }
  42. gl, err := NewRaftLogger(lcfg)
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. gl.Info("etcd-logutil-1")
  47. data, err := ioutil.ReadFile(logPath)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. if !bytes.Contains(data, []byte("etcd-logutil-1")) {
  52. t.Fatalf("can't find data in log %q", string(data))
  53. }
  54. gl.Warning("etcd-logutil-2")
  55. data, err = ioutil.ReadFile(logPath)
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. if !bytes.Contains(data, []byte("etcd-logutil-2")) {
  60. t.Fatalf("can't find data in log %q", string(data))
  61. }
  62. if !bytes.Contains(data, []byte("logutil/zap_raft_test.go:")) {
  63. t.Fatalf("unexpected caller; %q", string(data))
  64. }
  65. }
  66. func TestNewRaftLoggerFromZapCore(t *testing.T) {
  67. buf := bytes.NewBuffer(nil)
  68. syncer := zapcore.AddSync(buf)
  69. cr := zapcore.NewCore(
  70. zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
  71. syncer,
  72. zap.NewAtomicLevelAt(zap.InfoLevel),
  73. )
  74. lg := NewRaftLoggerFromZapCore(cr, syncer)
  75. lg.Info("TestNewRaftLoggerFromZapCore")
  76. txt := buf.String()
  77. if !strings.Contains(txt, "TestNewRaftLoggerFromZapCore") {
  78. t.Fatalf("unexpected log %q", txt)
  79. }
  80. }