add basic logging

This commit is contained in:
Nils
2021-12-23 01:35:47 +01:00
parent 99ff702d5d
commit 9af6ed7b41
3 changed files with 50 additions and 4 deletions

35
main.go
View File

@ -1,17 +1,44 @@
package main
import (
"fmt"
"os"
"os/exec"
"log"
"strings"
"net/http"
log "github.com/sirupsen/logrus"
)
func runner(command string, args... string) string{
var logstdout = log.New()
var logfile = log.New()
func init() {
logstdout.SetOutput(os.Stdout)
logstdout.SetLevel(log.WarnLevel)
logpath, err := os.OpenFile("probehost2.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0660)
if err != nil {
logstdout.Fatal("Failed to initialize the logfile: ", err.Error())
}
logfile.SetLevel(log.InfoLevel)
logfile.SetOutput(logpath)
logfile.Info("probehost2 initialized")
}
func runner(remoteip string, command string, args... string) string{
cmd, err := exec.Command(command, args...).Output()
if err != nil {
if ! strings.Contains(err.Error(), "1") { // dont exit if error code is 1
log.Fatal(command, args, "caused an error: ", err)
logstdout.WithFields(log.Fields{
"remote_ip": remoteip,
"command": fmt.Sprint(command, args),
"error": err.Error(),
}).Warn("the following request failed:")
logfile.WithFields(log.Fields{
"remote_ip": remoteip,
"command": fmt.Sprint(command, args),
"error": err.Error(),
}).Warn("the following request failed:")
}
}
return string(cmd)
@ -24,7 +51,7 @@ func showhelp(w http.ResponseWriter, req *http.Request) {
func ping(w http.ResponseWriter, req *http.Request) {
geturl := strings.Split(req.URL.String(), "/")
target := geturl[2]
pingres := runner("ping", "-c5", target)
pingres := runner(req.RemoteAddr, "ping", "-c5", target)
fmt.Fprintln(w, pingres)
}