templates.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "text/template"
  17. )
  18. // ColorizeLevel returns a TermColor byte sequence for the appropriate color
  19. // for the level. If you'd like to configure your own color choices, you can
  20. // make your own template with its own function map to your own colorize
  21. // function.
  22. func ColorizeLevel(level LogLevel) string {
  23. switch level.Match() {
  24. case Critical, Error:
  25. return TermColors{}.Red()
  26. case Warning:
  27. return TermColors{}.Magenta()
  28. case Notice:
  29. return TermColors{}.Yellow()
  30. case Info, Debug, Trace:
  31. return TermColors{}.Green()
  32. }
  33. return ""
  34. }
  35. var (
  36. // ColorTemplate uses the default ColorizeLevel method for color choices.
  37. ColorTemplate = template.Must(template.New("color").Funcs(template.FuncMap{
  38. "ColorizeLevel": ColorizeLevel}).Parse(
  39. `{{.Blue}}{{.Date}} {{.Time}}{{.Reset}} ` +
  40. `{{.Bold}}{{ColorizeLevel .Level}}{{.LevelJustified}}{{.Reset}} ` +
  41. `{{.Underline}}{{.LoggerName}}{{.Reset}} ` +
  42. `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}- ` +
  43. `{{ColorizeLevel .Level}}{{.Message}}{{.Reset}}`))
  44. // StandardTemplate is like ColorTemplate with no color.
  45. StandardTemplate = template.Must(template.New("standard").Parse(
  46. `{{.Date}} {{.Time}} ` +
  47. `{{.Level}} {{.LoggerName}} ` +
  48. `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` +
  49. `- {{.Message}}`))
  50. // SyslogTemplate is missing the date and time as syslog adds those
  51. // things.
  52. SyslogTemplate = template.Must(template.New("syslog").Parse(
  53. `{{.Level}} {{.LoggerName}} ` +
  54. `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` +
  55. `- {{.Message}}`))
  56. // StdlibTemplate is missing the date and time as the stdlib logger often
  57. // adds those things.
  58. StdlibTemplate = template.Must(template.New("stdlib").Parse(
  59. `{{.Level}} {{.LoggerName}} ` +
  60. `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` +
  61. `- {{.Message}}`))
  62. )