Archived
2
0
This repository has been archived on 2024-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
neko-custom/server/internal/preflight/logs.go

61 lines
1.3 KiB
Go
Raw Normal View History

2020-01-13 21:05:38 +13:00
package preflight
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/diode"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
func Logs(name string) {
zerolog.TimeFieldFormat = ""
zerolog.SetGlobalLevel(zerolog.InfoLevel)
2020-01-14 12:12:55 +13:00
if viper.GetBool("debug") {
2020-01-13 21:05:38 +13:00
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
console := zerolog.ConsoleWriter{Out: os.Stdout}
2020-01-14 12:12:55 +13:00
if !viper.GetBool("logs") {
2020-01-13 21:05:38 +13:00
log.Logger = log.Output(console)
} else {
logs := filepath.Join(".", "logs")
if runtime.GOOS == "linux" {
logs = "/var/log/neko"
}
if _, err := os.Stat(logs); os.IsNotExist(err) {
os.Mkdir(logs, os.ModePerm)
}
latest := filepath.Join(logs, name+"-latest.log")
_, err := os.Stat(latest)
if err == nil {
err = os.Rename(latest, filepath.Join(logs, "neko."+time.Now().Format("2006-01-02T15-04-05Z07-00")+".log"))
if err != nil {
2020-01-19 12:30:09 +13:00
log.Panic().Err(err).Msg("failed to rotate log file")
2020-01-13 21:05:38 +13:00
}
}
logf, err := os.OpenFile(latest, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
2020-01-19 12:30:09 +13:00
log.Panic().Err(err).Msg("failed to create log file")
2020-01-13 21:05:38 +13:00
}
logger := diode.NewWriter(logf, 1000, 10*time.Millisecond, func(missed int) {
2020-01-19 12:30:09 +13:00
fmt.Printf("logger dropped %d messages", missed)
2020-01-13 21:05:38 +13:00
})
log.Logger = log.Output(io.MultiWriter(console, logger))
}
}