Skip to content
This repository has been archived by the owner on Nov 25, 2024. It is now read-only.

Replace logrus with zerolog #3132

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions appservice/appservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus"

appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/appservice/consumers"
"github.com/matrix-org/dendrite/appservice/query"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api"
log "github.com/rs/zerolog/log"
)

// NewInternalAPI returns a concerete implementation of the internal API. Callers
Expand Down Expand Up @@ -59,9 +59,7 @@ func NewInternalAPI(
for _, appservice := range cfg.Derived.ApplicationServices {
// Create bot account for this AS if it doesn't already exist
if err := generateAppServiceAccount(userAPI, appservice, cfg.Global.ServerName); err != nil {
logrus.WithFields(logrus.Fields{
"appservice": appservice.ID,
}).WithError(err).Panicf("failed to generate bot account for appservice")
log.Logger.Panic().Str("appservice", appservice.ID).Err(err).Msg("failed to generate bot account for appservice")
}
}

Expand All @@ -73,7 +71,7 @@ func NewInternalAPI(
js, rsAPI,
)
if err := consumer.Start(); err != nil {
logrus.WithError(err).Panicf("failed to start appservice roomserver consumer")
log.Panic().Err(err).Msg("failed to start appservice roomserver consumer")
}

return appserviceQueryAPI
Expand Down
22 changes: 8 additions & 14 deletions appservice/consumers/roomserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import (
"github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/dendrite/syncapi/synctypes"

log "github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"
)

// ApplicationServiceTransaction is the transaction that is sent off to an
Expand Down Expand Up @@ -104,7 +104,7 @@ func (s *OutputRoomEventConsumer) Start() error {
func (s *OutputRoomEventConsumer) onMessage(
ctx context.Context, state *appserviceState, msgs []*nats.Msg,
) bool {
log.WithField("appservice", state.ID).Tracef("Appservice worker received %d message(s) from roomserver", len(msgs))
log.Trace().Str("appservice", state.ID).Msgf("Appservice worker received %d message(s) from roomserver", len(msgs))
events := make([]*types.HeaderedEvent, 0, len(msgs))
for _, msg := range msgs {
// Only handle events we care about
Expand All @@ -116,7 +116,7 @@ func (s *OutputRoomEventConsumer) onMessage(
var output api.OutputEvent
if err := json.Unmarshal(msg.Data, &output); err != nil {
// If the message was invalid, log it and move on to the next message in the stream
log.WithField("appservice", state.ID).WithError(err).Errorf("Appservice failed to parse message, ignoring")
log.Error().Str("appservice", state.ID).Err(err).Msg("Appservice failed to parse message, ignoring")
continue
}
switch output.Type {
Expand All @@ -139,7 +139,7 @@ func (s *OutputRoomEventConsumer) onMessage(
}
if len(eventsReq.EventIDs) > 0 {
if err := s.rsAPI.QueryEventsByID(s.ctx, eventsReq, eventsRes); err != nil {
log.WithError(err).Errorf("s.rsAPI.QueryEventsByID failed")
log.Error().Err(err).Msg("s.rsAPI.QueryEventsByID failed")
return false
}
events = append(events, eventsRes.Events...)
Expand Down Expand Up @@ -167,7 +167,7 @@ func (s *OutputRoomEventConsumer) onMessage(

// Send event to any relevant application services. If we hit
// an error here, return false, so that we negatively ack.
log.WithField("appservice", state.ID).Debugf("Appservice worker sending %d events(s) from roomserver", len(events))
log.Debug().Str("appservice", state.ID).Msgf("Appservice worker sending %d events(s) from roomserver", len(events))
return s.sendEvents(ctx, state, events, txnID) == nil
}

Expand Down Expand Up @@ -223,7 +223,7 @@ func (s *appserviceState) backoffAndPause(err error) error {
s.backoff++
}
duration := time.Second * time.Duration(math.Pow(2, float64(s.backoff)))
log.WithField("appservice", s.ID).WithError(err).Errorf("Unable to send transaction to appservice, backing off for %s", duration.String())
log.Error().Str("appservice", s.ID).Err(err).Msgf("Unable to send transaction to appservice, backing off for %s", duration.String())
time.Sleep(duration)
return err
}
Expand Down Expand Up @@ -258,10 +258,7 @@ func (s *OutputRoomEventConsumer) appserviceIsInterestedInEvent(ctx context.Cont
}
}
} else {
log.WithFields(log.Fields{
"appservice": appservice.ID,
"room_id": event.RoomID(),
}).WithError(err).Errorf("Unable to get aliases for room")
log.Error().Str("appservice", appservice.ID).Str("room_id", event.RoomID()).Err(err).Msg("Unable to get aliases for room")
}

// Check if any of the members in the room match the appservice
Expand Down Expand Up @@ -303,10 +300,7 @@ func (s *OutputRoomEventConsumer) appserviceJoinedAtEvent(ctx context.Context, e
}
}
} else {
log.WithFields(log.Fields{
"appservice": appservice.ID,
"room_id": event.RoomID(),
}).WithError(err).Errorf("Unable to get membership for room")
log.Error().Str("appservice", appservice.ID).Str("room_id", event.RoomID()).Err(err).Msg("Unable to get membership for room")
}
return false
}
36 changes: 11 additions & 25 deletions appservice/query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
"strings"
"sync"

log "github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"

"github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/internal"
Expand Down Expand Up @@ -77,15 +77,12 @@ func (a *AppServiceQueryAPI) RoomAliasExists(
defer func() {
err = resp.Body.Close()
if err != nil {
log.WithFields(log.Fields{
"appservice_id": appservice.ID,
"status_code": resp.StatusCode,
}).WithError(err).Error("Unable to close application service response body")
log.Error().Err(err).Str("appservice_id", appservice.ID).Int("status_code", resp.StatusCode).Msg("Unable to close application service response body")
}
}()
}
if err != nil {
log.WithError(err).Errorf("Issue querying room alias on application service %s", appservice.ID)
log.Error().Err(err).Msgf("Issue querying room alias on application service %s", appservice.ID)
return err
}
switch resp.StatusCode {
Expand All @@ -97,10 +94,7 @@ func (a *AppServiceQueryAPI) RoomAliasExists(
// Room does not exist
default:
// Application service reported an error. Warn
log.WithFields(log.Fields{
"appservice_id": appservice.ID,
"status_code": resp.StatusCode,
}).Warn("Application service responded with non-OK status code")
log.Warn().Str("appservice_id", appservice.ID).Int("status_code", resp.StatusCode).Msg("Application service responded with non-OK status code")
}
}
}
Expand Down Expand Up @@ -141,17 +135,12 @@ func (a *AppServiceQueryAPI) UserIDExists(
defer func() {
err = resp.Body.Close()
if err != nil {
log.WithFields(log.Fields{
"appservice_id": appservice.ID,
"status_code": resp.StatusCode,
}).Error("Unable to close application service response body")
log.Error().Str("appservice_id", appservice.ID).Int("status_code", resp.StatusCode).Msg("Unable to close application service response body")
}
}()
}
if err != nil {
log.WithFields(log.Fields{
"appservice_id": appservice.ID,
}).WithError(err).Error("issue querying user ID on application service")
log.Error().Err(err).Str("appservice_id", appservice.ID).Msg("issue querying user ID on application service")
return err
}
if resp.StatusCode == http.StatusOK {
Expand All @@ -161,10 +150,7 @@ func (a *AppServiceQueryAPI) UserIDExists(
}

// Log non OK
log.WithFields(log.Fields{
"appservice_id": appservice.ID,
"status_code": resp.StatusCode,
}).Warn("application service responded with non-OK status code")
log.Warn().Str("appservice_id", appservice.ID).Int("status_code", resp.StatusCode).Msg("application service responded with non-OK status code")
}
}

