-
Notifications
You must be signed in to change notification settings - Fork 713
Description
Hi there. im making a Application which is running as a Windows Serivce.
The Application working fine on development, but when i try to run it as install and start running as a Windows Serivce,
The Application cannot write log file.
Env:
Window server 2016
Golang version lastest
gopkg.in/natefinch/lumberjack.v2 v2.2.1
github.com/kardianos/service v1.2.2
Steps:
run build with command: GOOS=windows GOARCH=amd64 CGO_ENABLED=1 go build -ldflags="-w -s"
run install service with cmd: E:\GoLang\Project\TestApp.exe install
run start service with cmd: E:\GoLang\Project\TestApp.exe start => Error: Failed to start iLotusLand-Watchman-Go-v2: An instance of the service is already running
The service is running now, can see it in Services, and TaskManager
and The service Log on as Local system account

If i run it by just double click on .exe file, the log file are writing normally
but no output logfile when the it running as a Windows service
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/kardianos/service"
"gopkg.in/natefinch/lumberjack.v2"
)
type program struct{}
var logger service.Logger
func (p *program) Start(s service.Service) error {
go p.run()
return nil
}
func (p *program) run() {
if err != nil {
fmt.Println("Error:", err)
fmt.Println("Press any key to exit...")
fmt.Scanln()
os.Exit(0)
return
}
SetupLog()
log.Println("===========TEST LOG=========") // write into txt log file
log.Println("===========TEST LOG=========")
log.Println("===========TEST LOG=========")
log.Println("===========TEST LOG=========")
}
func (p *program) Stop(s service.Service) error {
return nil
}
func SetupLog() {
LOG_FOLDER := "E:\\LOG_FOLDER"
fileName := "file-log" + time.Time.Format(time.Now(), "-2006-01-02") + ".txt"
filePath := filepath.Join(LOG_FOLDER, fileName)
// E:\\LOG_FOLDER\\file-log-2024-09-25.txt
lumberjackLogger := &lumberjack.Logger{
Filename: filepath.ToSlash(filePath),
MaxSize: 2,
MaxBackups: 10000,
MaxAge: 30,
Compress: false,
}
multiWriter := io.MultiWriter(os.Stderr, lumberjackLogger)
log.SetOutput(multiWriter)
}
func main() {
svcConfig := &service.Config{
Name: "ServiceName",
DisplayName: "ServiceName",
Description: "ServiceName",
}
prg := &program{}
s, errS := service.New(prg, svcConfig)
if errS != nil {
log.Fatal(errS)
}
service.Control(s, "start")
if len(os.Args) > 1 {
errS := service.Control(s, os.Args[1])
if errS != nil {
fmt.Println("Error:", errS)
os.Exit(1)
}
os.Exit(0)
}
errS = s.Run()
if errS != nil {
log.Println(errS)
}
}