2020-05-25 19:26:40 -04:00
|
|
|
package tea
|
2020-01-25 01:15:56 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2020-05-21 16:56:47 -04:00
|
|
|
"os"
|
2021-02-01 15:19:50 -05:00
|
|
|
"unicode"
|
2020-01-25 01:15:56 -05:00
|
|
|
)
|
|
|
|
|
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.
|
|
|
|
//
|
|
|
|
// f, err := LogToFile("debug.log", "debug")
|
|
|
|
// if err != nil {
|
|
|
|
// fmt.Println("fatal:", err)
|
|
|
|
// os.Exit(1)
|
|
|
|
// }
|
|
|
|
// defer f.Close()
|
|
|
|
func LogToFile(path string, prefix string) (*os.File, error) {
|
|
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
log.SetOutput(f)
|
2021-02-01 15:19:50 -05:00
|
|
|
|
|
|
|
// 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]
|
2021-03-01 18:05:53 -05:00
|
|
|
if !unicode.IsSpace(rune(finalChar)) {
|
2021-02-01 15:19:50 -05:00
|
|
|
prefix += " "
|
|
|
|
}
|
|
|
|
}
|
2020-11-21 19:35:05 -05:00
|
|
|
log.SetPrefix(prefix)
|
2021-02-01 15:19:50 -05:00
|
|
|
|
2020-05-21 16:56:47 -04:00
|
|
|
return f, nil
|
|
|
|
}
|