Replace log with logrus for level based logging, add debug flag

This commit is contained in:
2023-12-15 06:40:10 -06:00
parent ca136634c9
commit b5ee5bec0c
7 changed files with 49 additions and 27 deletions

16
api.go
View File

@@ -2,7 +2,6 @@ package main
import (
"bytes"
"log"
"net/http"
"net/http/cookiejar"
"regexp"
@@ -11,6 +10,7 @@ import (
"time"
"github.com/PuerkitoBio/goquery"
log "github.com/sirupsen/logrus"
)
var (
@@ -33,16 +33,12 @@ func init() {
}
func onRequest(req *http.Request) {
log.Printf("GET %s", req.URL.String())
log.Debugf("GET %s", req.URL.String())
requestCounter++
}
func onResponse(res *http.Response) {
log.Printf("%s %d %s", res.Status, res.ContentLength, res.Header["Content-Type"])
}
func buildURL(path string, params map[string]string) string {
return baseURL + path
log.Debugf("%s %d %s", res.Status, res.ContentLength, res.Header["Content-Type"])
}
// Reloads the current session and completes the initial connection process that procedes bot operations.
@@ -72,7 +68,7 @@ func reload(name string) {
if !has_php_session {
log.Fatal("PHPSESSID cookie not found")
} else {
log.Println("PHPSESSID cookie found")
log.Debugf("PHPSESSID cookie found")
}
}
@@ -83,9 +79,9 @@ func tryReload(name string) {
lastReloadDiff := currentTime - lastReload
if requestCounter >= 10 {
log.Println("Reloading session due to request count...")
log.Info("Reloading session due to request count...")
} else if lastReloadDiff >= 15*60 {
log.Println("Reloading session due to time...")
log.Info("Reloading session due to time...")
} else {
return
}

View File

@@ -2,11 +2,11 @@ package main
import (
"fmt"
"log"
"strconv"
"time"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
var CodeCommandDefinition = &discordgo.ApplicationCommand{
@@ -87,7 +87,7 @@ func CodeCommandHandler(session *discordgo.Session, interaction *discordgo.Inter
}
}
default:
log.Printf("Warning: Unhandled autocomplete option: %s", data.Options)
log.Printf("Warning: Unhandled autocomplete option: %v", data.Options)
return
}

1
go.mod
View File

@@ -12,6 +12,7 @@ require (
github.com/gorilla/websocket v1.4.2 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/redis/go-redis/v9 v9.3.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.5.0 // indirect

11
go.sum
View File

@@ -6,6 +6,8 @@ github.com/bwmarrin/discordgo v0.27.1 h1:ib9AIc/dom1E/fSIulrBwnez0CToJE113ZGt4Ho
github.com/bwmarrin/discordgo v0.27.1/go.mod h1:NJZpH+1AfhIcyQsPeuBKsUtYrRnjkyu0kIVMCHkZtRY=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
@@ -14,10 +16,15 @@ github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0U
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis v6.15.9+incompatible h1:F+tnlesQSl3h9V8DdmtcYFdvkHLhbb7AgcLW6UJxnC4=
github.com/redis/go-redis v6.15.9+incompatible/go.mod h1:ic6dLmR0d9rkHSzaa0Ab3QVRZcjopJ9hSSPCrecj/+s=
github.com/redis/go-redis/v9 v9.3.0 h1:RiVDjmig62jIWp7Kk4XVLs0hzV6pI3PyTnnL0cnn0u0=
github.com/redis/go-redis/v9 v9.3.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b h1:7mWr3k41Qtv8XlltBkDkl8LoP3mpSgBW8BUoxtEdbXg=
@@ -39,7 +46,9 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -53,3 +62,5 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -3,13 +3,14 @@ package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
"reflect"
"runtime/debug"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
const baseURL = "https://www.register2park.com"

32
main.go
View File

@@ -1,13 +1,14 @@
package main
import (
"log"
"flag"
"os"
"os/signal"
"github.com/bwmarrin/discordgo"
"github.com/go-redis/redis"
"github.com/joho/godotenv"
log "github.com/sirupsen/logrus"
)
var (
@@ -17,9 +18,19 @@ var (
"register": RegisterCommandHandler,
"code": CodeCommandHandler,
}
db *redis.Client
db *redis.Client
debugFlag = flag.Bool("debug", false, "Enable debug logging")
)
func init() {
flag.Parse()
if *debugFlag {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func Bot() {
// Setup the session parameters
var err error
@@ -75,18 +86,23 @@ func Bot() {
<-stop
// Remove commands
log.Printf("Removing %d command%s...\n", len(registeredCommands), Plural(len(registeredCommands)))
log.Infof("Removing %d command%s...\n", len(registeredCommands), Plural(len(registeredCommands)))
for _, v := range registeredCommands {
log.Debugf("Removing '%v' command (%v)", v.Name, v.ID)
err := session.ApplicationCommandDelete(session.State.User.ID, os.Getenv("BOT_TARGET_GUILD"), v.ID)
if err != nil {
log.Panicf("Cannot delete '%v' command: %v", v.Name, err)
}
}
log.Println("Gracefully shutting down.")
log.Warn("Gracefully shutting down.")
}
func main() {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file")
@@ -102,7 +118,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
log.Printf("Redis connection established (%s).", ping_result)
log.Infof("Redis connection established (%s)", ping_result)
command := ""
if len(os.Args) > 1 {
@@ -111,13 +127,13 @@ func main() {
switch command {
case "scan":
log.Printf("Running scan")
log.Info("Running scan")
Scan()
case "bot":
log.Printf("Running bot")
log.Info("Running bot")
Bot()
default:
log.Printf("Running bot (default)")
log.Info("Running bot (default)")
Bot()
}
}

View File

@@ -5,9 +5,10 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func Scan() {
@@ -15,7 +16,7 @@ func Scan() {
total := len(locations)
for i, location := range locations {
log.Printf("[%6.2f] Fetching \"%s\" ", float64(i+1)/float64(total)*100, location.name)
log.Debugf("[%6.2f] Fetching \"%s\" ", float64(i+1)/float64(total)*100, location.name)
body := fmt.Sprintf("propertyIdSelected=%d&propertySource=parking-snap", location.id)
req := BuildRequestWithBody("POST", "/register-get-vehicle-form", nil, bytes.NewBufferString(body))
@@ -42,8 +43,6 @@ func Scan() {
if err != nil {
panic(err)
}
log.Println("DONE")
} else if stats.Size() < 16 {
// File exists, but is empty
file, err := os.OpenFile(html_path, os.O_WRONLY, 0644)
@@ -56,10 +55,8 @@ func Scan() {
if err != nil {
panic(err)
}
log.Println("OVERWRITE")
} else {
// File exists and is not empty, do nothing
log.Println("SKIP")
}
}
}