sink.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright (c) 2016-2022 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package zap
  21. import (
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net/url"
  26. "os"
  27. "path/filepath"
  28. "strings"
  29. "sync"
  30. "go.uber.org/zap/zapcore"
  31. )
  32. const schemeFile = "file"
  33. var _sinkRegistry = newSinkRegistry()
  34. // Sink defines the interface to write to and close logger destinations.
  35. type Sink interface {
  36. zapcore.WriteSyncer
  37. io.Closer
  38. }
  39. type errSinkNotFound struct {
  40. scheme string
  41. }
  42. func (e *errSinkNotFound) Error() string {
  43. return fmt.Sprintf("no sink found for scheme %q", e.scheme)
  44. }
  45. type nopCloserSink struct{ zapcore.WriteSyncer }
  46. func (nopCloserSink) Close() error { return nil }
  47. type sinkRegistry struct {
  48. mu sync.Mutex
  49. factories map[string]func(*url.URL) (Sink, error) // keyed by scheme
  50. openFile func(string, int, os.FileMode) (*os.File, error) // type matches os.OpenFile
  51. }
  52. func newSinkRegistry() *sinkRegistry {
  53. sr := &sinkRegistry{
  54. factories: make(map[string]func(*url.URL) (Sink, error)),
  55. openFile: os.OpenFile,
  56. }
  57. sr.RegisterSink(schemeFile, sr.newFileSinkFromURL)
  58. return sr
  59. }
  60. // RegisterScheme registers the given factory for the specific scheme.
  61. func (sr *sinkRegistry) RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error {
  62. sr.mu.Lock()
  63. defer sr.mu.Unlock()
  64. if scheme == "" {
  65. return errors.New("can't register a sink factory for empty string")
  66. }
  67. normalized, err := normalizeScheme(scheme)
  68. if err != nil {
  69. return fmt.Errorf("%q is not a valid scheme: %v", scheme, err)
  70. }
  71. if _, ok := sr.factories[normalized]; ok {
  72. return fmt.Errorf("sink factory already registered for scheme %q", normalized)
  73. }
  74. sr.factories[normalized] = factory
  75. return nil
  76. }
  77. func (sr *sinkRegistry) newSink(rawURL string) (Sink, error) {
  78. // URL parsing doesn't work well for Windows paths such as `c:\log.txt`, as scheme is set to
  79. // the drive, and path is unset unless `c:/log.txt` is used.
  80. // To avoid Windows-specific URL handling, we instead check IsAbs to open as a file.
  81. // filepath.IsAbs is OS-specific, so IsAbs('c:/log.txt') is false outside of Windows.
  82. if filepath.IsAbs(rawURL) {
  83. return sr.newFileSinkFromPath(rawURL)
  84. }
  85. u, err := url.Parse(rawURL)
  86. if err != nil {
  87. return nil, fmt.Errorf("can't parse %q as a URL: %v", rawURL, err)
  88. }
  89. if u.Scheme == "" {
  90. u.Scheme = schemeFile
  91. }
  92. sr.mu.Lock()
  93. factory, ok := sr.factories[u.Scheme]
  94. sr.mu.Unlock()
  95. if !ok {
  96. return nil, &errSinkNotFound{u.Scheme}
  97. }
  98. return factory(u)
  99. }
  100. // RegisterSink registers a user-supplied factory for all sinks with a
  101. // particular scheme.
  102. //
  103. // All schemes must be ASCII, valid under section 0.1 of RFC 3986
  104. // (https://tools.ietf.org/html/rfc3983#section-3.1), and must not already
  105. // have a factory registered. Zap automatically registers a factory for the
  106. // "file" scheme.
  107. func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error {
  108. return _sinkRegistry.RegisterSink(scheme, factory)
  109. }
  110. func (sr *sinkRegistry) newFileSinkFromURL(u *url.URL) (Sink, error) {
  111. if u.User != nil {
  112. return nil, fmt.Errorf("user and password not allowed with file URLs: got %v", u)
  113. }
  114. if u.Fragment != "" {
  115. return nil, fmt.Errorf("fragments not allowed with file URLs: got %v", u)
  116. }
  117. if u.RawQuery != "" {
  118. return nil, fmt.Errorf("query parameters not allowed with file URLs: got %v", u)
  119. }
  120. // Error messages are better if we check hostname and port separately.
  121. if u.Port() != "" {
  122. return nil, fmt.Errorf("ports not allowed with file URLs: got %v", u)
  123. }
  124. if hn := u.Hostname(); hn != "" && hn != "localhost" {
  125. return nil, fmt.Errorf("file URLs must leave host empty or use localhost: got %v", u)
  126. }
  127. return sr.newFileSinkFromPath(u.Path)
  128. }
  129. func (sr *sinkRegistry) newFileSinkFromPath(path string) (Sink, error) {
  130. switch path {
  131. case "stdout":
  132. return nopCloserSink{os.Stdout}, nil
  133. case "stderr":
  134. return nopCloserSink{os.Stderr}, nil
  135. }
  136. return sr.openFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
  137. }
  138. func normalizeScheme(s string) (string, error) {
  139. // https://tools.ietf.org/html/rfc3986#section-3.1
  140. s = strings.ToLower(s)
  141. if first := s[0]; 'a' > first || 'z' < first {
  142. return "", errors.New("must start with a letter")
  143. }
  144. for i := 1; i < len(s); i++ { // iterate over bytes, not runes
  145. c := s[i]
  146. switch {
  147. case 'a' <= c && c <= 'z':
  148. continue
  149. case '0' <= c && c <= '9':
  150. continue
  151. case c == '.' || c == '+' || c == '-':
  152. continue
  153. }
  154. return "", fmt.Errorf("may not contain %q", c)
  155. }
  156. return s, nil
  157. }