cmdlogger: initial commit

This commit is contained in:
Mikaël Cluseau
2024-01-20 13:24:14 +01:00
parent 354bdce5ab
commit 1a84bb4286
5 changed files with 76 additions and 31 deletions

View File

@ -3,12 +3,13 @@ package initservices
import (
"log"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/spf13/cobra"
plog "novit.nc/direktil/pkg/log"
cmdlogger "novit.nc/direktil/inits/pkg/cmd/logger"
)
var (
@ -58,18 +59,13 @@ func run(c *cobra.Command, args []string) {
func runService(svcPath string) {
svc := filepath.Base(svcPath)
logger := plog.Get(svc)
plog.EnableFiles()
n := 0
for {
lastStart := time.Now()
cmd := exec.Command(svcPath)
cmd.Stdout = logger
cmd.Stderr = logger
err := cmd.Run()
err := cmdlogger.Run("", svcPath)
if time.Since(lastStart) > crashForgiveDelay {
n = 0

49
pkg/cmd/logger/logger.go Normal file
View File

@ -0,0 +1,49 @@
package cmdlogger
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/spf13/cobra"
plog "novit.nc/direktil/pkg/log"
)
func Command() (c *cobra.Command) {
c = &cobra.Command{
Use: "logger [--] <command> [args]",
Short: "run a command through the dkl logger",
Args: cobra.MinimumNArgs(1),
Run: run,
}
c.Flags().StringP("name", "n", "", "log name")
return
}
func run(c *cobra.Command, args []string) {
logName, _ := c.Flags().GetString("name")
err := Run(logName, args[0], args[1:]...)
if err == nil {
os.Exit(0)
} else if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
} else {
fmt.Fprintln(os.Stderr, "failed to run command: "+err.Error())
os.Exit(1)
}
}
func Run(logName, command string, args ...string) (err error) {
if logName == "" {
logName = filepath.Base(command)
}
logger := plog.Get(logName)
plog.EnableFiles()
cmd := exec.Command(command, args...)
cmd.Stdout = logger
cmd.Stderr = logger
return cmd.Run()
}