github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/console.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 // Copyright 2014 The Gogs Authors. All rights reserved. 7 8 package log 9 10 import ( 11 "fmt" 12 "io" 13 "os" 14 15 "github.com/gitbundle/modules/json" 16 ) 17 18 // CanColorStdout reports if we can color the Stdout 19 // Although we could do terminal sniffing and the like - in reality 20 // most tools on *nix are happy to display ansi colors. 21 // We will terminal sniff on Windows in console_windows.go 22 var CanColorStdout = true 23 24 // CanColorStderr reports if we can color the Stderr 25 var CanColorStderr = true 26 27 type nopWriteCloser struct { 28 w io.WriteCloser 29 } 30 31 func (n *nopWriteCloser) Write(p []byte) (int, error) { 32 return n.w.Write(p) 33 } 34 35 func (n *nopWriteCloser) Close() error { 36 return nil 37 } 38 39 // ConsoleLogger implements LoggerProvider and writes messages to terminal. 40 type ConsoleLogger struct { 41 WriterLogger 42 Stderr bool `json:"stderr"` 43 } 44 45 // NewConsoleLogger create ConsoleLogger returning as LoggerProvider. 46 func NewConsoleLogger() LoggerProvider { 47 log := &ConsoleLogger{} 48 log.NewWriterLogger(&nopWriteCloser{ 49 w: os.Stdout, 50 }) 51 return log 52 } 53 54 // Init inits connection writer with json config. 55 // json config only need key "level". 56 func (log *ConsoleLogger) Init(config string) error { 57 err := json.Unmarshal([]byte(config), log) 58 if err != nil { 59 return fmt.Errorf("Unable to parse JSON: %v", err) 60 } 61 if log.Stderr { 62 log.NewWriterLogger(&nopWriteCloser{ 63 w: os.Stderr, 64 }) 65 } else { 66 log.NewWriterLogger(log.out) 67 } 68 return nil 69 } 70 71 // Content returns the content accumulated in the content provider 72 func (log *ConsoleLogger) Content() (string, error) { 73 return "", fmt.Errorf("not supported") 74 } 75 76 // Flush when log should be flushed 77 func (log *ConsoleLogger) Flush() { 78 } 79 80 // ReleaseReopen causes the console logger to reconnect to os.Stdout 81 func (log *ConsoleLogger) ReleaseReopen() error { 82 if log.Stderr { 83 log.NewWriterLogger(&nopWriteCloser{ 84 w: os.Stderr, 85 }) 86 } else { 87 log.NewWriterLogger(&nopWriteCloser{ 88 w: os.Stdout, 89 }) 90 } 91 return nil 92 } 93 94 // GetName returns the default name for this implementation 95 func (log *ConsoleLogger) GetName() string { 96 return "console" 97 } 98 99 func init() { 100 Register("console", NewConsoleLogger) 101 }