text.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (C) 2014 Space Monkey, Inc.
  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 spacelog
  15. import (
  16. "bytes"
  17. "fmt"
  18. "runtime"
  19. "strings"
  20. "sync"
  21. "text/template"
  22. "time"
  23. )
  24. // TextHandler is the default implementation of the Handler interface. A
  25. // TextHandler, on log events, makes LogEvent structures, passes them to the
  26. // configured template, and then passes that output to a configured TextOutput
  27. // interface.
  28. type TextHandler struct {
  29. mtx sync.RWMutex
  30. template *template.Template
  31. output TextOutput
  32. }
  33. // NewTextHandler creates a Handler that creates LogEvents, passes them to
  34. // the given template, and passes the result to output
  35. func NewTextHandler(t *template.Template, output TextOutput) *TextHandler {
  36. return &TextHandler{template: t, output: output}
  37. }
  38. // Log makes a LogEvent, formats it with the configured template, then passes
  39. // the output to configured output sink
  40. func (h *TextHandler) Log(logger_name string, level LogLevel, msg string,
  41. calldepth int) {
  42. h.mtx.RLock()
  43. output, template := h.output, h.template
  44. h.mtx.RUnlock()
  45. event := LogEvent{
  46. LoggerName: logger_name,
  47. Level: level,
  48. Message: strings.TrimRight(msg, "\n\r"),
  49. Timestamp: time.Now()}
  50. if calldepth >= 0 {
  51. _, event.Filepath, event.Line, _ = runtime.Caller(calldepth + 1)
  52. }
  53. var buf bytes.Buffer
  54. err := template.Execute(&buf, &event)
  55. if err != nil {
  56. output.Output(level, []byte(
  57. fmt.Sprintf("log format template failed: %s", err)))
  58. return
  59. }
  60. output.Output(level, buf.Bytes())
  61. }
  62. // SetTextTemplate changes the TextHandler's text formatting template
  63. func (h *TextHandler) SetTextTemplate(t *template.Template) {
  64. h.mtx.Lock()
  65. defer h.mtx.Unlock()
  66. h.template = t
  67. }
  68. // SetTextOutput changes the TextHandler's TextOutput sink
  69. func (h *TextHandler) SetTextOutput(output TextOutput) {
  70. h.mtx.Lock()
  71. defer h.mtx.Unlock()
  72. h.output = output
  73. }