event.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "path/filepath"
  17. "strings"
  18. "time"
  19. )
  20. // TermColors is a type that knows how to output terminal colors and formatting
  21. type TermColors struct{}
  22. // LogEvent is a type made by the default text handler for feeding to log
  23. // templates. It has as much contextual data about the log event as possible.
  24. type LogEvent struct {
  25. LoggerName string
  26. Level LogLevel
  27. Message string
  28. Filepath string
  29. Line int
  30. Timestamp time.Time
  31. TermColors
  32. }
  33. // Reset resets the color palette for terminals that support color
  34. func (TermColors) Reset() string { return "\x1b[0m" }
  35. func (TermColors) Bold() string { return "\x1b[1m" }
  36. func (TermColors) Underline() string { return "\x1b[4m" }
  37. func (TermColors) Black() string { return "\x1b[30m" }
  38. func (TermColors) Red() string { return "\x1b[31m" }
  39. func (TermColors) Green() string { return "\x1b[32m" }
  40. func (TermColors) Yellow() string { return "\x1b[33m" }
  41. func (TermColors) Blue() string { return "\x1b[34m" }
  42. func (TermColors) Magenta() string { return "\x1b[35m" }
  43. func (TermColors) Cyan() string { return "\x1b[36m" }
  44. func (TermColors) White() string { return "\x1b[37m" }
  45. func (l *LogEvent) Filename() string {
  46. if l.Filepath == "" {
  47. return ""
  48. }
  49. return filepath.Base(l.Filepath)
  50. }
  51. func (l *LogEvent) Time() string {
  52. return l.Timestamp.Format("15:04:05")
  53. }
  54. func (l *LogEvent) Date() string {
  55. return l.Timestamp.Format("2006/01/02")
  56. }
  57. // LevelJustified returns the log level in string form justified so that all
  58. // log levels take the same text width.
  59. func (l *LogEvent) LevelJustified() (rv string) {
  60. rv = l.Level.String()
  61. if len(rv) < 5 {
  62. rv += strings.Repeat(" ", 5-len(rv))
  63. }
  64. return rv
  65. }