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

48
api.go
View File

@@ -38,12 +38,19 @@ func init() {
} }
func onRequest(req *http.Request) { 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++ requestCounter++
} }
func onResponse(res *http.Response) { 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. // Reloads the current session and completes the initial connection process that procedes bot operations.
@@ -67,7 +74,7 @@ func reload() {
}) })
if !has_php_session { if !has_php_session {
log.Fatal("PHPSESSID cookie not found") log.WithFields(log.Fields{"cookies": site_cookies}).Panic("PHPSESSID cookie not found")
} else { } else {
log.Debugf("PHPSESSID cookie found") log.Debugf("PHPSESSID cookie found")
} }
@@ -80,9 +87,10 @@ func tryReload() {
lastReloadDiff := currentTime.Sub(lastReload) lastReloadDiff := currentTime.Sub(lastReload)
if requestCounter >= 10 { 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 { } 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 { } else {
return return
} }
@@ -92,17 +100,13 @@ func tryReload() {
requestCounter = 0 requestCounter = 0
} }
func register(location uint, code string, make string, model string, plate string) {
}
func GetLocations() []Location { func GetLocations() []Location {
if time.Now().Before(cacheExpiry) { if time.Now().Before(cacheExpiry) {
return cachedLocations return cachedLocations
} }
tryReload() 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 body := "propertyNameEntered=" // Empty, so we get all locations
req := BuildRequestWithBody("POST", "/register-get-properties-from-name", nil, bytes.NewBufferString(body)) req := BuildRequestWithBody("POST", "/register-get-properties-from-name", nil, bytes.NewBufferString(body))
@@ -147,13 +151,13 @@ func GetLocations() []Location {
} }
type GetFormResult struct { type GetFormResult struct {
propertyName string propertyName string
address string address string
fields []Field // label & inputs in the form fields []Field // label & inputs in the form
hiddenInputs []string // hidden inputs in the form hiddenInputs []string // hidden inputs in the form
requireGuestCode bool // whether a guest code is required requireGuestCode bool // whether a guest code is required
residentProfileId string residentProfileId string
err error // any error that occurred err error // any error that occurred
} }
func GetForm(id uint) GetFormResult { func GetForm(id uint) GetFormResult {
@@ -191,10 +195,10 @@ func GetForm(id uint) GetFormResult {
address := strings.TrimSpace(titleElement.Next().Text()) address := strings.TrimSpace(titleElement.Next().Text())
return GetFormResult{ return GetFormResult{
propertyName: title, propertyName: title,
address: address, address: address,
fields: formFields, fields: formFields,
hiddenInputs: hiddenInputs, hiddenInputs: hiddenInputs,
residentProfileId: residentProfileId, residentProfileId: residentProfileId,
} }
} }
@@ -243,7 +247,7 @@ type RegistrationResult struct {
emailIdentifier string 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 := url.Values{}
body.Set("propertySource", "parking-snap") body.Set("propertySource", "parking-snap")
body.Set("propertyIdSelected", strconv.FormatUint(uint64(propertyId), 10)) 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 // TODO: Parsing of success/failure
log.Debugf("RegisterVehicle response: %s", htmlString) 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 var err error
session, err = discordgo.New("Bot " + os.Getenv("BOT_TOKEN")) session, err = discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))
if err != nil { if err != nil {
log.Fatalf("Invalid bot parameters: %v", err) log.WithField("error", err).Panic("Invalid bot parameters")
} }
// Login handler // Login handler
session.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { session.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
log.Infof("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator) log.WithFields(
log.Fields{
// Count servers "username": r.User.Username,
guilds := s.State.Guilds "discriminator": r.User.Discriminator,
log.Debugf("Connected to %d server%s", len(guilds), Plural(len(guilds))) "id": r.User.ID,
"guilds": len(r.Guilds),
"session": r.SessionID,
}).Info("Logged in successfully")
// Load the session // Load the session
tryReload() tryReload()
@@ -58,7 +61,7 @@ func Bot() {
// Open the session // Open the session
err = session.Open() err = session.Open()
if err != nil { 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 // Make sure sessions and HTTP clients are closed
@@ -96,7 +99,11 @@ func Bot() {
// panic(err) // panic(err)
// } // }
default: 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) signal.Notify(stop, os.Interrupt)
// Register commands // 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)) registeredCommands := make([]*discordgo.ApplicationCommand, len(commandDefinitions))
for definitionIndex, commandDefinition := range commandDefinitions { for definitionIndex, commandDefinition := range commandDefinitions {
command, err := session.ApplicationCommandCreate(session.State.User.ID, os.Getenv("BOT_TARGET_GUILD"), commandDefinition) 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 { 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 registeredCommands[definitionIndex] = command
} }
// Wait here until CTRL-C or other term signal is received. // 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 <-stop
// Remove commands // Remove commands
log.Debugf("Removing %d command%s...\n", len(registeredCommands), Plural(len(registeredCommands))) log.WithField("count", len(registeredCommands)).Info("Removing commands")
for _, v := range registeredCommands { for _, registeredCommand := range registeredCommands {
log.Debugf("Removing '%v' command (%v)", v.Name, v.ID) log.WithFields(log.Fields{
err := session.ApplicationCommandDelete(session.State.User.ID, os.Getenv("BOT_TARGET_GUILD"), v.ID) "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 { 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() { func main() {
@@ -142,7 +156,7 @@ func main() {
// Load environment variables // Load environment variables
if err := godotenv.Load(); err != nil { if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file") log.WithField("error", err).Panic("Error loading .env file")
} }
opt := &redis.Options{ opt := &redis.Options{
@@ -155,7 +169,7 @@ func main() {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
log.Infof("Redis connection established (%s)", ping_result) log.WithField("ping", ping_result).Info("Redis connection established")
command := "" command := ""
args := flag.Args() args := flag.Args()
@@ -163,6 +177,7 @@ func main() {
command = args[1] command = args[1]
} }
log.WithField("command", command).Debug("Starting up")
switch command { switch command {
case "scan": case "scan":
log.Info("Scanning...") log.Info("Scanning...")