gitee.com/mirrors/gauge@v1.0.6/logger/logWriter.go (about) 1 // Copyright 2019 ThoughtWorks, Inc. 2 3 // This file is part of Gauge. 4 5 // Gauge is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 10 // Gauge is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 15 // You should have received a copy of the GNU General Public License 16 // along with Gauge. If not, see <http://www.gnu.org/licenses/>. 17 18 package logger 19 20 import ( 21 "encoding/json" 22 "fmt" 23 "io" 24 "os" 25 "strings" 26 ) 27 28 // Writer reperesnts to a custom writer. 29 // It intercents the log messages and redirects them to logger according the log level given in info 30 type Writer struct { 31 loggerID string 32 ShouldWriteToStdout bool 33 stream int 34 File io.Writer 35 } 36 37 // LogInfo repesents the log message structure for plugins 38 type LogInfo struct { 39 LogLevel string `json:"logLevel"` 40 Message string `json:"message"` 41 } 42 43 func (w Writer) Write(p []byte) (int, error) { 44 logEntry := string(p) 45 logEntries := strings.Split(logEntry, "\n") 46 for _, _logEntry := range logEntries { 47 _logEntry = strings.Trim(_logEntry, " ") 48 if len(_logEntry) == 0 { 49 continue 50 } 51 _p := []byte(_logEntry) 52 m := &LogInfo{} 53 err := json.Unmarshal(_p, m) 54 if err != nil { 55 fmt.Fprintln(w.File, string(_p)) 56 } 57 if w.stream > 0 { 58 m.Message = fmt.Sprintf("[runner: %d] %s", w.stream, m.Message) 59 } 60 switch m.LogLevel { 61 case "debug": 62 logDebug(GetLogger(w.loggerID), w.ShouldWriteToStdout, m.Message) 63 case "info": 64 logInfo(GetLogger(w.loggerID), w.ShouldWriteToStdout, m.Message) 65 case "error": 66 logError(GetLogger(w.loggerID), w.ShouldWriteToStdout, m.Message) 67 case "warning": 68 logWarning(GetLogger(w.loggerID), w.ShouldWriteToStdout, m.Message) 69 case "fatal": 70 logCritical(GetLogger(w.loggerID), m.Message) 71 addFatalError(w.loggerID, m.Message) 72 } 73 } 74 return len(p), nil 75 } 76 77 // LogWriter reperesents the type which consists of two custom writers 78 type LogWriter struct { 79 Stderr io.Writer 80 Stdout io.Writer 81 } 82 83 // NewLogWriter creates a new logWriter for given id 84 func NewLogWriter(loggerID string, stdout bool, stream int) *LogWriter { 85 return &LogWriter{ 86 Stderr: Writer{ShouldWriteToStdout: stdout, stream: stream, loggerID: loggerID, File: os.Stderr}, 87 Stdout: Writer{ShouldWriteToStdout: stdout, stream: stream, loggerID: loggerID, File: os.Stdout}, 88 } 89 }