github.com/eframework-cn/EP.GO.UTIL@v1.0.0/xlog/console.go (about) 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 15 package xlog 16 17 import ( 18 "encoding/json" 19 "os" 20 "strings" 21 "time" 22 23 "github.com/shiena/ansicolor" 24 ) 25 26 // brush is a color join function 27 type brush func(string) string 28 29 // newBrush return a fix color Brush 30 func newBrush(color string) brush { 31 pre := "\033[" 32 reset := "\033[0m" 33 return func(text string) string { 34 return pre + color + "m" + text + reset 35 } 36 } 37 38 var colors = []brush{ 39 newBrush("1;37"), // Emergency white 40 newBrush("1;36"), // Alert cyan 41 newBrush("1;35"), // Critical magenta 42 newBrush("1;31"), // Error red 43 newBrush("1;33"), // Warning yellow 44 newBrush("1;32"), // Notice green 45 newBrush("1;34"), // Informational blue 46 newBrush("1;44"), // Debug Background blue 47 } 48 49 // consoleWriter implements LoggerInterface and writes messages to terminal. 50 type consoleWriter struct { 51 lg *logWriter 52 Level int `json:"level"` 53 Colorful bool `json:"color"` //this filed is useful only when system's terminal supports color 54 } 55 56 // NewConsole create ConsoleWriter returning as LoggerInterface. 57 func NewConsole() Logger { 58 cw := &consoleWriter{ 59 lg: newLogWriter(ansicolor.NewAnsiColorWriter(os.Stdout)), 60 Level: LevelDebug, 61 Colorful: true, 62 } 63 return cw 64 } 65 66 // Init init console logger. 67 // jsonConfig like '{"level":LevelTrace}'. 68 func (c *consoleWriter) Init(jsonConfig string) error { 69 if len(jsonConfig) == 0 { 70 return nil 71 } 72 return json.Unmarshal([]byte(jsonConfig), c) 73 } 74 75 // WriteMsg write message in console. 76 func (c *consoleWriter) WriteMsg(when time.Time, msg string, level int) error { 77 if level > c.Level { 78 return nil 79 } 80 if c.Colorful { 81 msg = strings.Replace(msg, levelPrefix[level], colors[level](levelPrefix[level]), 1) 82 } 83 c.lg.writeln(when, msg) 84 return nil 85 } 86 87 // Destroy implementing method. empty. 88 func (c *consoleWriter) Destroy() { 89 90 } 91 92 // Flush implementing method. empty. 93 func (c *consoleWriter) Flush() { 94 95 } 96 97 func init() { 98 Register(AdapterConsole, NewConsole) 99 }