Skip to content

Commit

Permalink
feat: add better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
BrunnerLivio committed Oct 2, 2023
1 parent 1cd5598 commit 9ae2b44
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 52 deletions.
5 changes: 2 additions & 3 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
userconf "tsp-web/internal/user-conf"

"github.com/olahol/melody"
log "github.com/sirupsen/logrus"
)

var allowOriginFunc = func(r *http.Request) bool {
Expand All @@ -28,7 +29,6 @@ func Run(args args.TspWebArgs) error {
fileMatcher := regexp.MustCompile(`\.[a-zA-Z]*$`)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if !fileMatcher.MatchString(r.URL.Path) {
// http.ServeFile(w, r, "web/index.html")
var index, _ = Static.ReadFile("web/index.html")
w.Write(index)
} else {
Expand All @@ -43,7 +43,6 @@ func Run(args args.TspWebArgs) error {
})

m.HandleMessage(func(s *melody.Session, msg []byte) {
fmt.Printf("got message: %s\n", msg)
message := string(msg)
messageSplit := strings.Split(message, ":")
command := messageSplit[0]
Expand All @@ -64,7 +63,7 @@ func Run(args args.TspWebArgs) error {
CommandController(args)
}

fmt.Printf("Running server on http://0.0.0.0:%d\n", args.Port)
log.Info("Running server on http://0.0.0.0:", args.Port)

return http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", args.Port), nil)
}
5 changes: 3 additions & 2 deletions api/commandController.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package api

import (
"encoding/json"
"fmt"
"net/http"
"tsp-web/internal/args"
userconf "tsp-web/internal/user-conf"

log "github.com/sirupsen/logrus"
)

func CommandController(args args.TspWebArgs) {
Expand All @@ -24,7 +25,7 @@ func GetCommands(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
res, err := json.Marshal(commands)

if err != nil {
fmt.Printf("Error could not get commands: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand Down
11 changes: 6 additions & 5 deletions api/labelController.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package api

import (
"encoding/json"
"fmt"
"net/http"
"tsp-web/internal/args"
userconf "tsp-web/internal/user-conf"

log "github.com/sirupsen/logrus"
)

func LabelController(args args.TspWebArgs) {
Expand All @@ -29,7 +30,7 @@ func GetLabels(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
labels, err := userconf.GetLabels(args)
res, err := json.Marshal(labels)
if err != nil {
fmt.Printf("Error creating label: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -45,7 +46,7 @@ func PostLabel(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
res, err := json.Marshal(conf.Labels)

if err != nil {
fmt.Printf("Error creating label: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -61,7 +62,7 @@ func PutLabel(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
res, err := json.Marshal(conf.Labels)

if err != nil {
fmt.Printf("Error updating label: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -77,7 +78,7 @@ func DeleteLabel(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
res, err := json.Marshal(conf.Labels)

if err != nil {
fmt.Printf("Error removing label: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand Down
13 changes: 7 additions & 6 deletions api/taskSpoolerController.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package api

import (
"encoding/json"
"fmt"
"net/http"
"os/exec"
"tsp-web/internal/args"
taskspooler "tsp-web/internal/task-spooler"
userconf "tsp-web/internal/user-conf"

log "github.com/sirupsen/logrus"
)

var cachedTasks []taskspooler.Task
Expand Down Expand Up @@ -83,7 +84,7 @@ func GetList(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {

res, err := json.Marshal(currentTasks)
if err != nil {
fmt.Printf("error marshalling tasks: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -99,7 +100,7 @@ func PostExec(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
var command ExecArg
err := json.NewDecoder(r.Body).Decode(&command)
if err != nil {
fmt.Printf("Error decoding command: %s\n", err)
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand All @@ -115,16 +116,16 @@ func PostExec(args args.TspWebArgs, w http.ResponseWriter, r *http.Request) {
}

if foundCommand == nil {
fmt.Printf("Command not found: %s\n", command.Name)
log.Error("Command not found: ", command.Name)
w.WriteHeader(http.StatusNotFound)
return
}

fmt.Println("Executing command from user request with args: ", args.TsBin, foundCommand.Args)
log.Info("Executing command from user request with args: ", args.TsBin, foundCommand.Args)
cmd := exec.Command(args.TsBin, foundCommand.Args...)
out, err := cmd.Output()
if err != nil {
fmt.Printf("Error executing command: %s\n", err)
log.Error("Error executing command: ", err)
w.WriteHeader(http.StatusInternalServerError)
}

Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/olahol/melody v1.1.4 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
golang.org/x/sys v0.0.0-20220908164124-27713097b956 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,17 @@ github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad
github.com/olahol/melody v1.1.4 h1:RQHfKZkQmDxI0+SLZRNBCn4LiXdqxLKRGSkT8Dyoe/E=
github.com/olahol/melody v1.1.4/go.mod h1:GgkTl6Y7yWj/HtfD48Q5vLKPVoZOH+Qqgfa7CvJgJM4=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956 h1:XeJjHH1KiLpKGb6lvMiksZ9l0fVUh+AmGcm0nOMEBOY=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 changes: 2 additions & 0 deletions internal/args/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ type TspWebArgs struct {
TsBin string
Port uint16
ConfigPath string
LogLevel string
NoColor bool
}
44 changes: 13 additions & 31 deletions internal/user-conf/user-conf.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package userconf

import (
"log"
"os"
"path/filepath"
utils "tsp-web/internal"
"tsp-web/internal/args"

log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -43,9 +43,9 @@ type UserConf struct {
var cachedConf UserConf = UserConf{}

func StartWatcher(args args.TspWebArgs) {
log.Default().Println("Starting user conf watcher")
log.Debug("Starting user conf watcher")
utils.FileWatcher(func() {
log.Default().Println("Reloading user conf")
log.Info("User conf changed, reloading...")
Load(args)
}, getConfPath(args))
}
Expand All @@ -55,23 +55,18 @@ func GetUserConf(args args.TspWebArgs) UserConf {
}

func Load(args args.TspWebArgs) {
conf, err := load(args)
if err != nil {
log.Println(err)
} else {
cachedConf = conf
}
cachedConf = load(args)
}

func load(args args.TspWebArgs) (UserConf, error) {
func load(args args.TspWebArgs) UserConf {
conf := UserConf{}
confPath := getConfPath(args)
ensureConfExists(confPath)

f, err := os.Open(confPath)
if err != nil {
log.Println(err)
return UserConf{}, err
log.Error(confPath, ": ", err)
return UserConf{}
}

decoder := yaml.NewDecoder(f)
Expand All @@ -80,11 +75,11 @@ func load(args args.TspWebArgs) (UserConf, error) {
defer f.Close()

if err != nil {
log.Println(err)
return UserConf{}, err
log.Error(confPath, ": ", err)
return UserConf{}
}

return conf, nil
return conf
}

func writeUserConf(args args.TspWebArgs, conf UserConf) (UserConf, error) {
Expand All @@ -93,7 +88,6 @@ func writeUserConf(args args.TspWebArgs, conf UserConf) (UserConf, error) {

f, err := os.OpenFile(confPath, os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return UserConf{}, err
}

Expand All @@ -103,7 +97,6 @@ func writeUserConf(args args.TspWebArgs, conf UserConf) (UserConf, error) {
err = encoder.Encode(conf)

if err != nil {
log.Println(err)
return UserConf{}, err
}

Expand All @@ -113,7 +106,7 @@ func writeUserConf(args args.TspWebArgs, conf UserConf) (UserConf, error) {
func getConfPath(args args.TspWebArgs) string {
home, err := os.UserHomeDir()
if err != nil {
log.Println(err)
log.Error(err)
return ""
}

Expand All @@ -124,22 +117,11 @@ func ensureConfExists(confPath string) error {
_, err := os.Stat(confPath)
if os.IsNotExist(err) {
err = os.MkdirAll(filepath.Dir(confPath), 0755)
if err != nil {
log.Println(err)
return err
}

f, err := os.Create(confPath)
if err != nil {
log.Println(err)
return err
}

defer f.Close()

_, err = f.WriteString(initialConf)

if err != nil {
log.Println(err)
log.Error(err)
return err
}
}
Expand Down
31 changes: 26 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"tsp-web/api"
"tsp-web/internal/args"
userconf "tsp-web/internal/user-conf"

log "github.com/sirupsen/logrus"
)

//go:embed web/*
Expand All @@ -28,6 +30,8 @@ const maxPort uint64 = 65535
func parseArgs() (args.TspWebArgs, error) {
TsBin := flag.String("ts-bin", getenv("TSP_WEB_TS_BIN", "tsp"), "The binary for tsp")
portArg := flag.Uint64("port", 3000, "The port for tsp-web")
logLevel := flag.String("log-level", getenv("TSP_WEB_LOG_LEVEL", "info"), "The log level for tsp-web")
noColor := flag.Bool("no-color", false, "Disable colorized output")

flag.Parse()

Expand All @@ -37,16 +41,34 @@ func parseArgs() (args.TspWebArgs, error) {

Port := uint16(*portArg)

return args.TspWebArgs{TsBin: *TsBin, Port: Port}, nil
return args.TspWebArgs{TsBin: *TsBin, Port: Port, LogLevel: *logLevel, NoColor: *noColor}, nil
}

func setLogLevel(logLevel string) {
switch logLevel {
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "warn":
log.SetLevel(log.WarnLevel)
default:
log.SetLevel(log.InfoLevel)
}
}

func main() {
api.Static = static

args, err := parseArgs()
setLogLevel(args.LogLevel)
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
DisableColors: args.NoColor,
})

if err != nil {
fmt.Printf("%s\n", err)
log.Error(err)
flag.Usage()
os.Exit(1)
}
Expand All @@ -56,10 +78,9 @@ func main() {
err = api.Run(args)

if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
log.Info("server closed")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
log.Fatal("error starting server: ", err)
}
os.Exit(0)
}

0 comments on commit 9ae2b44

Please sign in to comment.