Skip to content

Commit

Permalink
feat(service): improve logs
Browse files Browse the repository at this point in the history
  • Loading branch information
ncarlier committed May 19, 2023
1 parent ce1af55 commit 2d2fb08
Show file tree
Hide file tree
Showing 7 changed files with 117 additions and 142 deletions.
50 changes: 25 additions & 25 deletions pkg/service/categories.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"github.com/ncarlier/readflow/pkg/model"
)

const unableToCreateCategoryErrorMsg = "unable to create category"

// GetCategories get categories from current user
func (reg *Registry) GetCategories(ctx context.Context) ([]model.Category, error) {
uid := getCurrentUserIDFromContext(ctx)
Expand Down Expand Up @@ -45,6 +47,8 @@ func (reg *Registry) GetCategory(ctx context.Context, id uint) (*model.Category,
func (reg *Registry) CreateCategory(ctx context.Context, form model.CategoryCreateForm) (*model.Category, error) {
uid := getCurrentUserIDFromContext(ctx)

logger := reg.logger.With().Uint("uid", uid).Logger()

// Validate user quota
plan, err := reg.GetCurrentUserPlan(ctx)
if err != nil {
Expand All @@ -53,30 +57,25 @@ func (reg *Registry) CreateCategory(ctx context.Context, form model.CategoryCrea
if plan != nil {
totalCategories, err := reg.CountCurrentUserCategories(ctx)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Msg("unable to create category")
logger.Info().Err(err).Msg(unableToCreateCategoryErrorMsg)
return nil, err
}
if totalCategories >= plan.TotalCategories {
err = ErrUserQuotaReached
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint(
"total", plan.TotalCategories,
).Msg("unable to create category")
logger.Info().Err(err).Uint("total", plan.TotalCategories).Msg(unableToCreateCategoryErrorMsg)
return nil, err
}
}
logger = logger.With().Str("title", form.Title).Logger()

// Create category
logger.Debug().Msg("creating category...")
result, err := reg.db.CreateCategoryForUser(uid, form)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Str("title", form.Title).Msg("unable to create category")
logger.Info().Err(err).Msg(unableToCreateCategoryErrorMsg)
return nil, err
}
logger.Info().Uint("id", *result.ID).Msg("category created")

return result, err
}
Expand All @@ -85,16 +84,16 @@ func (reg *Registry) CreateCategory(ctx context.Context, form model.CategoryCrea
func (reg *Registry) UpdateCategory(ctx context.Context, form model.CategoryUpdateForm) (*model.Category, error) {
uid := getCurrentUserIDFromContext(ctx)

logger := reg.logger.With().Uint("uid", uid).Uint("id", form.ID).Logger()

// Update category
logger.Debug().Msg("updating category...")
result, err := reg.db.UpdateCategoryForUser(uid, form)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Str("title", *form.Title).Uint(
"id", form.ID,
).Msg("unable to update category")
logger.Info().Err(err).Msg("unable to update category")
return nil, err
}
logger.Info().Msg("category updated")

return result, err
}
Expand All @@ -103,18 +102,20 @@ func (reg *Registry) UpdateCategory(ctx context.Context, form model.CategoryUpda
func (reg *Registry) DeleteCategory(ctx context.Context, id uint) (*model.Category, error) {
uid := getCurrentUserIDFromContext(ctx)

logger := reg.logger.With().Uint("uid", uid).Uint("id", id).Logger()

category, err := reg.GetCategory(ctx, id)
if err != nil {
return nil, err
}

logger.Debug().Msg("deleting category...")
err = reg.db.DeleteCategoryByUser(uid, id)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint("id", id).Msg("unable to delete category")
logger.Info().Err(err).Msg("unable to delete category")
return nil, err
}
logger.Info().Msg("category deleted")

return category, nil
}
Expand All @@ -124,16 +125,15 @@ func (reg *Registry) DeleteCategories(ctx context.Context, ids []uint) (int64, e
uid := getCurrentUserIDFromContext(ctx)
idsStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(ids)), ","), "[]")

logger := reg.logger.With().Uint("uid", uid).Str("ids", idsStr).Logger()

