feat(log): Formatted console logging with file output
This commit is contained in:
84
writer.go
Normal file
84
writer.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package masterlog
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// isTerminal checks if the writer is a terminal (TTY)
|
||||
func isTerminal(w io.Writer) bool {
|
||||
file, ok := w.(*os.File)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if it's a terminal by trying to get file info
|
||||
stat, err := file.Stat()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if it's a character device (terminal)
|
||||
return (stat.Mode() & os.ModeCharDevice) != 0
|
||||
}
|
||||
|
||||
// ConsoleWriter writes to stdout
|
||||
type ConsoleWriter struct {
|
||||
writer io.Writer
|
||||
isTerminal bool
|
||||
}
|
||||
|
||||
func NewConsoleWriter() *ConsoleWriter {
|
||||
writer := os.Stdout
|
||||
return &ConsoleWriter{
|
||||
writer: writer,
|
||||
isTerminal: isTerminal(writer),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *ConsoleWriter) Write(data []byte) error {
|
||||
_, err := w.writer.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *ConsoleWriter) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *ConsoleWriter) SupportsColors() bool {
|
||||
return w.isTerminal
|
||||
}
|
||||
|
||||
// FileWriter writes to a file
|
||||
type FileWriter struct {
|
||||
file *os.File
|
||||
writer io.Writer
|
||||
}
|
||||
|
||||
func NewFileWriter(filename string) (*FileWriter, error) {
|
||||
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FileWriter{
|
||||
file: file,
|
||||
writer: file,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (w *FileWriter) Write(data []byte) error {
|
||||
_, err := w.writer.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func (w *FileWriter) Close() error {
|
||||
if w.file != nil {
|
||||
return w.file.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *FileWriter) SupportsColors() bool {
|
||||
return false // File writers never support colors
|
||||
}
|
||||
Reference in New Issue
Block a user