Skip to content

Commit

Permalink
use slog
Browse files Browse the repository at this point in the history
  • Loading branch information
totegamma committed Feb 1, 2024
1 parent 1ddf2ab commit 94086a3
Show file tree
Hide file tree
Showing 12 changed files with 215 additions and 67 deletions.
7 changes: 3 additions & 4 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func main() {
}

// Migrate the schema
log.Println("start migrate")
slog.Info("start migrate")
db.AutoMigrate(
&core.Message{},
&core.Character{},
Expand Down Expand Up @@ -172,7 +172,6 @@ func main() {
}

mc := memcache.New(config.Server.MemcachedAddr)
log.Println("config.Server.MemcachedAddr", config.Server.MemcachedAddr)
if err != nil {
panic("failed to connect memcached")
}
Expand Down Expand Up @@ -321,7 +320,7 @@ func main() {
time.Sleep(15 * time.Second)
subscriptions, err := streamService.ListStreamSubscriptions(context.Background())
if err != nil {
log.Println("failed to list stream subscriptions", err)
slog.Error(fmt.Sprintf("failed to list stream subscriptions: %v", err))
continue
}
for stream, count := range subscriptions {
Expand Down Expand Up @@ -371,7 +370,7 @@ func setupTraceProvider(endpoint string, serviceName string, serviceVersion stri
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := tracerProvider.Shutdown(ctx); err != nil {
log.Printf("Failed to shutdown tracer provider: %v", err)
slog.Error(fmt.Sprintf("Failed to shutdown tracer provider: %v", err))
}
}
return cleanup, nil
Expand Down
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"@concurrent-world/client": "^4.1.2",
"@concurrent-world/client": "^4.1.4",
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.11.16",
Expand Down
8 changes: 4 additions & 4 deletions web/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion web/src/context/apiContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default function ApiProvider(props: ApiProviderProps): JSX.Element {

const setJWT = useMemo(() => (jwt: string) => {
setToken(jwt)
setApi(new Api({host: '', token: jwt}))
setApi(new Api({host: location.host, token: jwt}))
}, [setApi])

const apiContextState = useMemo(() => ({
Expand Down
2 changes: 1 addition & 1 deletion web/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const Home = (): JSX.Element => {

useEffect(() => {
if (!ccid) return
api.readEntity(ccid).then((entity) => {
api.getEntity(ccid).then((entity) => {
setTag(entity?.tag.split(',') ?? [])
})
}, [api])
Expand Down
27 changes: 21 additions & 6 deletions x/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package agent
import (
"context"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"github.com/redis/go-redis/v9"
"github.com/totegamma/concurrent/x/core"
Expand All @@ -13,7 +14,7 @@ import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"io"
"log"
"log/slog"
"math/rand"
"net/http"
"strconv"
Expand Down Expand Up @@ -62,7 +63,7 @@ func (a *agent) collectUsers(ctx context.Context) {

// Boot starts agent
func (a *agent) Boot() {
log.Printf("agent start!")
slog.Info("agent start!")
ticker60 := time.NewTicker(60 * time.Second)
go func() {
for {
Expand Down Expand Up @@ -118,7 +119,11 @@ func (a *agent) pullRemoteEntities(ctx context.Context, remote core.Domain) erro
err := json.Unmarshal([]byte(entity.Payload), &signedObj)
if err != nil {
span.RecordError(err)
log.Println(err)
slog.Error(
"pullRemoteEntities",
slog.String("error", err.Error()),
slog.String("module", "agent"),
)
continue
}

Expand All @@ -134,16 +139,26 @@ func (a *agent) pullRemoteEntities(ctx context.Context, remote core.Domain) erro

if err != nil {
span.RecordError(err)
slog.Error(
"pullRemoteEntities",
slog.String("error", err.Error()),
slog.String("module", "agent"),
)
errored = true
log.Println(err)
}
}

if !errored {
log.Printf("[agent] pulled %d entities from %s", len(remoteEntities.Content), remote.ID)
slog.Info(
fmt.Sprintf("[agent] pulled %d entities from %s", len(remoteEntities.Content), remote.ID),
slog.String("module", "agent"),
)
a.domain.UpdateScrapeTime(ctx, remote.ID, requestTime)
} else {
log.Printf("[agent] failed to pull entities from %s", remote.ID)
slog.Error(
fmt.Sprintf("[agent] failed to pull entities from %s", remote.ID),
slog.String("module", "agent"),
)
}

return nil
Expand Down
8 changes: 4 additions & 4 deletions x/association/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log"
"log/slog"

"github.com/totegamma/concurrent/x/core"
"github.com/totegamma/concurrent/x/message"
Expand Down Expand Up @@ -112,8 +112,8 @@ func (s *service) PostAssociation(ctx context.Context, objectStr string, signatu
for _, stream := range association.Streams {
err = s.stream.PostItem(ctx, stream, item, created)
if err != nil {
slog.ErrorContext(ctx, "failed to post stream", slog.String("error", err.Error()), slog.String("module", "association"))
span.RecordError(err)
log.Printf("fail to post stream: %v", err)
}
}

Expand All @@ -128,8 +128,8 @@ func (s *service) PostAssociation(ctx context.Context, objectStr string, signatu
err = s.stream.DistributeEvent(ctx, postto, event)

if err != nil {
slog.ErrorContext(ctx, "failed to publish message to Redis", slog.String("error", err.Error()), slog.String("module", "association"))
span.RecordError(err)
log.Printf("fail to publish message to Redis: %v", err)
}
}

Expand Down Expand Up @@ -181,7 +181,7 @@ func (s *service) Delete(ctx context.Context, id string) (core.Association, erro
}
err := s.stream.DistributeEvent(ctx, posted, event)
if err != nil {
log.Printf("fail to publish message to Redis: %v", err)
slog.ErrorContext(ctx, "failed to publish message to Redis", slog.String("error", err.Error()), slog.String("module", "association"))
span.RecordError(err)
return deleted, err
}
Expand Down
6 changes: 4 additions & 2 deletions x/message/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package message
import (
"context"
"encoding/json"
"log"
"fmt"
"log/slog"

"github.com/redis/go-redis/v9"
"github.com/totegamma/concurrent/x/core"
Expand Down Expand Up @@ -111,7 +112,8 @@ func (s *service) Delete(ctx context.Context, id string) (core.Message, error) {
defer span.End()

deleted, err := s.repo.Delete(ctx, id)
log.Printf("deleted: %v", deleted)
slog.DebugContext(ctx, fmt.Sprintf("deleted: %v", deleted), slog.String("module", "message"))

if err != nil {
span.RecordError(err)
return core.Message{}, err
Expand Down
53 changes: 44 additions & 9 deletions x/socket/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
package socket

import (
"fmt"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/redis/go-redis/v9"
"log"
"log/slog"
"net/http"
"sync"
)
Expand Down Expand Up @@ -50,8 +51,11 @@ func (h handler) send(ws *websocket.Conn, message string) error {
func (h handler) Connect(c echo.Context) error {
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
log.Println("Failed to upgrade WebSocket:", err)
c.Logger().Error(err)
slog.Error(
"Failed to upgrade WebSocket",
slog.String("error", err.Error()),
slog.String("module", "socket"),
)
}
defer func() {
h.manager.Unsubscribe(ws)
Expand All @@ -70,13 +74,33 @@ func (h handler) Connect(c echo.Context) error {
for {
select {
case <-quit:
log.Println("[socket] closed")
slog.InfoContext(
ctx, "Socket closed",
slog.String("module", "socket"),
)
return
case msg := <-psch:
log.Printf("[socket] -> %s\n", msg.Payload[:64])

if msg == nil {
slog.WarnContext(
ctx, "received nil message",
slog.String("module", "socket"),
)
return
}

slog.DebugContext(
ctx, fmt.Sprintf("Socket message: %s", msg.Payload[:64]),
slog.String("module", "socket"),
)

err = h.send(ws, msg.Payload)
if err != nil {
log.Println("Error writing message: ", err)
slog.ErrorContext(
ctx, "Error writing message",
slog.String("error", err.Error()),
slog.String("module", "socket"),
)
return
}
}
Expand All @@ -87,20 +111,31 @@ func (h handler) Connect(c echo.Context) error {
var req Request
err := ws.ReadJSON(&req)
if err != nil {
log.Println("Error reading JSON: ", err)
slog.ErrorContext(
ctx, "Error reading JSON",
slog.String("error", err.Error()),
slog.String("module", "socket"),
)
break
}

if req.Type == "ping" {
err = h.send(ws, "{\"type\":\"pong\"}")
if err != nil {
log.Println("Error writing message: ", err)
slog.ErrorContext(
ctx, "Error writing message",
slog.String("error", err.Error()),
slog.String("module", "socket"),
)
break
}
continue
}

log.Printf("[socket] subscribe: %s\n", req.Channels)
slog.DebugContext(
ctx, fmt.Sprintf("Socket subscribe: %s", req.Channels),
slog.String("module", "socket"),
)
pubsub.Unsubscribe(ctx)
pubsub.Subscribe(ctx, req.Channels...)
h.manager.Subscribe(ws, req.Channels)
Expand Down
Loading

0 comments on commit 94086a3

Please sign in to comment.