Debian Codegraph @

common/loggers/handlerterminal.go

raw
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 "regexp"
22 "strings"
23 "sync"
24
25 "github.com/bep/logg"
26 )
27
28 // newNoAnsiEscapeHandler creates a new noAnsiEscapeHandler
29 func newNoAnsiEscapeHandler(outWriter, errWriter io.Writer, noLevelPrefix bool, predicate func(*logg.Entry) bool) *noAnsiEscapeHandler {
30 if predicate == nil {
31 predicate = func(e *logg.Entry) bool { return true }
32 }
33 return &noAnsiEscapeHandler{
34 noLevelPrefix: noLevelPrefix,
35 outWriter: outWriter,
36 errWriter: errWriter,
37 predicate: predicate,
38 }
39 }
40
41 type noAnsiEscapeHandler struct {
42 mu sync.Mutex
43 outWriter io.Writer
44 errWriter io.Writer
45 predicate func(*logg.Entry) bool
46 noLevelPrefix bool
47 }
48
49 func (h *noAnsiEscapeHandler) HandleLog(e *logg.Entry) error {
50 if !h.predicate(e) {
51 return nil
52 }
53 h.mu.Lock()
54 defer h.mu.Unlock()
55
56 var w io.Writer
57 if e.Level > logg.LevelInfo {
58 w = h.errWriter
59 } else {
60 w = h.outWriter
61 }
62
63 var prefix string
64 for _, field := range e.Fields {
65 if field.Name == FieldNameCmd {
66 prefix = fmt.Sprint(field.Value)
67 break
68 }
69 }
70
71 if prefix != "" {
72 prefix = prefix + ": "
73 }
74
75 msg := stripANSI(e.Message)
76
77 if h.noLevelPrefix {
78 fmt.Fprintf(w, "%s%s", prefix, msg)
79 } else {
80 fmt.Fprintf(w, "%s %s%s", levelString[e.Level], prefix, msg)
81 }
82
83 for _, field := range e.Fields {
84 if strings.HasPrefix(field.Name, reservedFieldNamePrefix) {
85 continue
86 }
87 fmt.Fprintf(w, " %s %v", field.Name, field.Value)
88
89 }
90 fmt.Fprintln(w)
91
92 return nil
93 }
94
95 var ansiRe = regexp.MustCompile(`\x1b\[[0-9;]*m`)
96
97 // stripANSI removes ANSI escape codes from s.
98 func stripANSI(s string) string {
99 return ansiRe.ReplaceAllString(s, "")
100 }