sink.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Copyright (c) 2016 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. "strings"
  28. "sync"
  29. "go.uber.org/zap/zapcore"
  30. )
  31. const schemeFile = "file"
  32. var (
  33. _sinkMutex sync.RWMutex
  34. _sinkFactories map[string]func(*url.URL) (Sink, error) // keyed by scheme
  35. )
  36. func init() {
  37. resetSinkRegistry()
  38. }
  39. func resetSinkRegistry() {
  40. _sinkMutex.Lock()
  41. defer _sinkMutex.Unlock()
  42. _sinkFactories = map[string]func(*url.URL) (Sink, error){
  43. schemeFile: newFileSink,
  44. }
  45. }
  46. // Sink defines the interface to write to and close logger destinations.
  47. type Sink interface {
  48. zapcore.WriteSyncer
  49. io.Closer
  50. }
  51. type nopCloserSink struct{ zapcore.WriteSyncer }
  52. func (nopCloserSink) Close() error { return nil }
  53. type errSinkNotFound struct {
  54. scheme string
  55. }
  56. func (e *errSinkNotFound) Error() string {
  57. return fmt.Sprintf("no sink found for scheme %q", e.scheme)
  58. }
  59. // RegisterSink registers a user-supplied factory for all sinks with a
  60. // particular scheme.
  61. //
  62. // All schemes must be ASCII, valid under section 3.1 of RFC 3986
  63. // (https://tools.ietf.org/html/rfc3986#section-3.1), and must not already
  64. // have a factory registered. Zap automatically registers a factory for the
  65. // "file" scheme.
  66. func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error {
  67. _sinkMutex.Lock()
  68. defer _sinkMutex.Unlock()
  69. if scheme == "" {
  70. return errors.New("can't register a sink factory for empty string")
  71. }
  72. normalized, err := normalizeScheme(scheme)
  73. if err != nil {
  74. return fmt.Errorf("%q is not a valid scheme: %v", scheme, err)
  75. }
  76. if _, ok := _sinkFactories[normalized]; ok {
  77. return fmt.Errorf("sink factory already registered for scheme %q", normalized)
  78. }
  79. _sinkFactories[normalized] = factory
  80. return nil
  81. }
  82. func newSink(rawURL string) (Sink, error) {
  83. u, err := url.Parse(rawURL)
  84. if err != nil {
  85. return nil, fmt.Errorf("can't parse %q as a URL: %v", rawURL, err)
  86. }
  87. if u.Scheme == "" {
  88. u.Scheme = schemeFile
  89. }
  90. _sinkMutex.RLock()
  91. factory, ok := _sinkFactories[u.Scheme]
  92. _sinkMutex.RUnlock()
  93. if !ok {
  94. return nil, &errSinkNotFound{u.Scheme}
  95. }
  96. return factory(u)
  97. }
  98. func newFileSink(u *url.URL) (Sink, error) {
  99. if u.User != nil {
  100. return nil, fmt.Errorf("user and password not allowed with file URLs: got %v", u)
  101. }
  102. if u.Fragment != "" {
  103. return nil, fmt.Errorf("fragments not allowed with file URLs: got %v", u)
  104. }
  105. if u.RawQuery != "" {
  106. return nil, fmt.Errorf("query parameters not allowed with file URLs: got %v", u)
  107. }
  108. // Error messages are better if we check hostname and port separately.
  109. if u.Port() != "" {
  110. return nil, fmt.Errorf("ports not allowed with file URLs: got %v", u)
  111. }
  112. if hn := u.Hostname(); hn != "" && hn != "localhost" {
  113. return nil, fmt.Errorf("file URLs must leave host empty or use localhost: got %v", u)
  114. }
  115. switch u.Path {
  116. case "stdout":
  117. return nopCloserSink{os.Stdout}, nil
  118. case "stderr":
  119. return nopCloserSink{os.Stderr}, nil
  120. }
  121. return os.OpenFile(u.Path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
  122. }
  123. func normalizeScheme(s string) (string, error) {
  124. // https://tools.ietf.org/html/rfc3986#section-3.1
  125. s = strings.ToLower(s)
  126. if first := s[0]; 'a' > first || 'z' < first {
  127. return "", errors.New("must start with a letter")
  128. }
  129. for i := 1; i < len(s); i++ { // iterate over bytes, not runes
  130. c := s[i]
  131. switch {
  132. case 'a' <= c && c <= 'z':
  133. continue
  134. case '0' <= c && c <= '9':
  135. continue
  136. case c == '.' || c == '+' || c == '-':
  137. continue
  138. }
  139. return "", fmt.Errorf("may not contain %q", c)
  140. }
  141. return s, nil
  142. }