Skip to content

Commit

Permalink
Use slog
Browse files Browse the repository at this point in the history
  • Loading branch information
jlelse committed Dec 27, 2023
1 parent 5220c49 commit ad75360
Show file tree
Hide file tree
Showing 31 changed files with 247 additions and 245 deletions.
11 changes: 5 additions & 6 deletions activityPub.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
Expand Down Expand Up @@ -157,7 +156,7 @@ func (a *goBlog) apCheckMentions(p *post) {
links, err := allLinksFromHTML(pr, a.fullPostURL(p))
_ = pr.CloseWithError(err)
if err != nil {
log.Println("Failed to extract links from post: " + err.Error())
a.error("ActivityPub: Failed to extract links from post", err)
return
}
apc := a.apHttpClients[p.Blog]
Expand Down Expand Up @@ -486,12 +485,12 @@ func (a *goBlog) apUndelete(p *post) {

func (a *goBlog) apAccept(blogName string, blog *configBlog, follow *ap.Activity) {
newFollower := follow.Actor.GetLink()
log.Println("New follow request from follower id:", newFollower.String())
a.info("AcitivyPub: New follow request from follower", "id", newFollower.String())
// Get remote actor
follower, err := a.apGetRemoteActor(newFollower, blogName)
if err != nil || follower == nil {
// Couldn't retrieve remote actor info
log.Println("Failed to retrieve remote actor info:", newFollower)
a.error("ActivityPub: Failed to retrieve remote actor info", "actor", newFollower)
return
}
// Add or update follower
Expand Down Expand Up @@ -529,7 +528,7 @@ func (a *goBlog) apSendProfileUpdates() {
func (a *goBlog) apSendToAllFollowers(blog string, activity *ap.Activity, mentions ...string) {
inboxes, err := a.db.apGetAllInboxes(blog)
if err != nil {
log.Println("Failed to retrieve follower inboxes:", err.Error())
a.error("ActivityPub: Failed to retrieve follower inboxes", "err", err)
return
}
for _, m := range mentions {
Expand Down Expand Up @@ -583,7 +582,7 @@ func (a *goBlog) loadActivityPubPrivateKey() error {
if keyData, err := a.db.retrievePersistentCache("activitypub_key"); err == nil && keyData != nil {
privateKeyDecoded, _ := pem.Decode(keyData)
if privateKeyDecoded == nil {
log.Println("failed to decode cached private key")
a.error("ActivityPub: failed to decode cached private key")
// continue
} else {
key, err := x509.ParsePKCS1PrivateKey(privateKeyDecoded.Bytes)
Expand Down
5 changes: 2 additions & 3 deletions activityPubSending.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/gob"
"fmt"
"io"
"log"
"net/http"
"time"

Expand All @@ -26,7 +25,7 @@ func (a *goBlog) initAPSendQueue() {
a.listenOnQueue("ap", 30*time.Second, func(qi *queueItem, dequeue func(), reschedule func(time.Duration)) {
var r apRequest
if err := gob.NewDecoder(bytes.NewReader(qi.content)).Decode(&r); err != nil {
log.Println("activitypub queue:", err.Error())
a.error("Activitypub queue", "err", err)
dequeue()
return
}
Expand All @@ -40,7 +39,7 @@ func (a *goBlog) initAPSendQueue() {
bufferpool.Put(buf)
return
}
log.Println("AP request failed for the 20th time:", r.To)
a.info("AP request failed for the 20th time", "to", r.To)
_ = a.db.apRemoveInbox(r.To)
}
dequeue()
Expand Down
6 changes: 5 additions & 1 deletion app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"crypto/rsa"
"log/slog"
"net/http"
"sync"

Expand Down Expand Up @@ -66,8 +67,11 @@ type goBlog struct {
inLoad sync.Once
// IndieAuth
ias *indieauth.Server
// Logs
// Logs (HTTP)
logf *rotatelogs.RotateLogs
// Logs (Program)
logger *slog.Logger
logLevel *slog.LevelVar
// Markdown
md, absoluteMd, titleMd goldmark.Markdown
// Media
Expand Down
5 changes: 2 additions & 3 deletions blogroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"context"
"io"
"log"
"net/http"
"sort"
"strings"
Expand All @@ -25,7 +24,7 @@ func (a *goBlog) serveBlogroll(w http.ResponseWriter, r *http.Request) {
return a.getBlogrollOutlines(blog)
})
if err != nil {
log.Printf("Failed to get outlines: %v", err)
a.error("Blogroll: Failed to get outlines", "err", err)
a.serveError(w, r, "", http.StatusInternalServerError)
return
}
Expand All @@ -48,7 +47,7 @@ func (a *goBlog) serveBlogrollExport(w http.ResponseWriter, r *http.Request) {
return a.getBlogrollOutlines(blog)
})
if err != nil {
log.Printf("Failed to get outlines: %v", err)
a.error("Blogroll: Failed to get outlines", "err", err)
a.serveError(w, r, "", http.StatusInternalServerError)
return
}
Expand Down
3 changes: 1 addition & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"context"
"log"
"net/http"
"net/url"
"sort"
Expand Down Expand Up @@ -41,7 +40,7 @@ func (a *goBlog) initCache() (err error) {
ticker := time.NewTicker(15 * time.Minute)
for range ticker.C {
met := a.cache.c.Metrics
log.Println("\nCache:", met.String())
a.info("Cache metrics", "metrics", met.String())
}
}()
return
Expand Down
5 changes: 0 additions & 5 deletions captcha_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"encoding/base64"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
Expand Down Expand Up @@ -104,8 +103,6 @@ func Test_captchaMiddleware(t *testing.T) {
_, captchaSolved := session.Values["captcha"].(bool)
assert.False(t, captchaSolved)

log.Println("Captcha ID:", captchaId)

// Check form values
doc, err := goquery.NewDocumentFromReader(res.Body)
_ = res.Body.Close()
Expand Down Expand Up @@ -157,8 +154,6 @@ func Test_captchaMiddleware(t *testing.T) {
_, captchaSolved = session.Values["captcha"].(bool)
assert.False(t, captchaSolved)

log.Println("Captcha ID:", captchaId)

// Check form values
doc, err = goquery.NewDocumentFromReader(res.Body)
_ = res.Body.Close()
Expand Down
14 changes: 7 additions & 7 deletions check.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync/atomic"
Expand All @@ -27,24 +26,24 @@ func (a *goBlog) checkAllExternalLinks() error {
if err != nil {
return err
}
return a.checkLinks(log.Writer(), posts...)
return a.checkLinks(posts...)
}

func (a *goBlog) checkLinks(w io.Writer, posts ...*post) error {
func (a *goBlog) checkLinks(posts ...*post) error {
// Get all links
allLinks, err := a.allLinksToCheck(posts...)
if err != nil {
return err
}
// Print some info
fmt.Fprintln(w, "Checking", len(allLinks), "links")
fmt.Println("Checking", len(allLinks), "links")
// Cancel context
cancelContext, cancelFunc := context.WithCancel(context.Background())
var done atomic.Bool
a.shutdown.Add(func() {
done.Store(true)
cancelFunc()
fmt.Fprintln(w, "Cancelled link check")
fmt.Println("Cancelled link check")
})
// Create HTTP cache
cache, err := ristretto.NewCache(&ristretto.Config{
Expand Down Expand Up @@ -106,11 +105,12 @@ func (a *goBlog) checkLinks(w io.Writer, posts ...*post) error {
continue
}
if r.err != nil {
fmt.Fprintf(w, "%s in %s: %s\n", r.link, r.in, r.err.Error())
fmt.Printf("%s in %s: %s\n", r.link, r.in, r.err.Error())
} else if !successStatus(r.status) {
fmt.Fprintf(w, "%s in %s: %d (%s)\n", r.link, r.in, r.status, http.StatusText(r.status))
fmt.Printf("%s in %s: %d (%s)\n", r.link, r.in, r.status, http.StatusText(r.status))
}
}
fmt.Println("Finished link check")
return nil
}

Expand Down
5 changes: 3 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"errors"
"log"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -386,6 +385,8 @@ func (a *goBlog) initConfig(logging bool) error {
if a.cfg.initialized {
return nil
}
// Update log level
a.updateLogLevel()
// Init database
if err := a.initDatabase(logging); err != nil {
return err
Expand Down Expand Up @@ -561,7 +562,7 @@ func (a *goBlog) initConfig(logging bool) error {
}
// Log success
a.cfg.initialized = true
log.Println("Initialized configuration")
a.info("Initialized configuration")
return nil
}

Expand Down
3 changes: 1 addition & 2 deletions contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"fmt"
"log"
"net/http"
"time"

Expand Down Expand Up @@ -58,7 +57,7 @@ func (a *goBlog) sendContactSubmission(w http.ResponseWriter, r *http.Request) {
// Send submission
go func() {
if err := a.sendContactEmail(bc.Contact, message.String(), formEmail); err != nil {
log.Println(err.Error())
a.error("Failed to send contact email", "err", err)
}
}()
// Send notification
Expand Down
19 changes: 10 additions & 9 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"database/sql"
"errors"
"log"
"os"
"strings"
"sync"
Expand All @@ -17,6 +16,7 @@ import (
)

type database struct {
a *goBlog
// Basic things
db *sql.DB // database
em sync.Mutex // command execution (insert, update, delete ...)
Expand All @@ -35,7 +35,7 @@ func (a *goBlog) initDatabase(logging bool) (err error) {
return
}
if logging {
log.Println("Initialize database...")
a.info("Initialize database")
}
// Setup db
db, err := a.openDatabase(a.cfg.Db.File, logging)
Expand All @@ -46,9 +46,9 @@ func (a *goBlog) initDatabase(logging bool) (err error) {
a.db = db
a.shutdown.Add(func() {
if err := db.close(); err != nil {
log.Printf("Failed to close database: %v", err)
a.error("Failed to close database", "err", err)
} else {
log.Println("Closed database")
a.info("Closed database")
}
})
if a.cfg.Db.DumpFile != "" {
Expand All @@ -58,7 +58,7 @@ func (a *goBlog) initDatabase(logging bool) (err error) {
db.dump(a.cfg.Db.DumpFile)
}
if logging {
log.Println("Initialized database")
a.info("Initialized database")
}
return nil
}
Expand Down Expand Up @@ -116,7 +116,7 @@ func (a *goBlog) openDatabase(file string, logging bool) (*database, error) {
return nil, errors.New("sqlite not compiled with FTS5")
}
// Migrate DB
err = migrateDb(db, logging)
err = a.migrateDb(db, logging)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -144,6 +144,7 @@ func (a *goBlog) openDatabase(file string, logging bool) (*database, error) {
return nil, err
}
return &database{
a: a,
db: db,
debug: debug,
psc: psc,
Expand All @@ -163,11 +164,11 @@ func (db *database) dump(file string) {
// Dump database
f, err := os.Create(file)
if err != nil {
log.Println("Error while dump db:", err.Error())
db.a.error("Error while dump db", "err", err)
return
}
if err = sqlite3dump.DumpDB(db.db, f, sqlite3dump.WithTransaction(true)); err != nil {
log.Println("Error while dump db:", err.Error())
db.a.error("Error while dump db", "err", err)
}
}

Expand Down Expand Up @@ -202,7 +203,7 @@ func (db *database) prepare(query string, args ...any) (*sql.Stmt, []any, error)
})
if err != nil {
if db.debug {
log.Printf(`Failed to prepare query "%s": %s`, query, err.Error())
db.a.error("Failed to prepare query", "query", query, "err", err)
}
return nil, args, err
}
Expand Down
Loading

0 comments on commit ad75360

Please sign in to comment.