2021-06-11 20:56:53 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"regexp"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/hrfee/jfa-go/linecache"
|
|
|
|
)
|
|
|
|
|
|
|
|
var logPath string = filepath.Join(temp, "jfa-go.log")
|
|
|
|
var lineCache = linecache.NewLineCache(100)
|
|
|
|
|
2023-06-11 14:48:27 +00:00
|
|
|
var stderr = os.Stderr
|
|
|
|
|
2021-12-20 19:05:18 +00:00
|
|
|
func logOutput() (closeFunc func(), err error) {
|
2021-06-11 20:56:53 +00:00
|
|
|
old := os.Stdout
|
|
|
|
writers := []io.Writer{old, colorStripper{lineCache}}
|
|
|
|
wExit := make(chan bool)
|
|
|
|
r, w, _ := os.Pipe()
|
2021-12-20 19:05:18 +00:00
|
|
|
var f *os.File
|
2021-06-11 20:56:53 +00:00
|
|
|
if TRAY {
|
2021-06-24 01:22:44 +00:00
|
|
|
log.Printf("Logging to \"%s\"", logPath)
|
2021-12-20 19:05:18 +00:00
|
|
|
f, err = os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
|
2021-06-11 20:56:53 +00:00
|
|
|
if err != nil {
|
|
|
|
closeFunc = func() {}
|
|
|
|
return
|
|
|
|
}
|
2023-02-02 13:42:15 +00:00
|
|
|
if PLATFORM == "windows" {
|
|
|
|
writers = []io.Writer{colorStripper{lineCache}, colorStripper{f}}
|
|
|
|
} else {
|
|
|
|
writers = append(writers, colorStripper{f})
|
|
|
|
}
|
2021-06-11 20:56:53 +00:00
|
|
|
closeFunc = func() {
|
|
|
|
w.Close()
|
|
|
|
<-wExit
|
|
|
|
f.Close()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
closeFunc = func() {
|
|
|
|
w.Close()
|
|
|
|
<-wExit
|
|
|
|
}
|
|
|
|
}
|
|
|
|
writer := io.MultiWriter(writers...)
|
2021-09-18 12:43:11 +00:00
|
|
|
// FIXME: Potential cause if last log line doesn't get printed sometimes.
|
2021-06-11 20:56:53 +00:00
|
|
|
os.Stdout, os.Stderr = w, w
|
|
|
|
log.SetOutput(writer)
|
|
|
|
gin.DefaultWriter, gin.DefaultErrorWriter = writer, writer
|
|
|
|
go func() {
|
|
|
|
io.Copy(writer, r)
|
|
|
|
wExit <- true
|
|
|
|
}()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Regex that removes ANSI color escape sequences. Used for outputting to log file and log cache.
|
|
|
|
var stripColors = func() *regexp.Regexp {
|
|
|
|
r, err := regexp.Compile("\\x1b\\[[0-9;]*m")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to compile color escape regexp: %v", err)
|
|
|
|
}
|
|
|
|
return r
|
|
|
|
}()
|
|
|
|
|
|
|
|
type colorStripper struct {
|
|
|
|
file io.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c colorStripper) Write(p []byte) (n int, err error) {
|
|
|
|
_, err = c.file.Write(stripColors.ReplaceAll(p, []byte("")))
|
|
|
|
n = len(p)
|
|
|
|
return
|
|
|
|
}
|
2021-06-11 22:14:16 +00:00
|
|
|
|
|
|
|
func sanitizeLog(l string) string {
|
|
|
|
quoteCensor, err := regexp.Compile("\"([^\"]*)\"")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to compile sanitizing regexp: %v", err)
|
|
|
|
}
|
|
|
|
return string(quoteCensor.ReplaceAll([]byte(l), []byte("\"CENSORED\"")))
|
|
|
|
}
|