write log to file when running on windows

This commit is contained in:
Ulric Qin 2022-05-29 20:49:09 +08:00
parent 651d39716f
commit a529c7b1c8
2 changed files with 11 additions and 1 deletions

View File

@ -28,7 +28,7 @@ var (
inputFilters = flag.String("inputs", "", "e.g. cpu:mem:system")
flagWinSvcName = flag.String("win-service-name", "categraf", "Set windows service name")
flagWinSvcDesc = flag.String("win-service-desc", "Categraf is a monitoring agent", "Set windows service description")
flagWinSvcDesc = flag.String("win-service-desc", "Categraf", "Set windows service description")
flagWinSvcInstall = flag.Bool("win-service-install", false, "Install windows service")
flagWinSvcUninstall = flag.Bool("win-service-uninstall", false, "Uninstall windows service")
flagWinSvcStart = flag.Bool("win-service-start", false, "Start windows service")

View File

@ -5,6 +5,7 @@ package main
import (
"log"
"os"
"flashcat.cloud/categraf/agent"
"github.com/chai2010/winsvc"
@ -12,6 +13,15 @@ import (
func runAgent(ag *agent.Agent) {
if !winsvc.IsAnInteractiveSession() {
f, err := os.OpenFile("categraf.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalln("F! failed to open log file: categraf.log")
}
defer f.Close()
log.SetOutput(f)
if err := winsvc.RunAsService(*flagWinSvcName, ag.Start, ag.Stop, false); err != nil {
log.Fatalln("F! failed to run windows service:", err)
}