github.com/neohugo/neohugo@v0.123.8/common/loggers/handlerterminal.go (about) 1 // Copyright 2024 The Hugo Authors. All rights reserved. 2 // Some functions in this file (see comments) is based on the Go source code, 3 // copyright The Go Authors and governed by a BSD-style license. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 package loggers 17 18 import ( 19 "fmt" 20 "io" 21 "strings" 22 "sync" 23 24 "github.com/bep/logg" 25 ) 26 27 // newNoColoursHandler creates a new NoColoursHandler 28 func newNoColoursHandler(outWriter, errWriter io.Writer, noLevelPrefix bool, predicate func(*logg.Entry) bool) *noColoursHandler { 29 if predicate == nil { 30 predicate = func(e *logg.Entry) bool { return true } 31 } 32 return &noColoursHandler{ 33 noLevelPrefix: noLevelPrefix, 34 outWriter: outWriter, 35 errWriter: errWriter, 36 predicate: predicate, 37 } 38 } 39 40 type noColoursHandler struct { 41 mu sync.Mutex 42 outWriter io.Writer // Defaults to os.Stdout. 43 errWriter io.Writer // Defaults to os.Stderr. 44 predicate func(*logg.Entry) bool 45 noLevelPrefix bool 46 } 47 48 func (h *noColoursHandler) HandleLog(e *logg.Entry) error { 49 if !h.predicate(e) { 50 return nil 51 } 52 h.mu.Lock() 53 defer h.mu.Unlock() 54 55 var w io.Writer 56 if e.Level > logg.LevelInfo { 57 w = h.errWriter 58 } else { 59 w = h.outWriter 60 } 61 62 var prefix string 63 for _, field := range e.Fields { 64 if field.Name == FieldNameCmd { 65 prefix = fmt.Sprint(field.Value) 66 break 67 } 68 } 69 70 if prefix != "" { 71 prefix = prefix + ": " 72 } 73 74 if h.noLevelPrefix { 75 fmt.Fprintf(w, "%s%s", prefix, e.Message) 76 } else { 77 fmt.Fprintf(w, "%s %s%s", levelString[e.Level], prefix, e.Message) 78 } 79 80 for _, field := range e.Fields { 81 if strings.HasPrefix(field.Name, reservedFieldNamePrefix) { 82 continue 83 } 84 fmt.Fprintf(w, " %s %v", field.Name, field.Value) 85 86 } 87 fmt.Fprintln(w) 88 89 return nil 90 }