1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-04 10:34:55 +02:00
lazygit/pkg/logs/tail/logs_windows.go
Jesse Duffield e0ecc9e835 Allow global logging when developing
I'll be honest, for all I know logging should be global in general: it is
a pain to pass a logger to any struct that needs it. But smart people on the
internet tell me otherwise, and I do like the idea of not having any global
variables lying around.

Nonetheless, I often need to log things when locally debugging and that's a
different kind of logging than the kind you would include in the actual
released binary. For example if I want to log something from gocui, I would
rather not have gocui depend on lazygit's logging setup.
2023-05-25 18:31:32 +10:00

74 lines
1.4 KiB
Go

//go:build windows
// +build windows
package tail
import (
"bufio"
"log"
"os"
"strings"
"time"
"github.com/aybabtme/humanlog"
)
func tailLogsForPlatform(logFilePath string, opts *humanlog.HandlerOptions) {
var lastModified int64 = 0
var lastOffset int64 = 0
for {
stat, err := os.Stat(logFilePath)
if err != nil {
log.Fatal(err)
}
if stat.ModTime().Unix() > lastModified {
err = tailFrom(lastOffset, logFilePath, opts)
if err != nil {
log.Fatal(err)
}
}
lastOffset = stat.Size()
time.Sleep(1 * time.Second)
}
}
func openAndSeek(filepath string, offset int64) (*os.File, error) {
file, err := os.Open(filepath)
if err != nil {
return nil, err
}
_, err = file.Seek(offset, 0)
if err != nil {
_ = file.Close()
return nil, err
}
return file, nil
}
func tailFrom(lastOffset int64, logFilePath string, opts *humanlog.HandlerOptions) error {
file, err := openAndSeek(logFilePath, lastOffset)
if err != nil {
return err
}
fileScanner := bufio.NewScanner(file)
var lines []string
for fileScanner.Scan() {
lines = append(lines, fileScanner.Text())
}
file.Close()
lineCount := len(lines)
lastTen := lines
if lineCount > 10 {
lastTen = lines[lineCount-10:]
}
for _, line := range lastTen {
reader := strings.NewReader(line)
if err := humanlog.Scanner(reader, os.Stdout, opts); err != nil {
log.Fatal(err)
}
}
return nil
}