Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit 3b488e3

Browse files
committed
feat: integrate logger into server, extras, socket, stripe, membership
1 parent 5499a39 commit 3b488e3

File tree

6 files changed

+71
-52
lines changed

6 files changed

+71
-52
lines changed

cmd/main.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@ import (
77

88
backend "github.com/staticbackendhq/core"
99
"github.com/staticbackendhq/core/config"
10+
"github.com/staticbackendhq/core/logger"
1011
)
1112

1213
func main() {
1314
c := config.LoadConfig()
1415

16+
log := logger.Get(c)
17+
1518
var v bool
1619
flag.BoolVar(&v, "v", false, "Display the version and build info")
1720
flag.Parse()
@@ -28,5 +31,5 @@ func main() {
2831
c.Port = "8099"
2932
}
3033

31-
backend.Start(c)
34+
backend.Start(c, log)
3235
}

extras.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,18 @@ import (
1313
"github.com/chromedp/chromedp"
1414
"github.com/staticbackendhq/core/extra"
1515
"github.com/staticbackendhq/core/internal"
16+
"github.com/staticbackendhq/core/logger"
1617
"github.com/staticbackendhq/core/middleware"
1718
"github.com/staticbackendhq/core/sms"
1819
)
1920

20-
type extras struct{}
21+
type extras struct {
22+
log *logger.Logger
23+
}
2124