logger.Debug().Msg("deleting categories...")
nb, err := reg.db.DeleteCategoriesByUser(uid, ids)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Str("ids", idsStr).Msg("unable to delete categories")
logger.Info().Err(err).Msg("unable to delete categories")
return 0, err
}
reg.logger.Debug().Err(err).Uint(
"uid", uid,
).Str("ids", idsStr).Int64("nb", nb).Msg("categories deleted")
logger.Info().Int64("nb", nb).Msg("categories deleted")

return nb, nil
}
63 changes: 26 additions & 37 deletions pkg/service/devices.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,43 +53,46 @@ func (reg *Registry) GetDevice(ctx context.Context, id uint) (*model.Device, err
func (reg *Registry) CreateDevice(ctx context.Context, sub string) (*model.Device, error) {
uid := getCurrentUserIDFromContext(ctx)

logger := reg.logger.With().Uint("uid", uid).Logger()

builder := model.NewDeviceBuilder()
device := builder.UserID(uid).Subscription(sub).Build()

if device.Subscription == nil {
err := errors.New("invalid subscription")
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Msg("unable to configure device")
logger.Info().Err(err).Msg("unable to configure device")
return nil, err
}
logger = logger.With().Str("key", device.Key).Logger()

logger.Debug().Msg("creating device...")
result, err := reg.db.CreateDevice(*device)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Str("key", device.Key).Msg("unable to create device")
logger.Info().Err(err).Msg("unable to create device")
return nil, err
}
logger.Info().Uint("id", *result.ID).Msg("device created")
return result, err
}

// DeleteDevice delete a device of the current user
func (reg *Registry) DeleteDevice(ctx context.Context, id uint) (*model.Device, error) {
uid := getCurrentUserIDFromContext(ctx)

logger := reg.logger.With().Uint("uid", uid).Uint("id", id).Logger()

device, err := reg.GetDevice(ctx, id)
if err != nil {
return nil, err
}

logger.Debug().Msg("deleting device...")
err = reg.db.DeleteDevice(id)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint("id", id).Msg("unable to delete device")
logger.Info().Err(err).Msg("unable to delete device")
return nil, err
}
logger.Info().Msg("device deleted")
return device, nil
}

Expand All @@ -98,16 +101,15 @@ func (reg *Registry) DeleteDevices(ctx context.Context, ids []uint) (int64, erro
uid := getCurrentUserIDFromContext(ctx)
idsStr := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(ids)), ","), "[]")

logger := reg.logger.With().Uint("uid", uid).Str("ids", idsStr).Logger()

logger.Debug().Msg("deleting devices...")
nb, err := reg.db.DeleteDevicesByUser(uid, ids)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Str("ids", idsStr).Msg(errNotification)
logger.Info().Err(err).Msg("unable to delete devices")
return 0, err
}
reg.logger.Debug().Err(err).Uint(
"uid", uid,
).Str("ids", idsStr).Int64("nb", nb).Msg("devices deleted")
logger.Info().Int64("nb", nb).Msg("devices deleted")
return nb, nil
}

Expand All @@ -120,11 +122,11 @@ func (reg *Registry) NotifyDevices(ctx context.Context, payload *model.DeviceNot
}
uid := *user.ID

logger := reg.logger.With().Uint("uid", uid).Logger()

