From b1c450da08ce29f23cfd283fb068843350e9c622 Mon Sep 17 00:00:00 2001 From: Chris Sexton Date: Thu, 21 Feb 2019 10:01:10 -0500 Subject: [PATCH 1/2] cowsay: make messages visible :( --- plugins/talker/talker.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/plugins/talker/talker.go b/plugins/talker/talker.go index 92ef3ac..38153d9 100644 --- a/plugins/talker/talker.go +++ b/plugins/talker/talker.go @@ -173,11 +173,14 @@ func (p *TalkerPlugin) registerWeb() { http.HandleFunc("/slash/cowsay", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() log.Printf("Cowsay:\n%+v", r.PostForm.Get("text")) + channel := r.PostForm.Get("channel_id") + log.Printf("channel: %s", channel) msg, err := p.cowSay(r.PostForm.Get("text")) if err != nil { - fmt.Fprintf(w, "Error running cowsay: %s", err) + p.Bot.Send(bot.Message, channel, fmt.Sprintf("Error running cowsay: %s", err)) return } - fmt.Fprintf(w, "%s", msg) + p.Bot.Send(bot.Message, channel, msg) + w.WriteHeader(200) }) } From a2d5d173f991ce1b8ce0fa9262d4830c6d489eab Mon Sep 17 00:00:00 2001 From: Chris Sexton Date: Thu, 7 Mar 2019 11:35:42 -0500 Subject: [PATCH 2/2] logging: switch to a logging library --- bot/bot.go | 9 +- bot/handlers.go | 12 +-- bot/mock.go | 6 +- config/config.go | 10 +-- config/defaults.go | 7 +- connectors/irc/irc.go | 12 +-- connectors/slack/slack.go | 100 +++++++++++----------- connectors/slackapp/slackApp.go | 73 +++++++++++----- go.mod | 1 + go.sum | 2 + main.go | 33 +++++--- plugins/admin/admin.go | 13 +-- plugins/babbler/babbler.go | 144 ++++++++++++++++---------------- plugins/beers/beers.go | 50 ++++++----- plugins/counter/counter.go | 92 +++++++++++++++----- plugins/db/db.go | 5 +- plugins/emojifyme/emojifyme.go | 9 +- plugins/fact/factoid.go | 57 ++++++++----- plugins/first/first.go | 56 +++++++++---- plugins/inventory/inventory.go | 39 ++++----- plugins/remember/remember.go | 17 ++-- plugins/reminder/reminder.go | 29 +++---- plugins/sisyphus/sisyphus.go | 5 +- plugins/talker/talker.go | 7 +- plugins/twitch/twitch.go | 26 +++--- plugins/zork/zork.go | 13 +-- util/emojy/main.go | 23 ++--- util/files/main.go | 35 +++++--- 28 files changed, 526 insertions(+), 359 deletions(-) diff --git a/bot/bot.go b/bot/bot.go index b794fcc..8ba3029 100644 --- a/bot/bot.go +++ b/bot/bot.go @@ -4,12 +4,12 @@ package bot import ( "html/template" - "log" "net/http" "reflect" "strings" "github.com/jmoiron/sqlx" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msglog" "github.com/velour/catbase/bot/user" @@ -105,7 +105,7 @@ func (b *bot) migrateDB() { name string, value string );`); err != nil { - log.Fatal("Initial DB migration create variables table: ", err) + log.Fatal().Err(err).Msgf("Initial DB migration create variables table") } } @@ -160,7 +160,7 @@ func (b *bot) serveRoot(w http.ResponseWriter, r *http.Request) { context["EndPoints"] = b.httpEndPoints t, err := template.New("rootIndex").Parse(rootIndex) if err != nil { - log.Println(err) + log.Error().Err(err) } t.Execute(w, context) } @@ -170,7 +170,8 @@ func IsCmd(c *config.Config, message string) (bool, string) { cmdcs := c.GetArray("CommandChar", []string{"!"}) botnick := strings.ToLower(c.Get("Nick", "bot")) if botnick == "" { - log.Fatalf(`You must run catbase -set nick -val `) + log.Fatal(). + Msgf(`You must run catbase -set nick -val `) } iscmd := false lowerMessage := strings.ToLower(message) diff --git a/bot/handlers.go b/bot/handlers.go index 75eff1b..5dfe12c 100644 --- a/bot/handlers.go +++ b/bot/handlers.go @@ -6,7 +6,6 @@ import ( "database/sql" "errors" "fmt" - "log" "math/rand" "reflect" "regexp" @@ -14,18 +13,21 @@ import ( "strings" "time" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot/msg" ) func (b *bot) Receive(kind Kind, msg msg.Message, args ...interface{}) bool { - log.Println("Received event: ", msg) + log.Debug(). + Interface("msg", msg). + Msg("Received event") // msg := b.buildMessage(client, inMsg) // do need to look up user and fix it if kind == Message && strings.HasPrefix(msg.Body, "help") && msg.Command { parts := strings.Fields(strings.ToLower(msg.Body)) b.checkHelp(msg.Channel, parts) - log.Println("Handled a help, returning") + log.Debug().Msg("Handled a help, returning") goto RET } @@ -171,7 +173,7 @@ func (b *bot) getVar(varName string) (string, error) { case err == sql.ErrNoRows: return "", fmt.Errorf("No factoid found") case err != nil: - log.Fatal("getVar error: ", err) + log.Fatal().Err(err).Msg("getVar error") } return text, nil } @@ -180,7 +182,7 @@ func (b *bot) listVars(channel string, parts []string) { var variables []string err := b.DB().Select(&variables, `select name from variables group by name`) if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } msg := "I know: $who, $someone, $digit, $nonzero" if len(variables) > 0 { diff --git a/bot/mock.go b/bot/mock.go index f9f2917..6f11c12 100644 --- a/bot/mock.go +++ b/bot/mock.go @@ -4,12 +4,12 @@ package bot import ( "fmt" - "log" "net/http" "strconv" "strings" "github.com/jmoiron/sqlx" + "github.com/rs/zerolog/log" "github.com/stretchr/testify/mock" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/user" @@ -64,14 +64,14 @@ func (mb *MockBot) edit(channel, newMessage, identifier string) (string, error) isMessage := identifier[0] == 'm' if !isMessage && identifier[0] != 'a' { err := fmt.Errorf("failed to parse identifier: %s", identifier) - log.Println(err) + log.Error().Err(err) return "", err } index, err := strconv.Atoi(strings.Split(identifier, "-")[1]) if err != nil { err := fmt.Errorf("failed to parse identifier: %s", identifier) - log.Println(err) + log.Error().Err(err) return "", err } diff --git a/config/config.go b/config/config.go index 827b310..3431a8f 100644 --- a/config/config.go +++ b/config/config.go @@ -5,7 +5,6 @@ package config import ( "database/sql" "fmt" - "log" "os" "regexp" "strconv" @@ -13,6 +12,7 @@ import ( "github.com/jmoiron/sqlx" sqlite3 "github.com/mattn/go-sqlite3" + "github.com/rs/zerolog/log" ) // Config stores any system-wide startup information that cannot be easily configured via @@ -74,7 +74,7 @@ func (c *Config) GetString(key, fallback string) string { q := `select value from config where key=?` err := c.DB.Get(&configValue, q, key) if err != nil { - log.Printf("WARN: Key %s is empty", key) + log.Debug().Msgf("WARN: Key %s is empty", key) return fallback } return configValue @@ -137,11 +137,11 @@ func ReadConfig(dbpath string) *Config { if dbpath == "" { dbpath = "catbase.db" } - fmt.Printf("Using %s as database file.\n", dbpath) + log.Info().Msgf("Using %s as database file.\n", dbpath) sqlDB, err := sqlx.Open("sqlite3_custom", dbpath) if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } c := Config{ DBFile: dbpath, @@ -156,7 +156,7 @@ func ReadConfig(dbpath string) *Config { panic(err) } - fmt.Printf("catbase is running.\n") + log.Info().Msgf("catbase is running.") return &c } diff --git a/config/defaults.go b/config/defaults.go index f94d6b3..26626ba 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -2,9 +2,10 @@ package config import ( "bytes" - "log" "strings" "text/template" + + "github.com/rs/zerolog/log" ) var q = ` @@ -17,7 +18,7 @@ INSERT INTO config VALUES('init',1); func (c *Config) SetDefaults(mainChannel, nick string) { if nick == mainChannel && nick == "" { - log.Fatalf("You must provide a nick and a mainChannel") + log.Fatal().Msgf("You must provide a nick and a mainChannel") } t := template.Must(template.New("query").Parse(q)) vals := struct { @@ -33,5 +34,5 @@ func (c *Config) SetDefaults(mainChannel, nick string) { t.Execute(&buf, vals) c.MustExec(`delete from config;`) c.MustExec(buf.String()) - log.Println("Configuration initialized.") + log.Info().Msgf("Configuration initialized.") } diff --git a/connectors/irc/irc.go b/connectors/irc/irc.go index a10deea..b9f1b24 100644 --- a/connectors/irc/irc.go +++ b/connectors/irc/irc.go @@ -5,11 +5,11 @@ package irc import ( "fmt" "io" - "log" "os" "strings" "time" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/user" @@ -69,7 +69,7 @@ func (i *Irc) Send(kind bot.Kind, args ...interface{}) (string, error) { } func (i *Irc) JoinChannel(channel string) { - log.Printf("Joining channel: %s", channel) + log.Info().Msgf("Joining channel: %s", channel) i.Client.Out <- irc.Msg{Cmd: irc.JOIN, Args: []string{channel}} } @@ -147,7 +147,7 @@ func (i *Irc) handleConnection() { close(i.Client.Out) for err := range i.Client.Errors { if err != io.EOF { - log.Println(err) + log.Error().Err(err) } } }() @@ -169,7 +169,7 @@ func (i *Irc) handleConnection() { case err, ok := <-i.Client.Errors: if ok && err != io.EOF { - log.Println(err) + log.Error().Err(err) i.quit <- true return } @@ -183,7 +183,7 @@ func (i *Irc) handleMsg(msg irc.Msg) { switch msg.Cmd { case irc.ERROR: - log.Println(1, "Received error: "+msg.Raw) + log.Info().Msgf("Received error: " + msg.Raw) case irc.PING: i.Client.Out <- irc.Msg{Cmd: irc.PONG} @@ -241,7 +241,7 @@ func (i *Irc) handleMsg(msg irc.Msg) { default: cmd := irc.CmdNames[msg.Cmd] - log.Println("(" + cmd + ") " + msg.Raw) + log.Debug().Msgf("(%s) %s", cmd, msg.Raw) } } diff --git a/connectors/slack/slack.go b/connectors/slack/slack.go index 6fe4691..16076a9 100644 --- a/connectors/slack/slack.go +++ b/connectors/slack/slack.go @@ -10,7 +10,6 @@ import ( "html" "io" "io/ioutil" - "log" "net/http" "net/url" "regexp" @@ -21,6 +20,7 @@ import ( "context" "time" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/user" @@ -164,7 +164,7 @@ type rtmStart struct { func New(c *config.Config) *Slack { token := c.Get("slack.token", "NONE") if token == "NONE" { - log.Fatalf("No slack token found. Set SLACKTOKEN env.") + log.Fatal().Msgf("No slack token found. Set SLACKTOKEN env.") } return &Slack{ config: c, @@ -242,16 +242,16 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string }) if err != nil { - log.Printf("Error sending Slack message: %s", err) + log.Error().Err(err).Msgf("Error sending Slack message") } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - log.Fatalf("Error reading Slack API body: %s", err) + log.Fatal().Err(err).Msgf("Error reading Slack API body") } - log.Println(string(body)) + log.Debug().Msgf("%+v", body) type MessageResponse struct { OK bool `json:"ok"` @@ -264,7 +264,7 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string var mr MessageResponse err = json.Unmarshal(body, &mr) if err != nil { - log.Fatalf("Error parsing message response: %s", err) + log.Fatal().Err(err).Msgf("Error parsing message response") } if !mr.OK { @@ -277,13 +277,13 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string } func (s *Slack) sendMessage(channel, message string) (string, error) { - log.Printf("Sending message to %s: %s", channel, message) + log.Debug().Msgf("Sending message to %s: %s", channel, message) identifier, err := s.sendMessageType(channel, message, false) return identifier, err } func (s *Slack) sendAction(channel, message string) (string, error) { - log.Printf("Sending action to %s: %s", channel, message) + log.Debug().Msgf("Sending action to %s: %s", channel, message) identifier, err := s.sendMessageType(channel, "_"+message+"_", true) return identifier, err } @@ -313,7 +313,7 @@ func (s *Slack) replyToMessageIdentifier(channel, message, identifier string) (s return "", err } - log.Println(string(body)) + log.Debug().Msgf("%s", body) type MessageResponse struct { OK bool `json:"ok"` @@ -339,7 +339,7 @@ func (s *Slack) replyToMessage(channel, message string, replyTo msg.Message) (st } func (s *Slack) react(channel, reaction string, message msg.Message) (string, error) { - log.Printf("Reacting in %s: %s", channel, reaction) + log.Debug().Msgf("Reacting in %s: %s", channel, reaction) resp, err := http.PostForm("https://slack.com/api/reactions.add", url.Values{"token": {s.token}, "name": {reaction}, @@ -353,7 +353,7 @@ func (s *Slack) react(channel, reaction string, message msg.Message) (string, er } func (s *Slack) edit(channel, newMessage, identifier string) (string, error) { - log.Printf("Editing in (%s) %s: %s", identifier, channel, newMessage) + log.Debug().Msgf("Editing in (%s) %s: %s", identifier, channel, newMessage) resp, err := http.PostForm("https://slack.com/api/chat.update", url.Values{"token": {s.token}, "channel": {channel}, @@ -374,14 +374,14 @@ func (s *Slack) populateEmojiList() { resp, err := http.PostForm("https://slack.com/api/emoji.list", url.Values{"token": {s.token}}) if err != nil { - log.Printf("Error retrieving emoji list from Slack: %s", err) + log.Debug().Msgf("Error retrieving emoji list from Slack: %s", err) return } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - log.Fatalf("Error reading Slack API body: %s", err) + log.Fatal().Err(err).Msgf("Error reading Slack API body") } type EmojiListResponse struct { @@ -392,7 +392,7 @@ func (s *Slack) populateEmojiList() { var list EmojiListResponse err = json.Unmarshal(body, &list) if err != nil { - log.Fatalf("Error parsing emoji list: %s", err) + log.Fatal().Err(err).Msgf("Error parsing emoji list") } s.emoji = list.Emoji } @@ -417,7 +417,7 @@ func (s *Slack) receiveMessage() (slackMessage, error) { m := slackMessage{} err := s.ws.Recv(context.TODO(), &m) if err != nil { - log.Println("Error decoding WS message") + log.Error().Msgf("Error decoding WS message") panic(fmt.Errorf("%v\n%v", m, err)) } return m, nil @@ -442,7 +442,7 @@ func (s *Slack) Serve() error { for { msg, err := s.receiveMessage() if err != nil && err == io.EOF { - log.Fatalf("Slack API EOF") + log.Fatal().Msg("Slack API EOF") } else if err != nil { return fmt.Errorf("Slack API error: %s", err) } @@ -452,7 +452,7 @@ func (s *Slack) Serve() error { if !isItMe && !msg.Hidden && msg.ThreadTs == "" { m := s.buildMessage(msg) if m.Time.Before(s.lastRecieved) { - log.Printf("Ignoring message: %+v\nlastRecieved: %v msg: %v", msg.ID, s.lastRecieved, m.Time) + log.Debug().Msgf("Ignoring message: %+v\nlastRecieved: %v msg: %v", msg.ID, s.lastRecieved, m.Time) } else { s.lastRecieved = m.Time s.event(bot.Message, m) @@ -461,10 +461,10 @@ func (s *Slack) Serve() error { //we're throwing away some information here by not parsing the correct reply object type, but that's okay s.event(bot.Reply, s.buildLightReplyMessage(msg), msg.ThreadTs) } else { - log.Printf("THAT MESSAGE WAS HIDDEN: %+v", msg.ID) + log.Debug().Msgf("THAT MESSAGE WAS HIDDEN: %+v", msg.ID) } case "error": - log.Printf("Slack error, code: %d, message: %s", msg.Error.Code, msg.Error.Msg) + log.Error().Msgf("Slack error, code: %d, message: %s", msg.Error.Code, msg.Error.Msg) case "": // what even is this? case "hello": case "presence_change": @@ -475,7 +475,7 @@ func (s *Slack) Serve() error { // squeltch this stuff continue default: - log.Printf("Unhandled Slack message type: '%s'", msg.Type) + log.Debug().Msgf("Unhandled Slack message type: '%s'", msg.Type) } } } @@ -554,11 +554,11 @@ func (s *Slack) buildLightReplyMessage(m slackMessage) msg.Message { // markAllChannelsRead gets a list of all channels and marks each as read func (s *Slack) markAllChannelsRead() { chs := s.getAllChannels() - log.Printf("Got list of channels to mark read: %+v", chs) + log.Debug().Msgf("Got list of channels to mark read: %+v", chs) for _, ch := range chs { s.markChannelAsRead(ch.ID) } - log.Printf("Finished marking channels read") + log.Debug().Msgf("Finished marking channels read") } // getAllChannels returns info for all channels joined @@ -567,12 +567,11 @@ func (s *Slack) getAllChannels() []slackChannelListItem { resp, err := http.PostForm(u, url.Values{"token": {s.token}}) if err != nil { - log.Printf("Error posting user info request: %s", - err) + log.Error().Err(err).Msgf("Error posting user info request") return nil } if resp.StatusCode != 200 { - log.Printf("Error posting user info request: %d", + log.Error().Msgf("Error posting user info request: %d", resp.StatusCode) return nil } @@ -580,7 +579,7 @@ func (s *Slack) getAllChannels() []slackChannelListItem { var chanInfo slackChannelListResp err = json.NewDecoder(resp.Body).Decode(&chanInfo) if err != nil || !chanInfo.Ok { - log.Println("Error decoding response: ", err) + log.Error().Err(err).Msgf("Error decoding response") return nil } return chanInfo.Channels @@ -592,21 +591,19 @@ func (s *Slack) markChannelAsRead(slackChanId string) error { resp, err := http.PostForm(u, url.Values{"token": {s.token}, "channel": {slackChanId}}) if err != nil { - log.Printf("Error posting user info request: %s", - err) + log.Error().Err(err).Msgf("Error posting user info request") return err } if resp.StatusCode != 200 { - log.Printf("Error posting user info request: %d", + log.Error().Msgf("Error posting user info request: %d", resp.StatusCode) return err } defer resp.Body.Close() var chanInfo slackChannelInfoResp err = json.NewDecoder(resp.Body).Decode(&chanInfo) - log.Printf("%+v, %+v", err, chanInfo) if err != nil || !chanInfo.Ok { - log.Println("Error decoding response: ", err) + log.Error().Err(err).Msgf("Error decoding response") return err } @@ -614,25 +611,23 @@ func (s *Slack) markChannelAsRead(slackChanId string) error { resp, err = http.PostForm(u, url.Values{"token": {s.token}, "channel": {slackChanId}, "ts": {chanInfo.Channel.Latest.Ts}}) if err != nil { - log.Printf("Error posting user info request: %s", - err) + log.Error().Err(err).Msgf("Error posting user info request") return err } if resp.StatusCode != 200 { - log.Printf("Error posting user info request: %d", + log.Error().Msgf("Error posting user info request: %d", resp.StatusCode) return err } defer resp.Body.Close() var markInfo map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&markInfo) - log.Printf("%+v, %+v", err, markInfo) if err != nil { - log.Println("Error decoding response: ", err) + log.Error().Err(err).Msgf("Error decoding response") return err } - log.Printf("Marked %s as read", slackChanId) + log.Info().Msgf("Marked %s as read", slackChanId) return nil } @@ -644,12 +639,12 @@ func (s *Slack) connect() { return } if resp.StatusCode != 200 { - log.Fatalf("Slack API failed. Code: %d", resp.StatusCode) + log.Fatal().Msgf("Slack API failed. Code: %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - log.Fatalf("Error reading Slack API body: %s", err) + log.Fatal().Err(err).Msg("Error reading Slack API body") } var rtm rtmStart err = json.Unmarshal(body, &rtm) @@ -658,7 +653,7 @@ func (s *Slack) connect() { } if !rtm.Ok { - log.Fatalf("Slack error: %s", rtm.Error) + log.Fatal().Msgf("Slack error: %s", rtm.Error) } s.url = "https://slack.com/api/" @@ -670,7 +665,7 @@ func (s *Slack) connect() { rtmURL, _ := url.Parse(rtm.URL) s.ws, err = websocket.Dial(context.TODO(), rtmURL) if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } } @@ -680,20 +675,20 @@ func (s *Slack) getUser(id string) (string, bool) { return name, true } - log.Printf("User %s not already found, requesting info", id) + log.Debug().Msgf("User %s not already found, requesting info", id) u := s.url + "users.info" resp, err := http.PostForm(u, url.Values{"token": {s.token}, "user": {id}}) if err != nil || resp.StatusCode != 200 { - log.Printf("Error posting user info request: %d %s", - resp.StatusCode, err) + log.Error().Err(err).Msgf("Error posting user info request: %d", + resp.StatusCode) return "UNKNOWN", false } defer resp.Body.Close() var userInfo slackUserInfoResp err = json.NewDecoder(resp.Body).Decode(&userInfo) if err != nil { - log.Println("Error decoding response: ", err) + log.Error().Err(err).Msgf("Error decoding response") return "UNKNOWN", false } s.users[id] = userInfo.User.Name @@ -702,17 +697,18 @@ func (s *Slack) getUser(id string) (string, bool) { // Who gets usernames out of a channel func (s *Slack) Who(id string) []string { - log.Println("Who is queried for ", id) + log.Debug(). + Str("id", id). + Msg("Who is queried for ") u := s.url + "channels.info" resp, err := http.PostForm(u, url.Values{"token": {s.token}, "channel": {id}}) if err != nil { - log.Printf("Error posting user info request: %s", - err) + log.Error().Err(err).Msgf("Error posting user info request") return []string{} } if resp.StatusCode != 200 { - log.Printf("Error posting user info request: %d", + log.Error().Msgf("Error posting user info request: %d", resp.StatusCode) return []string{} } @@ -720,17 +716,17 @@ func (s *Slack) Who(id string) []string { var chanInfo slackChannelInfoResp err = json.NewDecoder(resp.Body).Decode(&chanInfo) if err != nil || !chanInfo.Ok { - log.Println("Error decoding response: ", err) + log.Error().Err(err).Msgf("Error decoding response") return []string{} } - log.Printf("%#v", chanInfo.Channel) + log.Debug().Msgf("%#v", chanInfo.Channel) handles := []string{} for _, member := range chanInfo.Channel.Members { u, _ := s.getUser(member) handles = append(handles, u) } - log.Printf("Returning %d handles", len(handles)) + log.Debug().Msgf("Returning %d handles", len(handles)) return handles } diff --git a/connectors/slackapp/slackApp.go b/connectors/slackapp/slackApp.go index 45d3b0d..4a264ed 100644 --- a/connectors/slackapp/slackApp.go +++ b/connectors/slackapp/slackApp.go @@ -7,7 +7,6 @@ import ( "fmt" "html" "io/ioutil" - "log" "net/http" "net/url" "regexp" @@ -15,6 +14,8 @@ import ( "strings" "time" + "github.com/rs/zerolog/log" + "github.com/nlopes/slack" "github.com/nlopes/slack/slackevents" @@ -50,7 +51,7 @@ type SlackApp struct { func New(c *config.Config) *SlackApp { token := c.Get("slack.token", "NONE") if token == "NONE" { - log.Fatalf("No slack token found. Set SLACKTOKEN env.") + log.Fatal().Msg("No slack token found. Set SLACKTOKEN env.") } api := slack.New(token, slack.OptionDebug(false)) @@ -88,7 +89,7 @@ func (s *SlackApp) Serve() error { body := buf.String() eventsAPIEvent, e := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionVerifyToken(&slackevents.TokenComparator{VerificationToken: s.verification})) if e != nil { - log.Println(e) + log.Error().Err(e) w.WriteHeader(http.StatusInternalServerError) } @@ -96,7 +97,7 @@ func (s *SlackApp) Serve() error { var r *slackevents.ChallengeResponse err := json.Unmarshal([]byte(body), &r) if err != nil { - log.Println(err) + log.Error().Err(err) w.WriteHeader(http.StatusInternalServerError) } w.Header().Set("Content-Type", "text") @@ -112,7 +113,10 @@ func (s *SlackApp) Serve() error { s.msgReceivd(ev) } } else { - log.Printf("Event: (%v): %+v", eventsAPIEvent.Type, eventsAPIEvent) + log.Debug(). + Str("type", eventsAPIEvent.Type). + Interface("event", eventsAPIEvent). + Msg("event") } }) return nil @@ -137,14 +141,19 @@ func (s *SlackApp) checkRingOrAdd(ts string) bool { func (s *SlackApp) msgReceivd(msg *slackevents.MessageEvent) { if s.checkRingOrAdd(msg.TimeStamp) { - log.Printf("Got a duplicate message from server: %s", msg.TimeStamp) + log.Debug(). + Str("ts", msg.TimeStamp). + Msg("Got a duplicate message from server") return } isItMe := msg.BotID != "" && msg.BotID == s.myBotID if !isItMe && msg.ThreadTimeStamp == "" { m := s.buildMessage(msg) if m.Time.Before(s.lastRecieved) { - log.Printf("Ignoring message: lastRecieved: %v msg: %v", s.lastRecieved, m.Time) + log.Debug(). + Time("ts", m.Time). + Interface("lastRecv", s.lastRecieved). + Msg("Ignoring message") } else { s.lastRecieved = m.Time s.event(bot.Message, m) @@ -153,7 +162,9 @@ func (s *SlackApp) msgReceivd(msg *slackevents.MessageEvent) { //we're throwing away some information here by not parsing the correct reply object type, but that's okay s.event(bot.Reply, s.buildMessage(msg), msg.ThreadTimeStamp) } else { - log.Printf("THAT MESSAGE WAS HIDDEN: %+v", msg.Text) + log.Debug(). + Str("text", msg.Text). + Msg("THAT MESSAGE WAS HIDDEN") } } @@ -197,7 +208,7 @@ func (s *SlackApp) sendMessageType(channel, message string, meMessage bool) (str } if err != nil { - log.Printf("Error sending message: %+v", err) + log.Error().Err(err).Msg("Error sending message") return "", err } @@ -205,13 +216,19 @@ func (s *SlackApp) sendMessageType(channel, message string, meMessage bool) (str } func (s *SlackApp) sendMessage(channel, message string) (string, error) { - log.Printf("Sending message to %s: %s", channel, message) + log.Debug(). + Str("channel", channel). + Str("message", message). + Msg("Sending message") identifier, err := s.sendMessageType(channel, message, false) return identifier, err } func (s *SlackApp) sendAction(channel, message string) (string, error) { - log.Printf("Sending action to %s: %s", channel, message) + log.Debug(). + Str("channel", channel). + Str("message", message). + Msg("Sending action") identifier, err := s.sendMessageType(channel, "_"+message+"_", true) return identifier, err } @@ -241,7 +258,7 @@ func (s *SlackApp) replyToMessageIdentifier(channel, message, identifier string) return "", err } - log.Println(string(body)) + log.Debug().Bytes("body", body) type MessageResponse struct { OK bool `json:"ok"` @@ -267,7 +284,10 @@ func (s *SlackApp) replyToMessage(channel, message string, replyTo msg.Message) } func (s *SlackApp) react(channel, reaction string, message msg.Message) (string, error) { - log.Printf("Reacting in %s: %s", channel, reaction) + log.Debug(). + Str("channel", channel). + Str("reaction", reaction). + Msg("reacting") ref := slack.ItemRef{ Channel: channel, Timestamp: message.AdditionalData["RAW_SLACK_TIMESTAMP"], @@ -277,7 +297,11 @@ func (s *SlackApp) react(channel, reaction string, message msg.Message) (string, } func (s *SlackApp) edit(channel, newMessage, identifier string) (string, error) { - log.Printf("Editing in (%s) %s: %s", identifier, channel, newMessage) + log.Debug(). + Str("channel", channel). + Str("identifier", identifier). + Str("newMessage", newMessage). + Msg("editing") nick := s.config.Get("Nick", "bot") _, ts, err := s.api.PostMessage(channel, slack.MsgOptionUsername(nick), @@ -293,14 +317,14 @@ func (s *SlackApp) GetEmojiList() map[string]string { func (s *SlackApp) populateEmojiList() { if s.userToken == "NONE" { - log.Println("Cannot get emoji list without slack.usertoken") + log.Error().Msg("Cannot get emoji list without slack.usertoken") return } api := slack.New(s.userToken, slack.OptionDebug(false)) em, err := api.GetEmoji() if err != nil { - log.Printf("Error retrieving emoji list from Slack: %s", err) + log.Error().Err(err).Msg("Error retrieving emoji list from Slack") return } @@ -357,7 +381,9 @@ func (s *SlackApp) getUser(id string) (string, error) { return name, nil } - log.Printf("User %s not already found, requesting info", id) + log.Debug(). + Str("id", id). + Msg("User not already found, requesting info") u, err := s.api.GetUserInfo(id) if err != nil { return "UNKNOWN", err @@ -369,12 +395,14 @@ func (s *SlackApp) getUser(id string) (string, error) { // Who gets usernames out of a channel func (s *SlackApp) Who(id string) []string { if s.userToken == "NONE" { - log.Println("Cannot get emoji list without slack.usertoken") + log.Error().Msg("Cannot get emoji list without slack.usertoken") return []string{s.config.Get("nick", "bot")} } api := slack.New(s.userToken, slack.OptionDebug(false)) - log.Println("Who is queried for ", id) + log.Debug(). + Str("id", id). + Msg("Who is queried") // Not super sure this is the correct call params := &slack.GetUsersInConversationParameters{ ChannelID: id, @@ -382,7 +410,7 @@ func (s *SlackApp) Who(id string) []string { } members, _, err := api.GetUsersInConversation(params) if err != nil { - log.Println(err) + log.Error().Err(err) return []string{s.config.Get("nick", "bot")} } @@ -390,7 +418,10 @@ func (s *SlackApp) Who(id string) []string { for _, m := range members { u, err := s.getUser(m) if err != nil { - log.Printf("Couldn't get user %s: %s", m, err) + log.Error(). + Err(err). + Str("user", m). + Msg("Couldn't get user") continue } ret = append(ret, u) diff --git a/go.mod b/go.mod index d05e371..5e3af06 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( github.com/nlopes/slack v0.5.0 github.com/pkg/errors v0.8.1 // indirect github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d // indirect + github.com/rs/zerolog v1.12.0 github.com/stretchr/objx v0.1.1 // indirect github.com/stretchr/testify v1.3.0 github.com/velour/chat v0.0.0-20180713122344-fd1d1606cb89 diff --git a/go.sum b/go.sum index e4ec4ff..5ee01c2 100644 --- a/go.sum +++ b/go.sum @@ -32,6 +32,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d h1:1VUlQbCfkoSGv7qP7Y+ro3ap1P1pPZxgdGVqiTVy5C4= github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY= +github.com/rs/zerolog v1.12.0 h1:aqZ1XRadoS8IBknR5IDFvGzbHly1X9ApIqOroooQF/c= +github.com/rs/zerolog v1.12.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/main.go b/main.go index aa5c352..521a459 100644 --- a/main.go +++ b/main.go @@ -4,11 +4,14 @@ package main import ( "flag" - "log" "math/rand" "net/http" + "os" "time" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/config" "github.com/velour/catbase/connectors/irc" @@ -19,7 +22,6 @@ import ( "github.com/velour/catbase/plugins/beers" "github.com/velour/catbase/plugins/couldashouldawoulda" "github.com/velour/catbase/plugins/counter" - "github.com/velour/catbase/plugins/db" "github.com/velour/catbase/plugins/dice" "github.com/velour/catbase/plugins/emojifyme" "github.com/velour/catbase/plugins/fact" @@ -42,9 +44,11 @@ import ( ) var ( - key = flag.String("set", "", "Configuration key to set") - val = flag.String("val", "", "Configuration value to set") - initDB = flag.Bool("init", false, "Initialize the configuration DB") + key = flag.String("set", "", "Configuration key to set") + val = flag.String("val", "", "Configuration value to set") + initDB = flag.Bool("init", false, "Initialize the configuration DB") + prettyLog = flag.Bool("pretty", false, "Use pretty console logger") + debug = flag.Bool("debug", false, "Turn on debug logging") ) func main() { @@ -54,15 +58,23 @@ func main() { "Database file to load. (Defaults to catbase.db)") flag.Parse() // parses the logging flags. + if *prettyLog { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + } + zerolog.SetGlobalLevel(zerolog.InfoLevel) + if *debug { + zerolog.SetGlobalLevel(zerolog.DebugLevel) + } + c := config.ReadConfig(*dbpath) if *key != "" && *val != "" { c.Set(*key, *val) - log.Printf("Set config %s: %s", *key, *val) + log.Info().Msgf("Set config %s: %s", *key, *val) return } if (*initDB && len(flag.Args()) != 2) || (!*initDB && c.GetInt("init", 0) != 1) { - log.Fatal(`You must run "catbase -init "`) + log.Fatal().Msgf(`You must run "catbase -init "`) } else if *initDB { c.SetDefaults(flag.Arg(0), flag.Arg(1)) return @@ -78,7 +90,7 @@ func main() { case "slackapp": client = slackapp.New(c) default: - log.Fatalf("Unknown connection type: %s", c.Get("type", "UNSET")) + log.Fatal().Msgf("Unknown connection type: %s", c.Get("type", "UNSET")) } b := bot.New(c, client) @@ -108,12 +120,11 @@ func main() { b.AddPlugin(nerdepedia.New(b)) // catches anything left, will always return true b.AddPlugin(fact.New(b)) - b.AddPlugin(db.New(b)) if err := client.Serve(); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } addr := c.Get("HttpAddr", "127.0.0.1:1337") - log.Fatal(http.ListenAndServe(addr, nil)) + log.Fatal().Err(http.ListenAndServe(addr, nil)) } diff --git a/plugins/admin/admin.go b/plugins/admin/admin.go index 98b439f..f7a38a2 100644 --- a/plugins/admin/admin.go +++ b/plugins/admin/admin.go @@ -4,10 +4,11 @@ package admin import ( "fmt" - "log" "strings" "time" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -63,14 +64,14 @@ func (p *AdminPlugin) message(k bot.Kind, message msg.Message, args ...interface if strings.ToLower(body) == "shut up" { dur := time.Duration(p.cfg.GetInt("quietDuration", 5)) * time.Minute - log.Printf("Going to sleep for %v, %v", dur, time.Now().Add(dur)) + log.Info().Msgf("Going to sleep for %v, %v", dur, time.Now().Add(dur)) p.Bot.Send(bot.Message, message.Channel, "Okay. I'll be back later.") p.quiet = true go func() { select { case <-time.After(dur): p.quiet = false - log.Println("Waking up from nap.") + log.Info().Msg("Waking up from nap.") } }() return true @@ -105,7 +106,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool { _, err := p.db.Exec(`delete from variables where name=? and value=?`, variable, value) if err != nil { p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") - log.Println("[admin]: ", err) + log.Error().Err(err) } else { p.Bot.Send(bot.Message, message.Channel, "Removed.") } @@ -126,7 +127,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool { err := row.Scan(&count) if err != nil { p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") - log.Println("[admin]: ", err) + log.Error().Err(err) return true } @@ -136,7 +137,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool { _, err := p.db.Exec(`INSERT INTO variables (name, value) VALUES (?, ?)`, variable, value) if err != nil { p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") - log.Println("[admin]: ", err) + log.Error().Err(err) return true } p.Bot.Send(bot.Message, message.Channel, "Added.") diff --git a/plugins/babbler/babbler.go b/plugins/babbler/babbler.go index f95782f..2c8311f 100644 --- a/plugins/babbler/babbler.go +++ b/plugins/babbler/babbler.go @@ -6,10 +6,11 @@ import ( "database/sql" "errors" "fmt" - "log" "math/rand" "strings" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -53,20 +54,18 @@ type BabblerArc struct { } func New(b bot.Bot) *BabblerPlugin { - log.SetFlags(log.LstdFlags | log.Lshortfile) - if _, err := b.DB().Exec(`create table if not exists babblers ( id integer primary key, babbler string );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } if _, err := b.DB().Exec(`create table if not exists babblerWords ( id integer primary key, word string );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } if _, err := b.DB().Exec(`create table if not exists babblerNodes ( @@ -76,7 +75,7 @@ func New(b bot.Bot) *BabblerPlugin { root integer, rootFrequency integer );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } if _, err := b.DB().Exec(`create table if not exists babblerArcs ( @@ -85,7 +84,7 @@ func New(b bot.Bot) *BabblerPlugin { toNodeId interger, frequency integer );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } plugin := &BabblerPlugin{ @@ -167,7 +166,7 @@ func (p *BabblerPlugin) makeBabbler(name string) (*Babbler, error) { if err == nil { id, err := res.LastInsertId() if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } return &Babbler{ @@ -183,11 +182,10 @@ func (p *BabblerPlugin) getBabbler(name string) (*Babbler, error) { err := p.db.QueryRowx(`select * from babblers where babbler = ? LIMIT 1;`, name).StructScan(&bblr) if err != nil { if err == sql.ErrNoRows { - log.Printf("failed to find babbler") + log.Error().Msg("failed to find babbler") return nil, NO_BABBLER } - log.Printf("encountered problem in babbler lookup") - log.Print(err) + log.Error().Err(err).Msg("encountered problem in babbler lookup") return nil, err } return &bblr, nil @@ -198,13 +196,13 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) { if err == NO_BABBLER { babbler, err = p.makeBabbler(name) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } rows, err := p.db.Queryx(fmt.Sprintf("select tidbit from factoid where fact like '%s quotes';", babbler.Name)) if err != nil { - log.Print(err) + log.Error().Err(err) return babbler, nil } defer rows.Close() @@ -214,10 +212,10 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) { var tidbit string err := rows.Scan(&tidbit) - log.Print(tidbit) + log.Debug().Str("tidbit", tidbit) if err != nil { - log.Print(err) + log.Error().Err(err) return babbler, err } tidbits = append(tidbits, tidbit) @@ -225,7 +223,7 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) { for _, tidbit := range tidbits { if err = p.addToMarkovChain(babbler, tidbit); err != nil { - log.Print(err) + log.Error().Err(err) } } } @@ -247,12 +245,12 @@ func (p *BabblerPlugin) getWord(word string) (*BabblerWord, error) { func (p *BabblerPlugin) createNewWord(word string) (*BabblerWord, error) { res, err := p.db.Exec(`insert into babblerWords (word) values (?);`, word) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } id, err := res.LastInsertId() if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } return &BabblerWord{ @@ -266,7 +264,7 @@ func (p *BabblerPlugin) getOrCreateWord(word string) (*BabblerWord, error) { return p.createNewWord(word) } else { if err != nil { - log.Print(err) + log.Error().Err(err) } return w, err } @@ -292,19 +290,19 @@ func (p *BabblerPlugin) getBabblerNode(babbler *Babbler, word string) (*BabblerN func (p *BabblerPlugin) createBabblerNode(babbler *Babbler, word string) (*BabblerNode, error) { w, err := p.getOrCreateWord(word) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } res, err := p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?, ?, 0, 0)`, babbler.BabblerId, w.WordId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } id, err := res.LastInsertId() if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } @@ -327,12 +325,12 @@ func (p *BabblerPlugin) getOrCreateBabblerNode(babbler *Babbler, word string) (* func (p *BabblerPlugin) incrementRootWordFrequency(babbler *Babbler, word string) (*BabblerNode, error) { node, err := p.getOrCreateBabblerNode(babbler, word) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } _, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + 1, root = 1 where id = ?;`, node.NodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } node.RootFrequency += 1 @@ -354,7 +352,7 @@ func (p *BabblerPlugin) getBabblerArc(fromNode, toNode *BabblerNode) (*BabblerAr func (p *BabblerPlugin) incrementWordArc(fromNode, toNode *BabblerNode) (*BabblerArc, error) { res, err := p.db.Exec(`update babblerArcs set frequency = frequency + 1 where fromNodeId = ? and toNodeId = ?;`, fromNode.NodeId, toNode.NodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } @@ -366,7 +364,7 @@ func (p *BabblerPlugin) incrementWordArc(fromNode, toNode *BabblerNode) (*Babble if affectedRows == 0 { res, err = p.db.Exec(`insert into babblerArcs (fromNodeId, toNodeId, frequency) values (?, ?, 1);`, fromNode.NodeId, toNode.NodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } } @@ -390,19 +388,19 @@ func (p *BabblerPlugin) addToMarkovChain(babbler *Babbler, phrase string) error curNode, err := p.incrementRootWordFrequency(babbler, words[0]) if err != nil { - log.Print(err) + log.Error().Err(err) return err } for i := 1; i < len(words); i++ { nextNode, err := p.getOrCreateBabblerNode(babbler, words[i]) if err != nil { - log.Print(err) + log.Error().Err(err) return err } _, err = p.incrementWordArc(curNode, nextNode) if err != nil { - log.Print(err) + log.Error().Err(err) return err } curNode = nextNode @@ -415,7 +413,7 @@ func (p *BabblerPlugin) addToMarkovChain(babbler *Babbler, phrase string) error func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *BabblerWord, error) { rows, err := p.db.Queryx(`select * from babblerNodes where babblerId = ? and root = 1;`, babbler.BabblerId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } defer rows.Close() @@ -427,7 +425,7 @@ func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *Ba var node BabblerNode err = rows.StructScan(&node) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } rootNodes = append(rootNodes, &node) @@ -446,21 +444,21 @@ func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *Ba var w BabblerWord err := p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } return node, &w, nil } } - log.Fatalf("shouldn't happen") - return nil, nil, errors.New("failed to find weighted root word") + log.Fatal().Msg("failed to find weighted root word") + return nil, nil, nil } func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode, *BabblerWord, error) { rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, fromNode.NodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } defer rows.Close() @@ -471,7 +469,7 @@ func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode var arc BabblerArc err = rows.StructScan(&arc) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } arcs = append(arcs, &arc) @@ -492,28 +490,28 @@ func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode var node BabblerNode err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.ToNodeId).StructScan(&node) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } var w BabblerWord err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } return &node, &w, nil } } - log.Fatalf("shouldn't happen") - return nil, nil, errors.New("failed to find weighted next word") + log.Fatal().Msg("failed to find weighted next word") + return nil, nil, nil } func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNode, *BabblerWord, bool, error) { rows, err := p.db.Queryx(`select * from babblerArcs where toNodeId = ?;`, toNode.NodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, false, err } defer rows.Close() @@ -524,7 +522,7 @@ func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNo var arc BabblerArc err = rows.StructScan(&arc) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, false, err } arcs = append(arcs, &arc) @@ -551,39 +549,39 @@ func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNo var node BabblerNode err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.FromNodeId).StructScan(&node) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, false, err } var w BabblerWord err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, false, err } return &node, &w, false, nil } } - log.Fatalf("shouldn't happen") - return nil, nil, false, errors.New("failed to find weighted previous word") + log.Fatal().Msg("failed to find weighted previous word") + return nil, nil, false, nil } func (p *BabblerPlugin) verifyPhrase(babbler *Babbler, phrase []string) (*BabblerNode, *BabblerNode, error) { curNode, err := p.getBabblerNode(babbler, phrase[0]) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } firstNode := curNode for i := 1; i < len(phrase); i++ { nextNode, err := p.getBabblerNode(babbler, phrase[i]) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } _, err = p.getBabblerArc(curNode, nextNode) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, nil, err } curNode = nextNode @@ -599,7 +597,7 @@ func (p *BabblerPlugin) babble(who string) (string, error) { func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, error) { babbler, err := p.getBabbler(babblerName) if err != nil { - log.Print(err) + log.Error().Err(err) return "", nil } @@ -610,14 +608,14 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e if len(seed) == 0 { curNode, curWord, err = p.getWeightedRootNode(babbler) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } words = append(words, curWord.Word) } else { _, curNode, err = p.verifyPhrase(babbler, seed) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } } @@ -625,7 +623,7 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e for { curNode, curWord, err = p.getWeightedNextWord(curNode) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } if curWord.Word == " " { @@ -644,12 +642,12 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoName, otherName string) error { intoNode, err := p.getOrCreateBabblerNode(intoBabbler, "<"+intoName+">") if err != nil { - log.Print(err) + log.Error().Err(err) return err } otherNode, err := p.getOrCreateBabblerNode(otherBabbler, "<"+otherName+">") if err != nil { - log.Print(err) + log.Error().Err(err) return err } @@ -657,7 +655,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa rows, err := p.db.Queryx("select * from babblerNodes where babblerId = ?;", otherBabbler.BabblerId) if err != nil { - log.Print(err) + log.Error().Err(err) return err } defer rows.Close() @@ -668,7 +666,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa var node BabblerNode err = rows.StructScan(&node) if err != nil { - log.Print(err) + log.Error().Err(err) return err } nodes = append(nodes, &node) @@ -684,12 +682,12 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa if node.Root > 0 { res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ?, root = 1 where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId) if err != nil { - log.Print(err) + log.Error().Err(err) } } else { res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ? where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId) if err != nil { - log.Print(err) + log.Error().Err(err) } } @@ -701,7 +699,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa if err != nil || rowsAffected == 0 { res, err = p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?,?,?,?) ;`, intoBabbler.BabblerId, node.WordId, node.Root, node.RootFrequency) if err != nil { - log.Print(err) + log.Error().Err(err) return err } } @@ -709,7 +707,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa var updatedNode BabblerNode err = p.db.QueryRowx(`select * from babblerNodes where babblerId = ? and wordId = ? LIMIT 1;`, intoBabbler.BabblerId, node.WordId).StructScan(&updatedNode) if err != nil { - log.Print(err) + log.Error().Err(err) return err } @@ -729,7 +727,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa var arc BabblerArc err = rows.StructScan(&arc) if err != nil { - log.Print(err) + log.Error().Err(err) return err } arcs = append(arcs, &arc) @@ -749,13 +747,13 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa func (p *BabblerPlugin) babbleSeedSuffix(babblerName string, seed []string) (string, error) { babbler, err := p.getBabbler(babblerName) if err != nil { - log.Print(err) + log.Error().Err(err) return "", nil } firstNode, curNode, err := p.verifyPhrase(babbler, seed) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } @@ -766,7 +764,7 @@ func (p *BabblerPlugin) babbleSeedSuffix(babblerName string, seed []string) (str for { curNode, curWord, shouldTerminate, err = p.getWeightedPreviousWord(curNode) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } @@ -795,7 +793,7 @@ func (p *BabblerPlugin) getNextArcs(babblerNodeId int64) ([]*BabblerArc, error) arcs := []*BabblerArc{} rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, babblerNodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return arcs, err } defer rows.Close() @@ -804,7 +802,7 @@ func (p *BabblerPlugin) getNextArcs(babblerNodeId int64) ([]*BabblerArc, error) var arc BabblerArc err = rows.StructScan(&arc) if err != nil { - log.Print(err) + log.Error().Err(err) return []*BabblerArc{}, err } arcs = append(arcs, &arc) @@ -816,7 +814,7 @@ func (p *BabblerPlugin) getBabblerNodeById(nodeId int64) (*BabblerNode, error) { var node BabblerNode err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, nodeId).StructScan(&node) if err != nil { - log.Print(err) + log.Error().Err(err) return nil, err } return &node, nil @@ -832,19 +830,19 @@ func shuffle(a []*BabblerArc) { func (p *BabblerPlugin) babbleSeedBookends(babblerName string, start, end []string) (string, error) { babbler, err := p.getBabbler(babblerName) if err != nil { - log.Print(err) + log.Error().Err(err) return "", nil } _, startWordNode, err := p.verifyPhrase(babbler, start) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } endWordNode, _, err := p.verifyPhrase(babbler, end) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } @@ -898,13 +896,13 @@ func (p *BabblerPlugin) babbleSeedBookends(babblerName string, start, end []stri for { cur, err := p.getBabblerNodeById(curSearchNode.babblerNodeId) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } var w BabblerWord err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, cur.WordId).StructScan(&w) if err != nil { - log.Print(err) + log.Error().Err(err) return "", err } words = append(words, w.Word) diff --git a/plugins/beers/beers.go b/plugins/beers/beers.go index 4e1640c..138d455 100644 --- a/plugins/beers/beers.go +++ b/plugins/beers/beers.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io/ioutil" - "log" "math/rand" "net/http" "strconv" @@ -15,6 +14,7 @@ import ( "time" "github.com/jmoiron/sqlx" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/plugins/counter" @@ -46,7 +46,7 @@ func New(b bot.Bot) *BeersPlugin { lastCheckin integer, chanNick string );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } p := &BeersPlugin{ Bot: b, @@ -147,13 +147,16 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf channel: channel, } - log.Println("Creating Untappd user:", u.untappdUser, "nick:", u.chanNick) + log.Info(). + Str("untappdUser", u.untappdUser). + Str("nick", u.chanNick). + Msg("Creating Untappd user") var count int err := p.db.QueryRow(`select count(*) from untappd where untappdUser = ?`, u.untappdUser).Scan(&count) if err != nil { - log.Println("Error registering untappd: ", err) + log.Error().Err(err).Msgf("Error registering untappd") } if count > 0 { p.Bot.Send(bot.Message, channel, "I'm already watching you.") @@ -171,7 +174,7 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf u.chanNick, ) if err != nil { - log.Println("Error registering untappd: ", err) + log.Error().Err(err).Msgf("Error registering untappd") p.Bot.Send(bot.Message, channel, "I can't see.") return true } @@ -184,7 +187,9 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf } if message.Command && parts[0] == "checkuntappd" { - log.Println("Checking untappd at request of user.") + log.Info(). + Str("user", message.User.Name). + Msgf("Checking untappd at request of user.") p.checkUntappd(channel) return true } @@ -210,7 +215,7 @@ func (p *BeersPlugin) setBeers(user string, amount int) { ub := getUserBeers(p.db, user) err := ub.Update(amount) if err != nil { - log.Println("Error saving beers: ", err) + log.Error().Err(err).Msgf("Error saving beers") } } @@ -218,7 +223,7 @@ func (p *BeersPlugin) addBeers(user string, delta int) { ub := getUserBeers(p.db, user) err := ub.UpdateDelta(delta) if err != nil { - log.Println("Error saving beers: ", err) + log.Error().Err(err).Msgf("Error saving beers") } } @@ -325,14 +330,14 @@ func (p *BeersPlugin) pullUntappd() ([]checkin, error) { } if resp.StatusCode == 500 { - log.Printf("Error querying untappd: %s, %s", resp.Status, body) + log.Error().Msgf("Error querying untappd: %s, %s", resp.Status, body) return []checkin{}, errors.New(resp.Status) } var beers Beers err = json.Unmarshal(body, &beers) if err != nil { - log.Println(err) + log.Error().Err(err) return []checkin{}, err } return beers.Response.Checkins.Items, nil @@ -341,31 +346,32 @@ func (p *BeersPlugin) pullUntappd() ([]checkin, error) { func (p *BeersPlugin) checkUntappd(channel string) { token := p.Bot.Config().Get("Untappd.Token", "NONE") if token == "NONE" { - log.Println(`Set config value "untappd.token" if you wish to enable untappd`) + log.Info(). + Msg(`Set config value "untappd.token" if you wish to enable untappd`) return } userMap := make(map[string]untappdUser) rows, err := p.db.Query(`select id, untappdUser, channel, lastCheckin, chanNick from untappd;`) if err != nil { - log.Println("Error getting untappd users: ", err) + log.Error().Err(err).Msg("Error getting untappd users") return } for rows.Next() { u := untappdUser{} err := rows.Scan(&u.id, &u.untappdUser, &u.channel, &u.lastCheckin, &u.chanNick) if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } userMap[u.untappdUser] = u if u.chanNick == "" { - log.Fatal("Empty chanNick for no good reason.") + log.Fatal().Msg("Empty chanNick for no good reason.") } } chks, err := p.pullUntappd() if err != nil { - log.Println("Untappd ERROR: ", err) + log.Error().Err(err).Msg("Untappd ERROR") return } for i := len(chks); i > 0; i-- { @@ -386,8 +392,9 @@ func (p *BeersPlugin) checkUntappd(channel string) { if !ok { continue } - log.Printf("user.chanNick: %s, user.untappdUser: %s, checkin.User.User_name: %s", - user.chanNick, user.untappdUser, checkin.User.User_name) + log.Debug(). + Msgf("user.chanNick: %s, user.untappdUser: %s, checkin.User.User_name: %s", + user.chanNick, user.untappdUser, checkin.User.User_name) p.addBeers(user.chanNick, 1) drunken := p.getBeers(user.chanNick) @@ -413,10 +420,13 @@ func (p *BeersPlugin) checkUntappd(channel string) { lastCheckin = ? where id = ?`, user.lastCheckin, user.id) if err != nil { - log.Println("UPDATE ERROR!:", err) + log.Error().Err(err).Msg("UPDATE ERROR!") } - log.Println("checkin id:", checkin.Checkin_id, "Message:", msg) + log.Debug(). + Int("checkin_id", checkin.Checkin_id). + Str("msg", msg). + Msg("checkin") p.Bot.Send(bot.Message, channel, msg) } } @@ -427,7 +437,7 @@ func (p *BeersPlugin) untappdLoop(channel string) { return } - log.Println("Checking every ", frequency, " seconds") + log.Info().Msgf("Checking every %v seconds", frequency) for { time.Sleep(time.Duration(frequency) * time.Second) diff --git a/plugins/counter/counter.go b/plugins/counter/counter.go index b7729cd..c7b62e5 100644 --- a/plugins/counter/counter.go +++ b/plugins/counter/counter.go @@ -5,12 +5,13 @@ package counter import ( "database/sql" "fmt" - "log" "math/rand" "regexp" "strconv" "strings" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -112,7 +113,7 @@ func GetItem(db *sqlx.DB, nick, itemName string) (Item, error) { if err := db.Get(&a, `select * from counter_alias where item=?`, itemName); err == nil { itemName = a.PointsTo } else { - log.Println(err, a) + log.Error().Err(err).Interface("alias", a) } err := db.Get(&item, `select * from counter where nick = ? and item= ?`, @@ -126,7 +127,11 @@ func GetItem(db *sqlx.DB, nick, itemName string) (Item, error) { default: return Item{}, err } - log.Printf("Got item %s.%s: %#v", nick, itemName, item) + log.Debug(). + Str("nick", nick). + Str("itemName", itemName). + Interface("item", item). + Msg("got item") return item, nil } @@ -153,7 +158,10 @@ func (i *Item) Update(value int) error { if i.ID == -1 { i.Create() } - log.Printf("Updating item: %#v, value: %d", i, value) + log.Debug(). + Interface("i", i). + Int("value", value). + Msg("Updating item") _, err := i.Exec(`update counter set count = ? where id = ?`, i.Count, i.ID) return err } @@ -212,7 +220,7 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte if len(parts) == 3 && strings.ToLower(parts[0]) == "mkalias" { if _, err := MkAlias(p.DB, parts[1], parts[2]); err != nil { - log.Println(err) + log.Error().Err(err) return false } p.Bot.Send(bot.Message, channel, fmt.Sprintf("Created alias %s -> %s", @@ -231,7 +239,7 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte its, err := cmd() if err != nil { - log.Println(err) + log.Error().Err(err) return false } else if len(its) == 0 { return false @@ -253,11 +261,14 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte } else if message.Command && message.Body == "reset me" { items, err := GetItems(p.DB, strings.ToLower(nick)) if err != nil { - log.Printf("Error getting items to reset %s: %s", nick, err) + log.Error(). + Err(err). + Str("nick", nick). + Msg("Error getting items to reset") p.Bot.Send(bot.Message, channel, "Something is technically wrong with your counters.") return true } - log.Printf("Items: %+v", items) + log.Debug().Msgf("Items: %+v", items) for _, item := range items { item.Delete() } @@ -272,11 +283,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte subject = strings.ToLower(parts[1]) } - log.Printf("Getting counter for %s", subject) + log.Debug(). + Str("subject", subject). + Msg("Getting counter") // pull all of the items associated with "subject" items, err := GetItems(p.DB, subject) if err != nil { - log.Fatalf("Error retrieving items for %s: %s", subject, err) + log.Error(). + Err(err). + Str("subject", subject). + Msg("Error retrieving items") p.Bot.Send(bot.Message, channel, "Something went wrong finding that counter;") return true } @@ -309,13 +325,21 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte it, err := GetItem(p.DB, subject, itemName) if err != nil { - log.Printf("Error getting item to remove %s.%s: %s", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error getting item to remove") p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;") return true } err = it.Delete() if err != nil { - log.Printf("Error removing item %s.%s: %s", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error removing item") p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;") return true } @@ -347,8 +371,11 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte subject, itemName)) return true case err != nil: - log.Printf("Error retrieving item count for %s.%s: %s", - subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error retrieving item count") return true } @@ -377,11 +404,15 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte // ++ those fuckers item, err := GetItem(p.DB, subject, itemName) if err != nil { - log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("error finding item") // Item ain't there, I guess return false } - log.Printf("About to update item: %#v", item) + log.Debug().Msgf("About to update item: %#v", item) item.UpdateDelta(1) p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, item.Count, item.Item)) @@ -390,7 +421,11 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte // -- those fuckers item, err := GetItem(p.DB, subject, itemName) if err != nil { - log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error finding item") // Item ain't there, I guess return false } @@ -417,12 +452,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte // += those fuckers item, err := GetItem(p.DB, subject, itemName) if err != nil { - log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error finding item") // Item ain't there, I guess return false } n, _ := strconv.Atoi(parts[2]) - log.Printf("About to update item by %d: %#v", n, item) + log.Debug().Msgf("About to update item by %d: %#v", n, item) item.UpdateDelta(n) p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, item.Count, item.Item)) @@ -431,12 +470,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte // -= those fuckers item, err := GetItem(p.DB, subject, itemName) if err != nil { - log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) + log.Error(). + Err(err). + Str("subject", subject). + Str("itemName", itemName). + Msg("Error finding item") // Item ain't there, I guess return false } n, _ := strconv.Atoi(parts[2]) - log.Printf("About to update item by -%d: %#v", n, item) + log.Debug().Msgf("About to update item by -%d: %#v", n, item) item.UpdateDelta(-n) p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, item.Count, item.Item)) @@ -469,11 +512,14 @@ func (p *CounterPlugin) checkMatch(message msg.Message) bool { // We will specifically allow :tea: to keep compatability item, err := GetItem(p.DB, nick, itemName) if err != nil || (item.Count == 0 && item.Item != ":tea:") { - log.Printf("Error finding item %s.%s: %s.", nick, itemName, err) + log.Error(). + Err(err). + Str("itemName", itemName). + Msg("Error finding item") // Item ain't there, I guess return false } - log.Printf("About to update item: %#v", item) + log.Debug().Msgf("About to update item: %#v", item) item.UpdateDelta(1) p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s... %s has %d %s", strings.Join(everyDayImShuffling([]string{"bleep", "bloop", "blop"}), "-"), nick, item.Count, itemName)) diff --git a/plugins/db/db.go b/plugins/db/db.go index 026bf76..a3799b9 100644 --- a/plugins/db/db.go +++ b/plugins/db/db.go @@ -2,11 +2,12 @@ package db import ( "fmt" - "log" "net/http" "os" "time" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/config" @@ -37,7 +38,7 @@ func (p *DBPlugin) serveQuery(w http.ResponseWriter, r *http.Request) { f, err := os.Open(p.bot.Config().DBFile) defer f.Close() if err != nil { - log.Printf("Error opening DB for web service: %s", err) + log.Error().Err(err).Msg("Error opening DB for web service") fmt.Fprintf(w, "Error opening DB") return } diff --git a/plugins/emojifyme/emojifyme.go b/plugins/emojifyme/emojifyme.go index 3419e4c..4a24d85 100644 --- a/plugins/emojifyme/emojifyme.go +++ b/plugins/emojifyme/emojifyme.go @@ -5,11 +5,12 @@ package emojifyme import ( "encoding/json" "io/ioutil" - "log" "math/rand" "net/http" "strings" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" ) @@ -23,12 +24,12 @@ type EmojifyMePlugin struct { func New(b bot.Bot) *EmojifyMePlugin { resp, err := http.Get("https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json") if err != nil { - log.Fatalf("Error generic emoji list: %s", err) + log.Fatal().Err(err).Msg("Error generic emoji list") } body, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { - log.Fatalf("Error generic emoji list body: %s", err) + log.Fatal().Err(err).Msg("Error generic emoji list body") } type Emoji struct { @@ -38,7 +39,7 @@ func New(b bot.Bot) *EmojifyMePlugin { var emoji []Emoji err = json.Unmarshal(body, &emoji) if err != nil { - log.Fatalf("Error parsing emoji list: %s", err) + log.Fatal().Err(err).Msg("Error parsing emoji list") } emojiMap := map[string]string{} diff --git a/plugins/fact/factoid.go b/plugins/fact/factoid.go index b4cc1d4..f7b25a5 100644 --- a/plugins/fact/factoid.go +++ b/plugins/fact/factoid.go @@ -6,13 +6,14 @@ import ( "database/sql" "fmt" "html/template" - "log" "math/rand" "net/http" "regexp" "strings" "time" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -166,7 +167,7 @@ func getFacts(db *sqlx.DB, fact string, tidbit string) ([]*Factoid, error) { rows, err := db.Query(query, "%"+fact+"%", "%"+tidbit+"%") if err != nil { - log.Printf("Error regexping for facts: %s", err) + log.Error().Err(err).Msg("Error regexping for facts") return nil, err } for rows.Next() { @@ -286,7 +287,7 @@ func New(botInst bot.Bot) *FactoidPlugin { accessed integer, count integer );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } if _, err := p.db.Exec(`create table if not exists factoid_alias ( @@ -294,7 +295,7 @@ func New(botInst bot.Bot) *FactoidPlugin { next string, primary key (fact, next) );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } for _, channel := range botInst.Config().GetArray("channels", []string{}) { @@ -359,10 +360,10 @@ func (p *FactoidPlugin) learnFact(message msg.Message, fact, verb, tidbit string where fact=? and verb=? and tidbit=?`, fact, verb, tidbit).Scan(&count) if err != nil { - log.Println("Error counting facts: ", err) + log.Error().Err(err).Msg("Error counting facts") return fmt.Errorf("What?") } else if count.Valid && count.Int64 != 0 { - log.Println("User tried to relearn a fact.") + log.Debug().Msg("User tried to relearn a fact.") return fmt.Errorf("Look, I already know that.") } @@ -378,7 +379,7 @@ func (p *FactoidPlugin) learnFact(message msg.Message, fact, verb, tidbit string p.LastFact = &n err = n.Save(p.db) if err != nil { - log.Println("Error inserting fact: ", err) + log.Error().Err(err).Msg("Error inserting fact") return fmt.Errorf("My brain is overheating.") } @@ -425,9 +426,10 @@ func (p *FactoidPlugin) sayFact(message msg.Message, fact Factoid) { fact.Count += 1 err := fact.Save(p.db) if err != nil { - log.Printf("Could not update fact.\n") - log.Printf("%#v\n", fact) - log.Println(err) + log.Error(). + Interface("fact", fact). + Err(err). + Msg("could not update fact") } p.LastFact = &fact } @@ -520,7 +522,10 @@ func (p *FactoidPlugin) forgetLastFact(message msg.Message) bool { err := p.LastFact.delete(p.db) if err != nil { - log.Println("Error removing fact: ", p.LastFact, err) + log.Error(). + Err(err). + Interface("LastFact", p.LastFact). + Msg("Error removing fact") } fmt.Printf("Forgot #%d: %s %s %s\n", p.LastFact.ID.Int64, p.LastFact.Fact, p.LastFact.Verb, p.LastFact.Tidbit) @@ -539,7 +544,11 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool { parts = strings.Split(userexp, "/") - log.Printf("changeFact: %s %s %#v", trigger, userexp, parts) + log.Debug(). + Str("trigger", trigger). + Str("userexp", userexp). + Strs("parts", parts). + Msg("changefact") if len(parts) == 4 { // replacement @@ -552,7 +561,10 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool { // replacement result, err := getFacts(p.db, trigger, parts[1]) if err != nil { - log.Println("Error getting facts: ", trigger, err) + log.Error(). + Err(err). + Str("trigger", trigger). + Msg("Error getting facts") } if userexp[len(userexp)-1] != 'g' { result = result[:1] @@ -578,7 +590,10 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool { // search for a factoid and print it result, err := getFacts(p.db, trigger, parts[1]) if err != nil { - log.Println("Error getting facts: ", trigger, err) + log.Error(). + Err(err). + Str("trigger", trigger). + Msg("Error getting facts") p.Bot.Send(bot.Message, message.Channel, "bzzzt") return true } @@ -626,7 +641,9 @@ func (p *FactoidPlugin) message(kind bot.Kind, message msg.Message, args ...inte } if strings.HasPrefix(strings.ToLower(message.Body), "alias") { - log.Printf("Trying to learn an alias: %s", message.Body) + log.Debug(). + Str("alias", message.Body). + Msg("Trying to learn an alias") m := strings.TrimPrefix(message.Body, "alias ") parts := strings.SplitN(m, "->", 2) if len(parts) != 2 { @@ -647,7 +664,7 @@ func (p *FactoidPlugin) message(kind bot.Kind, message msg.Message, args ...inte p.sayFact(message, *fact) return true } - log.Println("Got a nil fact.") + log.Debug().Msg("Got a nil fact.") } if strings.ToLower(message.Body) == "forget that" { @@ -721,7 +738,7 @@ func (p *FactoidPlugin) factTimer(channel string) { if success && tdelta > duration && earlier { fact := p.randomFact() if fact == nil { - log.Println("Didn't find a random fact to say") + log.Debug().Msg("Didn't find a random fact to say") continue } @@ -764,7 +781,7 @@ func (p *FactoidPlugin) serveQuery(w http.ResponseWriter, r *http.Request) { if e := r.FormValue("entry"); e != "" { entries, err := getFacts(p.db, e, "") if err != nil { - log.Println("Web error searching: ", err) + log.Error().Err(err).Msg("Web error searching") } context["Count"] = fmt.Sprintf("%d", len(entries)) context["Entries"] = entries @@ -772,10 +789,10 @@ func (p *FactoidPlugin) serveQuery(w http.ResponseWriter, r *http.Request) { } t, err := template.New("factoidIndex").Funcs(funcMap).Parse(factoidIndex) if err != nil { - log.Println(err) + log.Error().Err(err) } err = t.Execute(w, context) if err != nil { - log.Println(err) + log.Error().Err(err) } } diff --git a/plugins/first/first.go b/plugins/first/first.go index 88fcb47..c0a35b0 100644 --- a/plugins/first/first.go +++ b/plugins/first/first.go @@ -5,12 +5,12 @@ package first import ( "database/sql" "fmt" - "log" "regexp" "strings" "time" "github.com/jmoiron/sqlx" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" ) @@ -56,14 +56,19 @@ func New(b bot.Bot) *FirstPlugin { nick string );`) if err != nil { - log.Fatal("Could not create first table: ", err) + log.Fatal(). + Err(err). + Msg("Could not create first table") } - log.Println("First plugin initialized with day:", midnight(time.Now())) + log.Info().Msgf("First plugin initialized with day: %s", + midnight(time.Now())) first, err := getLastFirst(b.DB()) if err != nil { - log.Fatal("Could not initialize first plugin: ", err) + log.Fatal(). + Err(err). + Msg("Could not initialize first plugin") } fp := &FirstPlugin{ @@ -96,13 +101,14 @@ func getLastFirst(db *sqlx.DB) (*FirstEntry, error) { ) switch { case err == sql.ErrNoRows || !id.Valid: - log.Println("No previous first entries") + log.Info().Msg("No previous first entries") return nil, nil case err != nil: - log.Println("Error on first query row: ", err) + log.Warn().Err(err).Msg("Error on first query row") return nil, err } - log.Println(id, day, timeEntered, body, nick) + log.Debug().Msgf("id: %v day %v time %v body %v nick %v", + id, day, timeEntered, body, nick) return &FirstEntry{ id: id.Int64, day: time.Unix(day.Int64, 0), @@ -130,12 +136,18 @@ func (p *FirstPlugin) message(kind bot.Kind, message msg.Message, args ...interf // This bot does not reply to anything if p.First == nil && p.allowed(message) { - log.Printf("No previous first. Recording new first: %s", message.Body) + log.Debug(). + Str("body", message.Body). + Msg("No previous first. Recording new first") p.recordFirst(message) return false } else if p.First != nil { if isToday(p.First.time) && p.allowed(message) { - log.Printf("Recording first: %s - %v vs %v", message.Body, p.First.time, time.Now()) + log.Debug(). + Str("body", message.Body). + Time("t0", p.First.time). + Time("t1", time.Now()). + Msg("Recording first") p.recordFirst(message) return false } @@ -156,22 +168,31 @@ func (p *FirstPlugin) allowed(message msg.Message) bool { for _, msg := range p.Bot.Config().GetArray("Bad.Msgs", []string{}) { match, err := regexp.MatchString(msg, strings.ToLower(message.Body)) if err != nil { - log.Println("Bad regexp: ", err) + log.Error().Err(err).Msg("Bad regexp") } if match { - log.Println("Disallowing first: ", message.User.Name, ":", message.Body) + log.Info(). + Str("user", message.User.Name). + Str("body", message.Body). + Msg("Disallowing first") return false } } for _, host := range p.Bot.Config().GetArray("Bad.Hosts", []string{}) { if host == message.Host { - log.Println("Disallowing first: ", message.User.Name, ":", message.Body) + log.Info(). + Str("user", message.User.Name). + Str("body", message.Body). + Msg("Disallowing first") return false } } for _, nick := range p.Bot.Config().GetArray("Bad.Nicks", []string{}) { if nick == message.User.Name { - log.Println("Disallowing first: ", message.User.Name, ":", message.Body) + log.Info(). + Str("user", message.User.Name). + Str("body", message.Body). + Msg("Disallowing first") return false } } @@ -179,17 +200,20 @@ func (p *FirstPlugin) allowed(message msg.Message) bool { } func (p *FirstPlugin) recordFirst(message msg.Message) { - log.Println("Recording first: ", message.User.Name, ":", message.Body) + log.Info(). + Str("user", message.User.Name). + Str("body", message.Body). + Msg("Recording first") p.First = &FirstEntry{ day: midnight(time.Now()), time: message.Time, body: message.Body, nick: message.User.Name, } - log.Printf("recordFirst: %+v", p.First.day) + log.Info().Msgf("recordFirst: %+v", p.First.day) err := p.First.save(p.db) if err != nil { - log.Println("Error saving first entry: ", err) + log.Error().Err(err).Msg("Error saving first entry") return } p.announceFirst(message) diff --git a/plugins/inventory/inventory.go b/plugins/inventory/inventory.go index c13ac9e..b1fb2bf 100644 --- a/plugins/inventory/inventory.go +++ b/plugins/inventory/inventory.go @@ -6,10 +6,11 @@ package inventory import ( "fmt" - "log" "regexp" "strings" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -53,7 +54,7 @@ func New(b bot.Bot) *InventoryPlugin { );`) if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } b.Register(p, bot.Message, p.message) @@ -79,13 +80,13 @@ func (p *InventoryPlugin) itemFilter(input string) string { func (p *InventoryPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool { m := message.Body - log.Printf("inventory trying to read %+v", message) + log.Debug().Msgf("inventory trying to read %+v", message) if message.Command { if strings.ToLower(m) == "inventory" { items := p.getAll() say := "I'm not holding anything" if len(items) > 0 { - log.Printf("I think I have more than 0 items: %+v, len(items)=%d", items, len(items)) + log.Debug().Msgf("I think I have more than 0 items: %+v, len(items)=%d", items, len(items)) say = fmt.Sprintf("I'm currently holding %s", strings.Join(items, ", ")) } p.bot.Send(bot.Message, message.Channel, say) @@ -95,30 +96,30 @@ func (p *InventoryPlugin) message(kind bot.Kind, message msg.Message, args ...in // Bucket[:,] take this (.+) // Bucket[:,] have a (.+) if matches := p.r1.FindStringSubmatch(m); len(matches) > 0 { - log.Printf("Found item to add: %s", matches[1]) + log.Debug().Msgf("Found item to add: %s", matches[1]) return p.addItem(message, matches[1]) } if matches := p.r2.FindStringSubmatch(m); len(matches) > 0 { - log.Printf("Found item to add: %s", matches[1]) + log.Debug().Msgf("Found item to add: %s", matches[1]) return p.addItem(message, matches[1]) } } if message.Action { - log.Println("Inventory found an action") + log.Debug().Msg("Inventory found an action") // * Randall puts (.+) in Bucket([^a-zA-Z].*)? // * Randall gives Bucket (.+) // * Randall gives (.+) to Bucket([^a-zA-Z].*)? if matches := p.r3.FindStringSubmatch(m); len(matches) > 0 { - log.Printf("Found item to add: %s", matches[1]) + log.Debug().Msgf("Found item to add: %s", matches[1]) return p.addItem(message, matches[1]) } if matches := p.r4.FindStringSubmatch(m); len(matches) > 0 { - log.Printf("Found item to add: %s", matches[1]) + log.Debug().Msgf("Found item to add: %s", matches[1]) return p.addItem(message, matches[1]) } if matches := p.r5.FindStringSubmatch(m); len(matches) > 0 { - log.Printf("Found item to add: %s", matches[1]) + log.Debug().Msgf("Found item to add: %s", matches[1]) return p.addItem(message, matches[1]) } } @@ -131,12 +132,12 @@ func (p *InventoryPlugin) removeRandom() string { &name, ) if err != nil { - log.Printf("Error finding random entry: %s", err) + log.Error().Err(err).Msgf("Error finding random entry") return "IAMERROR" } _, err = p.Exec(`delete from inventory where item=?`, name) if err != nil { - log.Printf("Error finding random entry: %s", err) + log.Error().Err(err).Msgf("Error finding random entry") return "IAMERROR" } return name @@ -146,7 +147,7 @@ func (p *InventoryPlugin) count() int { var output int err := p.QueryRow(`select count(*) as count from inventory`).Scan(&output) if err != nil { - log.Printf("Error checking for item: %s", err) + log.Error().Err(err).Msg("Error checking for item") return -1 } return output @@ -158,7 +159,7 @@ func (p *InventoryPlugin) random() string { &name, ) if err != nil { - log.Printf("Error finding random entry: %s", err) + log.Error().Err(err).Msg("Error finding random entry") return "IAMERROR" } return name @@ -167,7 +168,7 @@ func (p *InventoryPlugin) random() string { func (p *InventoryPlugin) getAll() []string { rows, err := p.Queryx(`select item from inventory`) if err != nil { - log.Printf("Error getting all items: %s", err) + log.Error().Err(err).Msg("Error getting all items") return []string{} } output := []string{} @@ -184,7 +185,7 @@ func (p *InventoryPlugin) exists(i string) bool { var output int err := p.QueryRow(`select count(*) as count from inventory where item=?`, i).Scan(&output) if err != nil { - log.Printf("Error checking for item: %s", err) + log.Error().Err(err).Msg("Error checking for item") return false } return output > 0 @@ -193,7 +194,7 @@ func (p *InventoryPlugin) exists(i string) bool { func (p *InventoryPlugin) remove(i string) { _, err := p.Exec(`delete from inventory where item=?`, i) if err != nil { - log.Printf("Error inserting new inventory item: %s", err) + log.Error().Msg("Error inserting new inventory item") } } @@ -209,7 +210,7 @@ func (p *InventoryPlugin) addItem(m msg.Message, i string) bool { } _, err := p.Exec(`INSERT INTO inventory (item) values (?)`, i) if err != nil { - log.Printf("Error inserting new inventory item: %s", err) + log.Error().Err(err).Msg("Error inserting new inventory item") } if removed != "" { p.bot.Send(bot.Action, m.Channel, fmt.Sprintf("dropped %s and took %s from %s", removed, i, m.User.Name)) @@ -221,6 +222,6 @@ func (p *InventoryPlugin) addItem(m msg.Message, i string) bool { func checkerr(e error) { if e != nil { - log.Println(e) + log.Error().Err(e) } } diff --git a/plugins/remember/remember.go b/plugins/remember/remember.go index 820b5fa..67bad5d 100644 --- a/plugins/remember/remember.go +++ b/plugins/remember/remember.go @@ -2,10 +2,11 @@ package remember import ( "fmt" - "log" "strings" "time" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -52,14 +53,14 @@ func (p *RememberPlugin) message(kind bot.Kind, message msg.Message, args ...int snip := strings.Join(parts[2:], " ") for i := len(p.log[message.Channel]) - 1; i >= 0; i-- { entry := p.log[message.Channel][i] - log.Printf("Comparing %s:%s with %s:%s", + log.Debug().Msgf("Comparing %s:%s with %s:%s", entry.User.Name, entry.Body, nick, snip) if strings.ToLower(entry.User.Name) == strings.ToLower(nick) && strings.Contains( strings.ToLower(entry.Body), strings.ToLower(snip), ) { - log.Printf("Found!") + log.Debug().Msg("Found!") var msg string if entry.Action { @@ -80,11 +81,13 @@ func (p *RememberPlugin) message(kind bot.Kind, message msg.Message, args ...int Count: 0, } if err := fact.Save(p.db); err != nil { - log.Println("ERROR!!!!:", err) + log.Error().Err(err) p.bot.Send(bot.Message, message.Channel, "Tell somebody I'm broke.") } - log.Println("Remembering factoid:", msg) + log.Info(). + Str("msg", msg). + Msg("Remembering factoid") // sorry, not creative with names so we're reusing msg msg = fmt.Sprintf("Okay, %s, remembering '%s'.", @@ -134,7 +137,7 @@ func (p *RememberPlugin) randQuote() string { &f.Count, ) if err != nil { - log.Println("Error getting quotes: ", err) + log.Error().Err(err).Msg("Error getting quotes") return "I had a problem getting your quote." } f.Created = time.Unix(tmpCreated, 0) @@ -144,6 +147,6 @@ func (p *RememberPlugin) randQuote() string { } func (p *RememberPlugin) recordMsg(message msg.Message) { - log.Printf("Logging message: %s: %s", message.User.Name, message.Body) + log.Debug().Msgf("Logging message: %s: %s", message.User.Name, message.Body) p.log[message.Channel] = append(p.log[message.Channel], message) } diff --git a/plugins/reminder/reminder.go b/plugins/reminder/reminder.go index 715ba68..cd6cd58 100644 --- a/plugins/reminder/reminder.go +++ b/plugins/reminder/reminder.go @@ -5,12 +5,13 @@ package reminder import ( "errors" "fmt" - "log" "strconv" "strings" "sync" "time" + "github.com/rs/zerolog/log" + "github.com/jmoiron/sqlx" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" @@ -39,7 +40,6 @@ type Reminder struct { } func New(b bot.Bot) *ReminderPlugin { - log.SetFlags(log.LstdFlags | log.Lshortfile) if _, err := b.DB().Exec(`create table if not exists reminders ( id integer primary key, fromWho string, @@ -48,7 +48,7 @@ func New(b bot.Bot) *ReminderPlugin { remindWhen string, channel string );`); err != nil { - log.Fatal(err) + log.Fatal().Err(err) } dur, _ := time.ParseDuration("1h") @@ -205,7 +205,7 @@ func (p *ReminderPlugin) getNextReminder() *Reminder { defer p.mutex.Unlock() rows, err := p.db.Query("select id, fromWho, toWho, what, remindWhen, channel from reminders order by remindWhen asc limit 1;") if err != nil { - log.Print(err) + log.Error().Err(err) return nil } defer rows.Close() @@ -214,19 +214,19 @@ func (p *ReminderPlugin) getNextReminder() *Reminder { var reminder *Reminder for rows.Next() { if once { - log.Print("somehow got multiple rows") + log.Debug().Msg("somehow got multiple rows") } reminder = &Reminder{} var when string err := rows.Scan(&reminder.id, &reminder.from, &reminder.who, &reminder.what, &when, &reminder.channel) if err != nil { - log.Print(err) + log.Error().Err(err) return nil } reminder.when, err = time.Parse(TIMESTAMP, when) if err != nil { - log.Print(err) + log.Error().Err(err) return nil } @@ -243,7 +243,7 @@ func (p *ReminderPlugin) addReminder(reminder *Reminder) error { reminder.from, reminder.who, reminder.what, reminder.when.Format(TIMESTAMP), reminder.channel) if err != nil { - log.Print(err) + log.Error().Err(err) } return err } @@ -253,7 +253,7 @@ func (p *ReminderPlugin) deleteReminder(id int64) error { defer p.mutex.Unlock() res, err := p.db.Exec(`delete from reminders where id = ?;`, id) if err != nil { - log.Print(err) + log.Error().Err(err) } else { if affected, err := res.RowsAffected(); err != nil { return err @@ -275,7 +275,7 @@ func (p *ReminderPlugin) getRemindersFormatted(filter string) (string, error) { var total int err := p.db.Get(&total, countString) if err != nil { - log.Print(err) + log.Error().Err(err) return "", nil } @@ -285,7 +285,7 @@ func (p *ReminderPlugin) getRemindersFormatted(filter string) (string, error) { rows, err := p.db.Query(queryString) if err != nil { - log.Print(err) + log.Error().Err(err) return "", nil } defer rows.Close() @@ -348,9 +348,10 @@ func reminderer(p *ReminderPlugin) { p.Bot.Send(bot.Message, reminder.channel, message) if err := p.deleteReminder(reminder.id); err != nil { - log.Print(reminder.id) - log.Print(err) - log.Fatal("this will cause problems, we need to stop now.") + log.Error(). + Int64("id", reminder.id). + Err(err). + Msg("this will cause problems, we need to stop now.") } } diff --git a/plugins/sisyphus/sisyphus.go b/plugins/sisyphus/sisyphus.go index 31c3f02..6238596 100644 --- a/plugins/sisyphus/sisyphus.go +++ b/plugins/sisyphus/sisyphus.go @@ -2,12 +2,13 @@ package sisyphus import ( "fmt" - "log" "math/rand" "strconv" "strings" "time" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" ) @@ -192,7 +193,7 @@ func (p *SisyphusPlugin) replyMessage(kind bot.Kind, message msg.Message, args . if strings.ToLower(message.User.Name) != strings.ToLower(p.Bot.Config().Get("Nick", "bot")) { if g, ok := p.listenFor[identifier]; ok { - log.Printf("got message on %s: %+v", identifier, message) + log.Debug().Msgf("got message on %s: %+v", identifier, message) if g.ended { return false diff --git a/plugins/talker/talker.go b/plugins/talker/talker.go index 38153d9..3bba94f 100644 --- a/plugins/talker/talker.go +++ b/plugins/talker/talker.go @@ -5,12 +5,13 @@ package talker import ( "fmt" "io/ioutil" - "log" "net/http" "os" "os/exec" "strings" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/config" @@ -172,9 +173,9 @@ func (p *TalkerPlugin) allCows() []string { func (p *TalkerPlugin) registerWeb() { http.HandleFunc("/slash/cowsay", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() - log.Printf("Cowsay:\n%+v", r.PostForm.Get("text")) + log.Debug().Msgf("Cowsay:\n%+v", r.PostForm.Get("text")) channel := r.PostForm.Get("channel_id") - log.Printf("channel: %s", channel) + log.Debug().Msgf("channel: %s", channel) msg, err := p.cowSay(r.PostForm.Get("text")) if err != nil { p.Bot.Send(bot.Message, channel, fmt.Sprintf("Error running cowsay: %s", err)) diff --git a/plugins/twitch/twitch.go b/plugins/twitch/twitch.go index 3046709..37d8602 100644 --- a/plugins/twitch/twitch.go +++ b/plugins/twitch/twitch.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" "io/ioutil" - "log" "net/http" "net/url" "strings" "text/template" "time" + "github.com/rs/zerolog/log" "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" "github.com/velour/catbase/config" @@ -110,12 +110,12 @@ func (p *TwitchPlugin) serveStreaming(w http.ResponseWriter, r *http.Request) { t, err := template.New("streaming").Parse(page) if err != nil { - log.Println("Could not parse template!", err) + log.Error().Err(err).Msg("Could not parse template!") return } err = t.Execute(w, context) if err != nil { - log.Println("Could not execute template!", err) + log.Error().Err(err).Msg("Could not execute template!") } } @@ -154,11 +154,11 @@ func (p *TwitchPlugin) help(kind bot.Kind, message msg.Message, args ...interfac func (p *TwitchPlugin) twitchLoop(channel string) { frequency := p.config.GetInt("Twitch.Freq", 60) if p.config.Get("twitch.clientid", "") == "" || p.config.Get("twitch.authorization", "") == "" { - log.Println("Disabling twitch autochecking.") + log.Info().Msgf("Disabling twitch autochecking.") return } - log.Println("Checking every ", frequency, " seconds") + log.Info().Msgf("Checking every %d seconds", frequency) for { time.Sleep(time.Duration(frequency) * time.Second) @@ -193,14 +193,14 @@ func getRequest(url, clientID, authorization string) ([]byte, bool) { return body, true errCase: - log.Println(err) + log.Error().Err(err) return []byte{}, false } func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPrintStatus bool) { baseURL, err := url.Parse("https://api.twitch.tv/helix/streams") if err != nil { - log.Println("Error parsing twitch stream URL") + log.Error().Msg("Error parsing twitch stream URL") return } @@ -212,7 +212,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri cid := p.config.Get("Twitch.ClientID", "") auth := p.config.Get("Twitch.Authorization", "") if cid == auth && cid == "" { - log.Println("Twitch plugin not enabled.") + log.Info().Msgf("Twitch plugin not enabled.") return } @@ -224,7 +224,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri var s stream err = json.Unmarshal(body, &s) if err != nil { - log.Println(err) + log.Error().Err(err) return } @@ -254,7 +254,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri if gameID == "" { t, err := template.New("notStreaming").Parse(notStreamingTpl) if err != nil { - log.Println(err) + log.Error().Err(err) p.Bot.Send(bot.Message, channel, err) t = template.Must(template.New("notStreaming").Parse(notStreamingTplFallback)) } @@ -263,7 +263,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri } else { t, err := template.New("isStreaming").Parse(isStreamingTpl) if err != nil { - log.Println(err) + log.Error().Err(err) p.Bot.Send(bot.Message, channel, err) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) } @@ -274,7 +274,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri if twitcher.gameID != "" { t, err := template.New("stoppedStreaming").Parse(stoppedStreamingTpl) if err != nil { - log.Println(err) + log.Error().Err(err) p.Bot.Send(bot.Message, channel, err) t = template.Must(template.New("stoppedStreaming").Parse(stoppedStreamingTplFallback)) } @@ -286,7 +286,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri if twitcher.gameID != gameID { t, err := template.New("isStreaming").Parse(isStreamingTpl) if err != nil { - log.Println(err) + log.Error().Err(err) p.Bot.Send(bot.Message, channel, err) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) } diff --git a/plugins/zork/zork.go b/plugins/zork/zork.go index d2fda1b..95da698 100644 --- a/plugins/zork/zork.go +++ b/plugins/zork/zork.go @@ -8,12 +8,13 @@ import ( "bytes" "go/build" "io" - "log" "os/exec" "path/filepath" "strings" "sync" + "github.com/rs/zerolog/log" + "github.com/velour/catbase/bot" "github.com/velour/catbase/bot/msg" ) @@ -52,7 +53,7 @@ func (p *ZorkPlugin) runZork(ch string) error { var w io.WriteCloser cmd.Stdin, w = io.Pipe() - log.Printf("zork running %v\n", cmd) + log.Info().Msgf("zork running %v", cmd) if err := cmd.Start(); err != nil { w.Close() return err @@ -83,20 +84,20 @@ func (p *ZorkPlugin) runZork(ch string) error { }() go func() { if err := cmd.Wait(); err != nil { - log.Printf("zork exited: %v\n", err) + log.Error().Err(err).Msg("zork exited") } p.Lock() p.zorks[ch] = nil p.Unlock() }() - log.Printf("zork is running in %s\n", ch) + log.Info().Msgf("zork is running in %s\n", ch) p.zorks[ch] = w return nil } func (p *ZorkPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool { m := strings.ToLower(message.Body) - log.Printf("got message [%s]\n", m) + log.Debug().Msgf("got message [%s]", m) if ts := strings.Fields(m); len(ts) < 1 || ts[0] != "zork" { return false } @@ -111,7 +112,7 @@ func (p *ZorkPlugin) message(kind bot.Kind, message msg.Message, args ...interfa return true } } - log.Printf("zorking, [%s]\n", m) + log.Debug().Msgf("zorking, [%s]", m) io.WriteString(p.zorks[ch], m+"\n") return true } diff --git a/util/emojy/main.go b/util/emojy/main.go index b3aea9c..03c421c 100644 --- a/util/emojy/main.go +++ b/util/emojy/main.go @@ -5,12 +5,14 @@ import ( "flag" "io" "io/ioutil" - "log" "net/http" "net/url" "os" "path/filepath" "strings" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" ) var ( @@ -20,9 +22,10 @@ var ( func main() { flag.Parse() + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) if *token == "" { - log.Printf("No token provided.") + log.Fatal().Msg("No token provided.") return } @@ -35,7 +38,7 @@ func main() { func getFiles() map[string]string { files := fileResp{} - log.Printf("Getting files") + log.Debug().Msgf("Getting files") body := mkReq("https://slack.com/api/emoji.list", "token", *token, ) @@ -43,9 +46,9 @@ func getFiles() map[string]string { err := json.Unmarshal(body, &files) checkErr(err) - log.Printf("Ok: %v", files.Ok) + log.Debug().Msgf("Ok: %v", files.Ok) if !files.Ok { - log.Println(files) + log.Debug().Msgf("%+v", files) } return files.Files @@ -55,7 +58,7 @@ func downloadFile(n, f string) { url := strings.Replace(f, "\\", "", -1) // because fuck slack if strings.HasPrefix(url, "alias:") { - log.Printf("Skipping alias: %s", url) + log.Debug().Msgf("Skipping alias: %s", url) return } @@ -66,7 +69,7 @@ func downloadFile(n, f string) { fname := filepath.Join(*path, n+"."+ext) - log.Printf("Downloading from: %s", url) + log.Debug().Msgf("Downloading from: %s", url) client := &http.Client{} req, err := http.NewRequest("GET", url, nil) @@ -82,18 +85,18 @@ func downloadFile(n, f string) { defer out.Close() io.Copy(out, resp.Body) - log.Printf("Downloaded %s", f) + log.Debug().Msgf("Downloaded %s", f) } func checkErr(err error) { if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } } func mkReq(path string, arg ...string) []byte { if len(arg)%2 != 0 { - log.Fatal("Bad request arg number.") + log.Fatal().Msg("Bad request arg number.") } u, err := url.Parse(path) diff --git a/util/files/main.go b/util/files/main.go index 267c469..b7a87c3 100644 --- a/util/files/main.go +++ b/util/files/main.go @@ -5,13 +5,15 @@ import ( "flag" "io" "io/ioutil" - "log" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" ) var ( @@ -24,6 +26,7 @@ var ( func main() { flag.Parse() + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) for { files, count := getFiles() @@ -40,7 +43,7 @@ func main() { func getFiles() ([]slackFile, int) { files := fileResp{} - log.Printf("Getting files") + log.Debug().Msg("Getting files") body := mkReq("https://slack.com/api/files.list", "token", *token, "count", strconv.Itoa(*limit), @@ -50,9 +53,11 @@ func getFiles() ([]slackFile, int) { err := json.Unmarshal(body, &files) checkErr(err) - log.Printf("Ok: %v, Count: %d", files.Ok, files.Paging.Count) + log.Info(). + Int("count", files.Paging.Count). + Bool("ok", files.Ok) if !files.Ok { - log.Println(files) + log.Error().Interface("files", files) } return files.Files, files.Paging.Pages @@ -69,18 +74,24 @@ func deleteFile(f slackFile) { checkErr(err) if !del.Ok { - log.Println(body) - log.Fatal("Couldn't delete " + f.ID) + log.Fatal(). + Bytes("body", body). + Str("id", f.ID). + Msg("Couldn't delete") } - log.Printf("Deleted %s", f.ID) + log.Info(). + Str("id", f.ID). + Msg("Deleted") } func downloadFile(f slackFile) { url := strings.Replace(f.URLPrivateDownload, "\\", "", -1) // because fuck slack fname := filepath.Join(*path, f.ID+f.Name) - log.Printf("Downloading from: %s", url) + log.Info(). + Str("url", url). + Msg("Downloading") client := &http.Client{} req, err := http.NewRequest("GET", url, nil) @@ -96,18 +107,20 @@ func downloadFile(f slackFile) { defer out.Close() io.Copy(out, resp.Body) - log.Printf("Downloaded %s", f.ID) + log.Info(). + Str("id", f.ID). + Msg("Downloaded") } func checkErr(err error) { if err != nil { - log.Fatal(err) + log.Fatal().Err(err) } } func mkReq(path string, arg ...string) []byte { if len(arg)%2 != 0 { - log.Fatal("Bad request arg number.") + log.Fatal().Msg("Bad request arg number.") } u, err := url.Parse(path)