You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.8 KiB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package log
  5. import (
  6. "encoding/json"
  7. "log"
  8. "os"
  9. "runtime"
  10. )
  11. // Brush brush type
  12. type Brush func(string) string
  13. // NewBrush create a brush according color
  14. func NewBrush(color string) Brush {
  15. pre := "\033["
  16. reset := "\033[0m"
  17. return func(text string) string {
  18. return pre + color + "m" + text + reset
  19. }
  20. }
  21. var colors = []Brush{
  22. NewBrush("1;36"), // Trace cyan
  23. NewBrush("1;34"), // Debug blue
  24. NewBrush("1;32"), // Info green
  25. NewBrush("1;33"), // Warn yellow
  26. NewBrush("1;31"), // Error red
  27. NewBrush("1;35"), // Critical purple
  28. NewBrush("1;31"), // Fatal red
  29. }
  30. // ConsoleWriter implements LoggerInterface and writes messages to terminal.
  31. type ConsoleWriter struct {
  32. lg *log.Logger
  33. Level int `json:"level"`
  34. }
  35. // NewConsole create ConsoleWriter returning as LoggerInterface.
  36. func NewConsole() LoggerInterface {
  37. return &ConsoleWriter{
  38. lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
  39. Level: TRACE,
  40. }
  41. }
  42. // Init inits connection writer with json config.
  43. // json config only need key "level".
  44. func (cw *ConsoleWriter) Init(config string) error {
  45. return json.Unmarshal([]byte(config), cw)
  46. }
  47. // WriteMsg writes message in console.
  48. // if OS is windows, ignore colors.
  49. func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
  50. if cw.Level > level {
  51. return nil
  52. }
  53. if runtime.GOOS == "windows" {
  54. cw.lg.Println(msg)
  55. } else {
  56. cw.lg.Println(colors[level](msg))
  57. }
  58. return nil
  59. }
  60. // Flush when log should be flushed
  61. func (cw *ConsoleWriter) Flush() {
  62. }
  63. // Destroy when writer is destroy
  64. func (cw *ConsoleWriter) Destroy() {
  65. }
  66. func init() {
  67. Register("console", NewConsole)
  68. }