log.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package httplog
  14. import (
  15. "bufio"
  16. "fmt"
  17. "net"
  18. "net/http"
  19. "runtime"
  20. "time"
  21. "github.com/golang/glog"
  22. )
  23. // Handler wraps all HTTP calls to delegate with nice logging.
  24. // delegate may use LogOf(w).Addf(...) to write additional info to
  25. // the per-request log message.
  26. //
  27. // Intended to wrap calls to your ServeMux.
  28. func Handler(delegate http.Handler, pred StacktracePred) http.Handler {
  29. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  30. defer NewLogged(req, &w).StacktraceWhen(pred).Log()
  31. delegate.ServeHTTP(w, req)
  32. })
  33. }
  34. // StacktracePred returns true if a stacktrace should be logged for this status.
  35. type StacktracePred func(httpStatus int) (logStacktrace bool)
  36. type logger interface {
  37. Addf(format string, data ...interface{})
  38. }
  39. // Add a layer on top of ResponseWriter, so we can track latency and error
  40. // message sources.
  41. //
  42. // TODO now that we're using go-restful, we shouldn't need to be wrapping
  43. // the http.ResponseWriter. We can recover panics from go-restful, and
  44. // the logging value is questionable.
  45. type respLogger struct {
  46. hijacked bool
  47. statusRecorded bool
  48. status int
  49. statusStack string
  50. addedInfo string
  51. startTime time.Time
  52. captureErrorOutput bool
  53. req *http.Request
  54. w http.ResponseWriter
  55. logStacktracePred StacktracePred
  56. }
  57. // Simple logger that logs immediately when Addf is called
  58. type passthroughLogger struct{}
  59. // Addf logs info immediately.
  60. func (passthroughLogger) Addf(format string, data ...interface{}) {
  61. glog.V(2).Info(fmt.Sprintf(format, data...))
  62. }
  63. // DefaultStacktracePred is the default implementation of StacktracePred.
  64. func DefaultStacktracePred(status int) bool {
  65. return (status < http.StatusOK || status >= http.StatusInternalServerError) && status != http.StatusSwitchingProtocols
  66. }
  67. // NewLogged turns a normal response writer into a logged response writer.
  68. //
  69. // Usage:
  70. //
  71. // defer NewLogged(req, &w).StacktraceWhen(StatusIsNot(200, 202)).Log()
  72. //
  73. // (Only the call to Log() is deferred, so you can set everything up in one line!)
  74. //
  75. // Note that this *changes* your writer, to route response writing actions
  76. // through the logger.
  77. //
  78. // Use LogOf(w).Addf(...) to log something along with the response result.
  79. func NewLogged(req *http.Request, w *http.ResponseWriter) *respLogger {
  80. if _, ok := (*w).(*respLogger); ok {
  81. // Don't double-wrap!
  82. panic("multiple NewLogged calls!")
  83. }
  84. rl := &respLogger{
  85. startTime: time.Now(),
  86. req: req,
  87. w: *w,
  88. logStacktracePred: DefaultStacktracePred,
  89. }
  90. *w = rl // hijack caller's writer!
  91. return rl
  92. }
  93. // LogOf returns the logger hiding in w. If there is not an existing logger
  94. // then a passthroughLogger will be created which will log to stdout immediately
  95. // when Addf is called.
  96. func LogOf(req *http.Request, w http.ResponseWriter) logger {
  97. if _, exists := w.(*respLogger); !exists {
  98. pl := &passthroughLogger{}
  99. return pl
  100. }
  101. if rl, ok := w.(*respLogger); ok {
  102. return rl
  103. }
  104. panic("Unable to find or create the logger!")
  105. }
  106. // Unlogged returns the original ResponseWriter, or w if it is not our inserted logger.
  107. func Unlogged(w http.ResponseWriter) http.ResponseWriter {
  108. if rl, ok := w.(*respLogger); ok {
  109. return rl.w
  110. }
  111. return w
  112. }
  113. // StacktraceWhen sets the stacktrace logging predicate, which decides when to log a stacktrace.
  114. // There's a default, so you don't need to call this unless you don't like the default.
  115. func (rl *respLogger) StacktraceWhen(pred StacktracePred) *respLogger {
  116. rl.logStacktracePred = pred
  117. return rl
  118. }
  119. // StatusIsNot returns a StacktracePred which will cause stacktraces to be logged
  120. // for any status *not* in the given list.
  121. func StatusIsNot(statuses ...int) StacktracePred {
  122. return func(status int) bool {
  123. for _, s := range statuses {
  124. if status == s {
  125. return false
  126. }
  127. }
  128. return true
  129. }
  130. }
  131. // Addf adds additional data to be logged with this request.
  132. func (rl *respLogger) Addf(format string, data ...interface{}) {
  133. rl.addedInfo += "\n" + fmt.Sprintf(format, data...)
  134. }
  135. // Log is intended to be called once at the end of your request handler, via defer
  136. func (rl *respLogger) Log() {
  137. latency := time.Since(rl.startTime)
  138. if glog.V(2) {
  139. if !rl.hijacked {
  140. glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) %v%v%v [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.status, rl.statusStack, rl.addedInfo, rl.req.Header["User-Agent"], rl.req.RemoteAddr))
  141. } else {
  142. glog.InfoDepth(1, fmt.Sprintf("%s %s: (%v) hijacked [%s %s]", rl.req.Method, rl.req.RequestURI, latency, rl.req.Header["User-Agent"], rl.req.RemoteAddr))
  143. }
  144. }
  145. }
  146. // Header implements http.ResponseWriter.
  147. func (rl *respLogger) Header() http.Header {
  148. return rl.w.Header()
  149. }
  150. // Write implements http.ResponseWriter.
  151. func (rl *respLogger) Write(b []byte) (int, error) {
  152. if !rl.statusRecorded {
  153. rl.recordStatus(http.StatusOK) // Default if WriteHeader hasn't been called
  154. }
  155. if rl.captureErrorOutput {
  156. rl.Addf("logging error output: %q\n", string(b))
  157. }
  158. return rl.w.Write(b)
  159. }
  160. // Flush implements http.Flusher even if the underlying http.Writer doesn't implement it.
  161. // Flush is used for streaming purposes and allows to flush buffered data to the client.
  162. func (rl *respLogger) Flush() {
  163. if flusher, ok := rl.w.(http.Flusher); ok {
  164. flusher.Flush()
  165. } else if glog.V(2) {
  166. glog.InfoDepth(1, fmt.Sprintf("Unable to convert %+v into http.Flusher", rl.w))
  167. }
  168. }
  169. // WriteHeader implements http.ResponseWriter.
  170. func (rl *respLogger) WriteHeader(status int) {
  171. rl.recordStatus(status)
  172. rl.w.WriteHeader(status)
  173. }
  174. // Hijack implements http.Hijacker.
  175. func (rl *respLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  176. rl.hijacked = true
  177. return rl.w.(http.Hijacker).Hijack()
  178. }
  179. // CloseNotify implements http.CloseNotifier
  180. func (rl *respLogger) CloseNotify() <-chan bool {
  181. return rl.w.(http.CloseNotifier).CloseNotify()
  182. }
  183. func (rl *respLogger) recordStatus(status int) {
  184. rl.status = status
  185. rl.statusRecorded = true
  186. if rl.logStacktracePred(status) {
  187. // Only log stacks for errors
  188. stack := make([]byte, 50*1024)
  189. stack = stack[:runtime.Stack(stack, false)]
  190. rl.statusStack = "\n" + string(stack)
  191. rl.captureErrorOutput = true
  192. } else {
  193. rl.statusStack = ""
  194. }
  195. }