inits/pkg/cmd/logger/logger.go

50 lines
1002 B
Go
Raw Normal View History

2024-01-20 12:24:14 +00:00
package cmdlogger
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/spf13/cobra"
2024-01-20 13:20:51 +00:00
plog "novit.tech/direktil/pkg/log"
2024-01-20 12:24:14 +00:00
)
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()
}