Switch to field-based logging (main.go, api.go)

Also removed unused register function
This commit is contained in:
2023-12-20 08:18:29 -06:00
parent a6e47a33e6
commit 473690bbd1
2 changed files with 62 additions and 43 deletions

28
api.go
View File

@@ -38,12 +38,19 @@ func init() {
}
func onRequest(req *http.Request) {
log.Debugf("%s %s", req.Method, req.URL.String())
log.WithFields(log.Fields{
"method": req.Method,
"url": req.URL.String(),
}).Debugf("%s %s", req.Method, req.URL.String())
requestCounter++
}
func onResponse(res *http.Response) {
log.Debugf("%s %d %s", res.Status, res.ContentLength, res.Header["Content-Type"])
log.WithFields(log.Fields{
"status": res.Status,
"length": res.ContentLength,
"type": res.Header["Content-Type"],
}).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.
@@ -67,7 +74,7 @@ func reload() {
})
if !has_php_session {
log.Fatal("PHPSESSID cookie not found")
log.WithFields(log.Fields{"cookies": site_cookies}).Panic("PHPSESSID cookie not found")
} else {
log.Debugf("PHPSESSID cookie found")
}
@@ -80,9 +87,10 @@ func tryReload() {
lastReloadDiff := currentTime.Sub(lastReload)
if requestCounter >= 10 {
log.Info("Reloading session due to request count...")
log.WithFields(log.Fields{"requestCounter": requestCounter}).Info("Reloading session due to request count")
log.Info("Reloading session due to request count")
} else if lastReloadDiff >= 15*60 {
log.Infof("Reloading session due to time (%s)...", lastReloadDiff)
log.WithFields(log.Fields{"lastReload": lastReload, "difference": lastReloadDiff}).Info("Reloading session due to time")
} else {
return
}
@@ -92,17 +100,13 @@ func tryReload() {
requestCounter = 0
}
func register(location uint, code string, make string, model string, plate string) {
}
func GetLocations() []Location {
if time.Now().Before(cacheExpiry) {
return cachedLocations
}
tryReload()
log.Printf("Refetching locations (%s since refresh)", time.Now().Sub(cacheExpiry))
log.WithFields(log.Fields{"sinceRefresh": time.Now().Sub(cacheExpiry)}).Debug("Refetching locations")
body := "propertyNameEntered=" // Empty, so we get all locations
req := BuildRequestWithBody("POST", "/register-get-properties-from-name", nil, bytes.NewBufferString(body))
@@ -243,7 +247,7 @@ type RegistrationResult struct {
emailIdentifier string
}
func RegisterVehicle(formParams map[string]string, propertyId uint, residentProfileId uint, hiddenParams []string) (bool, RegistrationResult) {
func RegisterVehicle(formParams map[string]string, propertyId uint, residentProfileId uint, hiddenParams []string) (bool, *RegistrationResult) {
body := url.Values{}
body.Set("propertySource", "parking-snap")
body.Set("propertyIdSelected", strconv.FormatUint(uint64(propertyId), 10))
@@ -270,5 +274,5 @@ func RegisterVehicle(formParams map[string]string, propertyId uint, residentProf
// TODO: Parsing of success/failure
log.Debugf("RegisterVehicle response: %s", htmlString)
return (false, nil)
return false, nil
}

55
main.go
View File

@@ -40,16 +40,19 @@ func Bot() {
var err error
session, err = discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))
if err != nil {
log.Fatalf("Invalid bot parameters: %v", err)
log.WithField("error", err).Panic("Invalid bot parameters")
}
// Login handler
session.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
log.Infof("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
// Count servers
guilds := s.State.Guilds
log.Debugf("Connected to %d server%s", len(guilds), Plural(len(guilds)))
log.WithFields(
log.Fields{
"username": r.User.Username,
"discriminator": r.User.Discriminator,
"id": r.User.ID,
"guilds": len(r.Guilds),
"session": r.SessionID,
}).Info("Logged in successfully")
// Load the session
tryReload()
@@ -58,7 +61,7 @@ func Bot() {
// Open the session
err = session.Open()
if err != nil {
log.Fatalf("Cannot open the session: %v", err)
log.WithField("error", err).Panic("Cannot open the session")
}
// Make sure sessions and HTTP clients are closed
@@ -96,7 +99,11 @@ func Bot() {
// panic(err)
// }
default:
log.Warnf("Warning: Unhandled interaction type: %v", interaction.Type)
log.WithFields(
log.Fields{
"type": interaction.Type,
"ref": interaction.Message.Reference(),
}).Warn("Unhandled interaction type")
}
})
@@ -105,33 +112,40 @@ func Bot() {
signal.Notify(stop, os.Interrupt)
// Register commands
log.Debugf("Adding %d command%s...", len(commandDefinitions), Plural(len(commandDefinitions)))
log.WithField("count", len(commandDefinitions)).Info("Registering commands")
registeredCommands := make([]*discordgo.ApplicationCommand, len(commandDefinitions))
for definitionIndex, commandDefinition := range commandDefinitions {
command, err := session.ApplicationCommandCreate(session.State.User.ID, os.Getenv("BOT_TARGET_GUILD"), commandDefinition)
log.Debugf("Registering '%v' command (%v)", commandDefinition.Name, command.ID)
log.WithField("command", commandDefinition.Name).Debug("Registering command")
if err != nil {
log.Panicf("Failed while registering '%v' command: %v", commandDefinition.Name, err)
log.WithFields(log.Fields{
"error": err,
"command": commandDefinition.Name,
}).Panic("Failed while registering command")
}
registeredCommands[definitionIndex] = command
}
// Wait here until CTRL-C or other term signal is received.
log.Println("Press Ctrl+C to exit")
log.Info("Press Ctrl+C to exit")
<-stop
// Remove commands
log.Debugf("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)
log.WithField("count", len(registeredCommands)).Info("Removing commands")
for _, registeredCommand := range registeredCommands {
log.WithFields(log.Fields{
"command": registeredCommand.Name,
"id": registeredCommand.ID,
}).Debug("Removing command")
err := session.ApplicationCommandDelete(session.State.User.ID, os.Getenv("BOT_TARGET_GUILD"), registeredCommand.ID)
if err != nil {
log.Panicf("Cannot delete '%v' command: %v", v.Name, err)
log.Panicf("Cannot delete '%v' command: %v", registeredCommand.Name, err)
}
}
log.Warn("Gracefully shutting down.")
log.Warn("Gracefully shutting down")
defer log.Warn("Graceful shutdown complete")
}
func main() {
@@ -142,7 +156,7 @@ func main() {
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file")
log.WithField("error", err).Panic("Error loading .env file")
}
opt := &redis.Options{
@@ -155,7 +169,7 @@ func main() {
if err != nil {
log.Fatal(err)
}
log.Infof("Redis connection established (%s)", ping_result)
log.WithField("ping", ping_result).Info("Redis connection established")
command := ""
args := flag.Args()
@@ -163,6 +177,7 @@ func main() {
command = args[1]
}
log.WithField("command", command).Debug("Starting up")
switch command {
case "scan":
log.Info("Scanning...")