Expand Down Expand Up @@ -217,7 +203,7 @@ func (a *AppServiceQueryAPI) Locations(
}

if err := requestDo[[]api.ASLocationResponse](as.HTTPClient, url+"?"+params.Encode(), &asLocations); err != nil {
log.WithError(err).Error("unable to get 'locations' from application service")
log.Error().Err(err).Msg("unable to get 'locations' from application service")
continue
}

Expand Down Expand Up @@ -252,7 +238,7 @@ func (a *AppServiceQueryAPI) User(
}

if err := requestDo[[]api.ASUserResponse](as.HTTPClient, url+"?"+params.Encode(), &asUsers); err != nil {
log.WithError(err).Error("unable to get 'user' from application service")
log.Error().Err(err).Msg("unable to get 'user' from application service")
continue
}

Expand Down Expand Up @@ -290,7 +276,7 @@ func (a *AppServiceQueryAPI) Protocols(
for _, as := range a.Cfg.Derived.ApplicationServices {
var proto api.ASProtocolResponse
if err := requestDo[api.ASProtocolResponse](as.HTTPClient, as.RequestUrl()+api.ASProtocolPath+req.Protocol, &proto); err != nil {
log.WithError(err).Error("unable to get 'protocol' from application service")
log.Error().Err(err).Msg("unable to get 'protocol' from application service")
continue
}

Expand Down Expand Up @@ -320,7 +306,7 @@ func (a *AppServiceQueryAPI) Protocols(
for _, p := range as.Protocols {
var proto api.ASProtocolResponse
if err := requestDo[api.ASProtocolResponse](as.HTTPClient, as.RequestUrl()+api.ASProtocolPath+p, &proto); err != nil {
log.WithError(err).Error("unable to get 'protocol' from application service")
log.Error().Err(err).Msg("unable to get 'protocol' from application service")
continue
}
existing, ok := response[p]
Expand Down
5 changes: 3 additions & 2 deletions clientapi/auth/user_interactive.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import (
"github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/util"
"github.com/sirupsen/logrus"
"github.com/tidwall/gjson"

log "github.com/rs/zerolog/log"
)

// Type represents an auth type
Expand Down Expand Up @@ -177,7 +178,7 @@ func (u *UserInteractive) challenge(sessionID string) *util.JSONResponse {
func (u *UserInteractive) NewSession() *util.JSONResponse {
sessionID, err := GenerateAccessToken()
if err != nil {
logrus.WithError(err).Error("failed to generate session ID")
log.Error().Err(err).Msg("failed to generate session ID")
res := jsonerror.InternalServerError()
return &res
}
Expand Down
4 changes: 2 additions & 2 deletions clientapi/jsonerror/jsonerror.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util"
"github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"
)

// MatrixError represents the "standard error response" in Matrix.
Expand Down Expand Up @@ -235,7 +235,7 @@ func NotTrusted(serverName string) *MatrixError {

// InternalAPIError is returned when Dendrite failed to reach an internal API.
func InternalAPIError(ctx context.Context, err error) util.JSONResponse {
logrus.WithContext(ctx).WithError(err).Error("Error reaching an internal API")
log.Error().Any("context", ctx).Err(err).Msg("Error reaching an internal API")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: &MatrixError{
Expand Down
16 changes: 6 additions & 10 deletions clientapi/producers/syncapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"

"github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/syncapi/types"
Expand Down Expand Up @@ -56,7 +56,7 @@ func (p *SyncAPIProducer) SendReceipt(
m.Header.Set("type", receiptType)
m.Header.Set("timestamp", fmt.Sprintf("%d", timestamp))

log.WithFields(log.Fields{}).Tracef("Producing to topic '%s'", p.TopicReceiptEvent)
log.Trace().Msgf("Producing to topic '%s'", p.TopicReceiptEvent)
_, err := p.JetStream.PublishMsg(m, nats.Context(ctx))
return err
}
Expand Down Expand Up @@ -91,11 +91,7 @@ func (p *SyncAPIProducer) SendToDevice(
devices = append(devices, deviceID)
}

log.WithFields(log.Fields{
"user_id": userID,
"num_devices": len(devices),
"type": eventType,
}).Tracef("Producing to topic '%s'", p.TopicSendToDeviceEvent)
log.Trace().Str("user_id", userID).Int("num_devices", len(devices)).Str("type", eventType).Msgf("Producing to topic '%s'", p.TopicSendToDeviceEvent)
for i, device := range devices {
ote := &types.OutputSendToDeviceEvent{
UserID: userID,
Expand All @@ -109,7 +105,7 @@ func (p *SyncAPIProducer) SendToDevice(

eventJSON, err := json.Marshal(ote)
if err != nil {
log.WithError(err).Error("sendToDevice failed json.Marshal")
log.Error().Err(err).Msg("sendToDevice failed json.Marshal")
return err
}
m := nats.NewMsg(p.TopicSendToDeviceEvent)
Expand All @@ -119,10 +115,10 @@ func (p *SyncAPIProducer) SendToDevice(

if _, err = p.JetStream.PublishMsg(m, nats.Context(ctx)); err != nil {
if i < len(devices)-1 {
log.WithError(err).Warn("sendToDevice failed to PublishMsg, trying further devices")
log.Warn().Err(err).Msg("sendToDevice failed to PublishMsg, trying further devices")
continue
}
log.WithError(err).Error("sendToDevice failed to PublishMsg for all devices")
log.Error().Err(err).Msg("sendToDevice failed to PublishMsg for all devices")
return err
}
}
Expand Down
15 changes: 6 additions & 9 deletions clientapi/routing/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util"
"github.com/nats-io/nats.go"
"github.com/sirupsen/logrus"

log "github.com/rs/zerolog/log"

"github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/internal/httputil"
Expand All @@ -40,7 +41,7 @@ func AdminEvacuateRoom(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAP
JSON: jsonerror.NotFound(err.Error()),
}
default:
logrus.WithError(err).WithField("roomID", vars["roomID"]).Error("Failed to evacuate room")
log.Error().Err(err).Str("roomID", vars["roomID"]).Msg("Failed to evacuate room")
return util.ErrorResponse(err)
}
return util.JSONResponse{
Expand All @@ -59,7 +60,7 @@ func AdminEvacuateUser(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAP

affected, err := rsAPI.PerformAdminEvacuateUser(req.Context(), vars["userID"])
if err != nil {
logrus.WithError(err).WithField("userID", vars["userID"]).Error("Failed to evacuate user")
log.Error().Err(err).Str("userID", vars["userID"]).Msg("Failed to evacuate user")
return util.MessageResponse(http.StatusBadRequest, err.Error())
}

Expand Down Expand Up @@ -169,7 +170,7 @@ func AdminResetPassword(req *http.Request, cfg *config.ClientAPI, device *api.De
func AdminReindex(req *http.Request, cfg *config.ClientAPI, device *api.Device, natsClient *nats.Conn) util.JSONResponse {
_, err := natsClient.RequestMsg(nats.NewMsg(cfg.Matrix.JetStream.Prefixed(jetstream.InputFulltextReindex)), time.Second*10)
if err != nil {
logrus.WithError(err).Error("failed to publish nats message")
log.Error().Err(err).Msg("failed to publish nats message")
return jsonerror.InternalServerError()
}
return util.JSONResponse{
Expand Down Expand Up @@ -238,11 +239,7 @@ func AdminDownloadState(req *http.Request, device *api.Device, rsAPI roomserverA
JSON: jsonerror.NotFound(eventutil.ErrRoomNoExists.Error()),
}
}
logrus.WithError(err).WithFields(logrus.Fields{
"userID": device.UserID,
"serverName": serverName,
"roomID": roomID,
}).Error("failed to download state")
log.Error().Err(err).Str("userID", device.UserID).Str("serverName", serverName).Str("roomID", roomID).Msg("failed to download state")
return util.ErrorResponse(err)
}
return util.JSONResponse{
Expand Down
2 changes: 1 addition & 1 deletion clientapi/routing/createroom.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
"github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util"
log "github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"
)

// https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-createroom
Expand Down
7 changes: 2 additions & 5 deletions clientapi/routing/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util"
"github.com/sirupsen/logrus"
log "github.com/rs/zerolog/log"
)

type newPasswordRequest struct {
Expand All @@ -37,10 +37,7 @@ func Password(
var r newPasswordRequest
r.LogoutDevices = true

logrus.WithFields(logrus.Fields{
"sessionId": device.SessionID,
"userId": device.UserID,
}).Debug("Changing password")
log.Debug().Int64("sessionId", device.SessionID).Str("userId", device.UserID).Msg("Changing password")

// Unmarshal the request.
resErr := httputil.UnmarshalJSONRequest(req, &r)
Expand Down
Loading