2225
func (ex *extras) resizeImage(w http.ResponseWriter, r *http.Request) {
2326
if err := r.ParseMultipartForm(32 << 20); err != nil {
24-
fmt.Println("cannot parse form")
27+
ex.log.Error().Err(err).Msg("cannot parse form")
2528
http.Error(w, err.Error(), http.StatusBadRequest)
2629
return
2730
}
@@ -76,7 +79,8 @@ func (ex *extras) resizeImage(w http.ResponseWriter, r *http.Request) {
7679
)
7780

7881
resizedBytes := buf.Bytes()
79-
fmt.Println("resized bytes: ", len(resizedBytes))
82+
83+
ex.log.Info().Msgf("resized bytes: %d", len(resizedBytes))
8084
upData := internal.UploadFileData{FileKey: fileKey, File: bytes.NewReader(resizedBytes)}
8185
url, err := storer.Save(upData)
8286
if err != nil {

membership.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7-
"log"
87
"net/http"
98
"strings"
109
"time"
1110

1211
"github.com/staticbackendhq/core/internal"
12+
"github.com/staticbackendhq/core/logger"
1313
"github.com/staticbackendhq/core/middleware"
1414

1515
"golang.org/x/crypto/bcrypt"
@@ -19,6 +19,7 @@ import (
1919

2020
type membership struct {
2121
//volatile internal.Volatilizer
22+
log *logger.Logger
2223
}
2324

2425
func (m *membership) emailExists(w http.ResponseWriter, r *http.Request) {
@@ -114,7 +115,7 @@ func (m *membership) register(w http.ResponseWriter, r *http.Request) {
114115
conf, _, err := middleware.Extract(r, false)
115116
if err != nil {
116117
http.Error(w, "invalid StaticBackend key", http.StatusUnauthorized)
117-
log.Println("invalid StaticBackend key")
118+
m.log.Error().Err(err).Msg("invalid StaticBackend key")
118119
return
119120
}
120121

server.go

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"encoding/json"
77
"errors"
88
"fmt"
9-
"log"
109
"math/rand"
1110
"net/http"
1211
"os"
@@ -23,6 +22,7 @@ import (
2322
"github.com/staticbackendhq/core/email"
2423
"github.com/staticbackendhq/core/function"
2524
"github.com/staticbackendhq/core/internal"
25+
"github.com/staticbackendhq/core/logger"
2626
"github.com/staticbackendhq/core/middleware"
2727
"github.com/staticbackendhq/core/realtime"
2828
"github.com/staticbackendhq/core/storage"
@@ -53,19 +53,21 @@ func init() {
5353
}
5454

5555
// Start starts the web server and all dependencies services
56-
func Start(c config.AppConfig) {
56+
func Start(c config.AppConfig, log *logger.Logger) {
57+
log.Info().Str("Addr", c.AppURL).Msg("server started")
58+
5759
config.Current = c
5860

5961
stripe.Key = config.Current.StripeKey
6062

6163
if err := loadTemplates(); err != nil {
6264
// if we're running from the CLI, no need to load templates
6365
if len(config.Current.FromCLI) == 0 {
64-
log.Fatal("error loading templates: ", err)
66+
log.Fatal().Err(err).Msg("error loading templates")
6567
}
6668
}
6769

68-
initServices(c.DatabaseURL)
70+
initServices(c.DatabaseURL, log)
6971

7072
// websockets
7173
hub := newHub(volatile)
@@ -112,10 +114,11 @@ func Start(c config.AppConfig) {
112114
}
113115

114116
return key, nil
115-
}, volatile)
117+
}, volatile, log)
116118

117119
database := &Database{
118120
cache: volatile,
121+
log: log,
119122
}
120123

121124
stdPub := []middleware.Middleware{
@@ -138,7 +141,7 @@ func Start(c config.AppConfig) {
138141
middleware.RequireRoot(datastore),
139142
}
140143

141-
m := &membership{}
144+
m := &membership{log: log}
142145

143146
http.Handle("/login", middleware.Chain(http.HandlerFunc(m.login), pubWithDB...))
144147
http.Handle("/register", middleware.Chain(http.HandlerFunc(m.register), pubWithDB...))
@@ -149,7 +152,7 @@ func Start(c config.AppConfig) {
149152
http.Handle("/me", middleware.Chain(http.HandlerFunc(m.me), stdAuth...))
150153

151154
// oauth handlers
152-
el := &ExternalLogins{}
155+
el := &ExternalLogins{log: log}
153156
http.Handle("/oauth/login", middleware.Chain(el.login(), pubWithDB...))
154157
http.Handle("/oauth/callback/", middleware.Chain(el.callback(), stdPub...))
155158
http.Handle("/oauth/get-user", middleware.Chain(http.HandlerFunc(el.getUser), pubWithDB...))
@@ -179,19 +182,19 @@ func Start(c config.AppConfig) {
179182
http.Handle("/sudo/cache", middleware.Chain(http.HandlerFunc(sudoCache), stdRoot...))
180183

181184
// account
182-
acct := &accounts{membership: m}
185+
acct := &accounts{membership: m, log: log}
183186
http.Handle("/account/init", middleware.Chain(http.HandlerFunc(acct.create), stdPub...))
184187
http.Handle("/account/auth", middleware.Chain(http.HandlerFunc(acct.auth), stdRoot...))
185188
http.Handle("/account/portal", middleware.Chain(http.HandlerFunc(acct.portal), stdRoot...))
186189

187190
// stripe webhooks
188-
swh := stripeWebhook{}
191+
swh := stripeWebhook{log: log}
189192
http.HandleFunc("/stripe", swh.process)
190193

191194
http.HandleFunc("/ping", ping)
192195

193196
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
194-
serveWs(hub, w, r)
197+
serveWs(log, hub, w, r)
195198
})
196199

197200
http.Handle("/sse/connect", middleware.Chain(http.HandlerFunc(b.Accept), pubWithDB...))
@@ -219,7 +222,7 @@ func Start(c config.AppConfig) {
219222
http.Handle("/fn", middleware.Chain(http.HandlerFunc(f.list), stdRoot...))
220223

221224
// extras routes
222-
ex := &extras{}
225+
ex := &extras{log: log}
223226
http.Handle("/extra/resizeimg", middleware.Chain(http.HandlerFunc(ex.resizeImage), stdAuth...))
224227
http.Handle("/extra/sms", middleware.Chain(http.HandlerFunc(ex.sudoSendSMS), stdRoot...))
225228
http.Handle("/extra/htmltox", middleware.Chain(http.HandlerFunc(ex.htmlToX), stdAuth...))
@@ -233,7 +236,7 @@ func Start(c config.AppConfig) {
233236
}
234237

235238
// ui routes
236-
webUI := ui{}
239+
webUI := ui{log: log}
237240
http.HandleFunc("/ui/login", webUI.auth)
238241
http.Handle("/ui/logins", middleware.Chain(http.HandlerFunc(webUI.logins), stdRoot...))
239242
http.Handle("/ui/enable-login", middleware.Chain(http.HandlerFunc(webUI.enableExternalLogin), stdRoot...))
@@ -278,16 +281,16 @@ func Start(c config.AppConfig) {
278281
})
279282

280283
if err := g.Wait(); err != nil {
281-
fmt.Printf("exit reason: %s \n", err)
284+
log.Error().Err(err).Msg("exit reason")
282285
}
283286
}
284287

285-
func initServices(dbHost string) {
288+
func initServices(dbHost string, log *logger.Logger) {
286289

287290
if strings.EqualFold(dbHost, "mem") {
288291
volatile = cache.NewDevCache()
289292
} else {
290-
volatile = cache.NewCache()
293+
volatile = cache.NewCache(log)
291294
}
292295

293296
persister := config.Current.DataStore
@@ -296,16 +299,16 @@ func initServices(dbHost string) {
296299
} else if strings.EqualFold(persister, "mongo") {
297300
cl, err := openMongoDatabase(dbHost)
298301
if err != nil {
299-
log.Fatal(err)
302+
log.Fatal().Err(err).Msg("failed to create connection with mongodb")
300303
}
301-
datastore = mongo.New(cl, volatile.PublishDocument)
304+
datastore = mongo.New(cl, volatile.PublishDocument, log)
302305
} else {
303306
cl, err := openPGDatabase(dbHost)
304307
if err != nil {
305-
log.Fatal(err)
308+
log.Fatal().Err(err).Msg("failed to create connection with postgres")
306309
}
307310

308-
datastore = postgresql.New(cl, volatile.PublishDocument, "./sql/")
311+
datastore = postgresql.New(cl, volatile.PublishDocument, "./sql/", log)
309312
}
310313

311314
mp := config.Current.MailProvider
@@ -322,7 +325,7 @@ func initServices(dbHost string) {
322325
storer = storage.Local{}
323326
}
324327

325-
sub := &function.Subscriber{}
328+
sub := &function.Subscriber{Log: log}
326329
sub.PubSub = volatile
327330
sub.GetExecEnv = func(token string) (function.ExecutionEnvironment, error) {
328331
var exe function.ExecutionEnvironment
@@ -332,19 +335,19 @@ func initServices(dbHost string) {
332335
if strings.HasPrefix(token, "__tmp__experimental_public") {
333336
pk := strings.Replace(token, "__tmp__experimental_public_", "", -1)
334337
pairs := strings.Split(pk, "_")
335-
fmt.Println("checking for base in cache: ", pairs[0])
338+
log.Info().Msgf("checking for base in cache: %d", pairs[0])
336339
if err := volatile.GetTyped(pairs[0], &conf); err != nil {
337-
log.Println("cannot find base for public websocket")
340+
log.Error().Err(err).Msg("cannot find base for public websocket")
338341
return exe, err
339342
}
340343
} else if err := volatile.GetTyped("base:"+token, &conf); err != nil {
341-
log.Println("cannot find base")
344+
log.Error().Err(err).Msg("cannot find base")
342345
return exe, err
343346
}
344347

345348
var auth internal.Auth
346349
if err := volatile.GetTyped(token, &auth); err != nil {
347-
log.Println("cannot find auth")
350+
log.Error().Err(err).Msg("cannot find auth")
348351
return exe, err
349352
}
350353

@@ -359,6 +362,7 @@ func initServices(dbHost string) {
359362
// start system events subscriber
360363
go sub.Start()
361364
}
365+
362366
func openMongoDatabase(dbHost string) (*mongodrv.Client, error) {
363367
uri := dbHost
364368

socket.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package staticbackend
22

33
import (
4-
"log"
54
"net/http"
65
"time"
76

87
"github.com/staticbackendhq/core/internal"
8+
"github.com/staticbackendhq/core/logger"
99

1010
"github.com/google/uuid"
1111
"github.com/gorilla/websocket"
@@ -50,6 +50,8 @@ type Socket struct {
5050

5151
// unique socket identifier
5252
id string
53+
54+
log *logger.Logger
5355
}
5456

5557
// readPump pumps messages from the websocket connection to the hub.
@@ -69,7 +71,7 @@ func (c *Socket) readPump() {
6971
var msg internal.Command
7072
if err := c.conn.ReadJSON(&msg); err != nil {
7173
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
72-
log.Printf("error: %v", err)
74+
c.log.Error().Err(err).Msg("error")
7375
}
7476
break
7577
}
@@ -109,17 +111,17 @@ func (c *Socket) writePump() {
109111
}
110112

111113
// serveWs handles websocket requests from the peer.
112-
func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
114+
func serveWs(log *logger.Logger, hub *Hub, w http.ResponseWriter, r *http.Request) {
113115
conn, err := upgrader.Upgrade(w, r, nil)
114116
if err != nil {
115-
log.Println(err)
117+
log.Error().Err(err)
116118
return
117119
}
118120
id, err := uuid.NewUUID()
119121
if err != nil {
120-
log.Println(err)
122+
log.Error().Err(err)
121123
}
122-
sck := &Socket{hub: hub, conn: conn, send: make(chan internal.Command), id: id.String()}
124+
sck := &Socket{hub: hub, conn: conn, send: make(chan internal.Command), id: id.String(), log: log}
123125
sck.hub.register <- sck
124126

125127
// Allow collection of memory referenced by the caller by doing all work in

0 commit comments

Comments
 (0)