zap_grpc_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 TestNewGRPCLoggerV2(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.InfoLevel),
  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 := NewGRPCLoggerV2(lcfg)
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. // debug level is not enabled,
  47. // so info level gRPC-side logging is discarded
  48. gl.Info("etcd-logutil-1")
  49. data, err := ioutil.ReadFile(logPath)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. if bytes.Contains(data, []byte("etcd-logutil-1")) {
  54. t.Fatalf("unexpected line %q", string(data))
  55. }
  56. gl.Warning("etcd-logutil-2")
  57. data, err = ioutil.ReadFile(logPath)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. if !bytes.Contains(data, []byte("etcd-logutil-2")) {
  62. t.Fatalf("can't find data in log %q", string(data))
  63. }
  64. if !bytes.Contains(data, []byte("logutil/zap_grpc_test.go:")) {
  65. t.Fatalf("unexpected caller; %q", string(data))
  66. }
  67. }
  68. func TestNewGRPCLoggerV2FromZapCore(t *testing.T) {
  69. buf := bytes.NewBuffer(nil)
  70. syncer := zapcore.AddSync(buf)
  71. cr := zapcore.NewCore(
  72. zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
  73. syncer,
  74. zap.NewAtomicLevelAt(zap.InfoLevel),
  75. )
  76. lg := NewGRPCLoggerV2FromZapCore(cr, syncer)
  77. lg.Warning("TestNewGRPCLoggerV2FromZapCore")
  78. txt := buf.String()
  79. if !strings.Contains(txt, "TestNewGRPCLoggerV2FromZapCore") {
  80. t.Fatalf("unexpected log %q", txt)
  81. }
  82. }