console.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2014 beego Author. All Rights Reserved.
  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 logs
  15. import (
  16. "encoding/json"
  17. "log"
  18. "os"
  19. "runtime"
  20. )
  21. type Brush func(string) string
  22. func NewBrush(color string) Brush {
  23. pre := "\033["
  24. reset := "\033[0m"
  25. return func(text string) string {
  26. return pre + color + "m" + text + reset
  27. }
  28. }
  29. var colors = []Brush{
  30. NewBrush("1;37"), // Emergency white
  31. NewBrush("1;36"), // Alert cyan
  32. NewBrush("1;35"), // Critical magenta
  33. NewBrush("1;31"), // Error red
  34. NewBrush("1;33"), // Warning yellow
  35. NewBrush("1;32"), // Notice green
  36. NewBrush("1;34"), // Informational blue
  37. NewBrush("1;34"), // Debug blue
  38. }
  39. // ConsoleWriter implements LoggerInterface and writes messages to terminal.
  40. type ConsoleWriter struct {
  41. lg *log.Logger
  42. Level int `json:"level"`
  43. }
  44. // create ConsoleWriter returning as LoggerInterface.
  45. func NewConsole() LoggerInterface {
  46. cw := &ConsoleWriter{
  47. lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
  48. Level: LevelDebug,
  49. }
  50. return cw
  51. }
  52. // init console logger.
  53. // jsonconfig like '{"level":LevelTrace}'.
  54. func (c *ConsoleWriter) Init(jsonconfig string) error {
  55. if len(jsonconfig) == 0 {
  56. return nil
  57. }
  58. return json.Unmarshal([]byte(jsonconfig), c)
  59. }
  60. // write message in console.
  61. func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
  62. if level > c.Level {
  63. return nil
  64. }
  65. if goos := runtime.GOOS; goos == "windows" {
  66. c.lg.Println(msg)
  67. return nil
  68. }
  69. c.lg.Println(colors[level](msg))
  70. return nil
  71. }
  72. // implementing method. empty.
  73. func (c *ConsoleWriter) Destroy() {
  74. }
  75. // implementing method. empty.
  76. func (c *ConsoleWriter) Flush() {
  77. }
  78. func init() {
  79. Register("console", NewConsole)
  80. }