bubbletea/logging.go

54 lines
1.4 KiB
Go
Raw Permalink Normal View History

package tea
import (
2023-07-07 11:35:32 -04:00
"fmt"
"io"
"log"
2020-05-21 16:56:47 -04:00
"os"
"unicode"
)
2020-07-29 20:49:20 -04:00
// LogToFile sets up default logging to log to a file. This is helpful as we
2020-05-21 16:56:47 -04:00
// can't print to the terminal since our TUI is occupying it. If the file
// doesn't exist it will be created.
//
// Don't forget to close the file when you're done with it.
//
2022-08-15 05:58:40 -04:00
// f, err := LogToFile("debug.log", "debug")
// if err != nil {
// fmt.Println("fatal:", err)
// os.Exit(1)
// }
// defer f.Close()
2020-05-21 16:56:47 -04:00
func LogToFile(path string, prefix string) (*os.File, error) {
return LogToFileWith(path, prefix, log.Default())
}
// LogOptionsSetter is an interface implemented by stdlib's log and charm's log
// libraries.
type LogOptionsSetter interface {
SetOutput(io.Writer)
SetPrefix(string)
}
// LogToFileWith does allows to call LogToFile with a custom LogOptionsSetter.
func LogToFileWith(path string, prefix string, log LogOptionsSetter) (*os.File, error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) //nolint:gomnd
2020-05-21 16:56:47 -04:00
if err != nil {
2023-07-07 11:35:32 -04:00
return nil, fmt.Errorf("error opening file for logging: %w", err)
2020-05-21 16:56:47 -04:00
}
log.SetOutput(f)
// Add a space after the prefix if a prefix is being specified and it
// doesn't already have a trailing space.
if len(prefix) > 0 {
finalChar := prefix[len(prefix)-1]
if !unicode.IsSpace(rune(finalChar)) {
prefix += " "
}
}
2020-11-21 19:35:05 -05:00
log.SetPrefix(prefix)
2020-05-21 16:56:47 -04:00
return f, nil
}