devices, err := reg.GetDevices(ctx)
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Msg(errNotification)
logger.Info().Err(err).Msg(errNotification)
return 0, err
}
msg, err := json.Marshal(payload)
Expand All @@ -133,14 +135,13 @@ func (reg *Registry) NotifyDevices(ctx context.Context, payload *model.DeviceNot
}
counter := 0
for _, device := range *devices {
logger = reg.logger.With().Uint("uid", uid).Uint("device", *device.ID).Logger()
// Rate limiting
if _, _, _, ok, err := reg.notificationRateLimiter.Take(ctx, user.Username); err != nil || !ok {
if !ok {
err = errors.New("rate limiting activated")
}
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint("device", *device.ID).Msg(errNotification)
logger.Info().Err(err).Msg(errNotification)
continue
}
// Send notification
Expand All @@ -151,33 +152,21 @@ func (reg *Registry) NotifyDevices(ctx context.Context, payload *model.DeviceNot
TTL: 30,
})
if err != nil {
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint("device", *device.ID).Msg(errNotification)
logger.Info().Err(err).Msg(errNotification)
continue
}
if res.StatusCode == 410 {
// Registration is gone... we should remove the device
err = reg.db.DeleteDevice(*device.ID)
reg.logger.Info().Err(err).Uint(
"uid", uid,
).Uint("device", *device.ID).Msg("registration gone: device deleted")
logger.Info().Err(err).Msg("registration gone: device deleted")
continue
}
if res.StatusCode >= 400 {
reg.logger.Info().Err(errors.New(res.Status)).Uint(
"uid", uid,
).Uint(
"device", *device.ID,
).Int("status", res.StatusCode).Msg(errNotification)
logger.Info().Err(errors.New(res.Status)).Int("status", res.StatusCode).Msg(errNotification)
continue
}
counter++
reg.logger.Info().Uint(
"uid", uid,
).Uint(
"device", *device.ID,
).Int("status", res.StatusCode).Msg("notification sent to user device")
logger.Info().Str("title", payload.Title).Msg("notification sent to user device")
}
return counter, nil
}
6 changes: 3 additions & 3 deletions pkg/service/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ func (reg *Registry) DownloadArticle(ctx context.Context, idArticle uint, format
logger.Info().Err(err).Msg(ErrArticleDownload.Error())
return nil, err
}
logger.Debug().Msg("preparing article download artifact")

// get downloadable article from the cache
key := helper.Hash(format, article.Hash)
Expand All @@ -50,11 +49,12 @@ func (reg *Registry) DownloadArticle(ctx context.Context, idArticle uint, format
logger.Info().Err(err).Msg(ErrArticleDownload.Error())
}
if data != nil {
reg.logger.Debug().Uint("uid", uid).Uint("id", idArticle).Msg("returns article download artefact from cache")
logger.Debug().Msg("get article downloadable asset from cache")
return downloader.NewWebAsset(data)
}

// export article to the downloadable format
logger.Debug().Msg("preparing article downloadable asset...")
result, err := exp.Export(ctx, article)
if err != nil {
logger.Info().Err(err).Msg(ErrArticleDownload.Error())
Expand All @@ -72,7 +72,7 @@ func (reg *Registry) DownloadArticle(ctx context.Context, idArticle uint, format
logger.Info().Err(err).Msg(ErrArticleDownload.Error())
}

reg.logger.Info().Uint("uid", uid).Uint("id", idArticle).Msg("article download artifact created")
logger.Info().Msg("article downloadable asset created")

return result, nil
}
8 changes: 5 additions & 3 deletions pkg/service/event-notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,17 @@ func newNotificationEventHandler(srv *Registry) event.EventHandler {
ctx := context.WithValue(context.TODO(), constant.ContextUserID, uid)
req := model.ArticlesPageRequest{Status: &status}

logger := log.With().Uint("uid", uid).Logger()

user, err := srv.GetCurrentUser(ctx)
if err != nil {
log.Info().Err(err).Uint("id", uid).Msg(notificationErrorMessage)
logger.Info().Err(err).Msg(notificationErrorMessage)
return
}

nb, err := srv.CountCurrentUserDevices(ctx)
if err != nil {
log.Info().Err(err).Uint("id", uid).Msg(notificationErrorMessage)
logger.Info().Err(err).Msg(notificationErrorMessage)
return
}
if nb == 0 {
Expand All @@ -52,7 +54,7 @@ func newNotificationEventHandler(srv *Registry) event.EventHandler {
// Retrieve number of articles
nb, err = srv.CountCurrentUserArticles(ctx, req)
if err != nil {
log.Info().Err(err).Uint("id", uid).Msg(notificationErrorMessage)
logger.Info().Err(err).Msg(notificationErrorMessage)
return
}
// Send notification only every 10 articles
Expand Down
Loading

0 comments on commit 2d2fb08

Please sign in to comment.