2019-10-07 22:14:47 +08:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 19:15:48 +08:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-04-19 19:40:22 +08:00
|
|
|
// +build !test
|
|
|
|
|
2017-09-23 07:55:29 +08:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2019-07-18 21:01:09 +08:00
|
|
|
"context"
|
2018-04-04 16:15:23 +08:00
|
|
|
"fmt"
|
2017-09-23 07:55:29 +08:00
|
|
|
"time"
|
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
"github.com/mainflux/mainflux"
|
2018-04-04 16:15:23 +08:00
|
|
|
log "github.com/mainflux/mainflux/logger"
|
2017-09-23 07:55:29 +08:00
|
|
|
)
|
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
var _ mainflux.MessagePublisher = (*loggingMiddleware)(nil)
|
2017-09-23 07:55:29 +08:00
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
type loggingMiddleware struct {
|
2017-09-23 07:55:29 +08:00
|
|
|
logger log.Logger
|
2018-03-12 01:06:01 +08:00
|
|
|
svc mainflux.MessagePublisher
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
// LoggingMiddleware adds logging facilities to the adapter.
|
|
|
|
func LoggingMiddleware(svc mainflux.MessagePublisher, logger log.Logger) mainflux.MessagePublisher {
|
|
|
|
return &loggingMiddleware{logger, svc}
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
|
2019-11-05 18:57:16 +08:00
|
|
|
func (lm *loggingMiddleware) Publish(ctx context.Context, token string, msg mainflux.Message) (err error) {
|
2017-09-23 07:55:29 +08:00
|
|
|
defer func(begin time.Time) {
|
2019-03-16 01:38:07 +08:00
|
|
|
destChannel := msg.Channel
|
|
|
|
if msg.Subtopic != "" {
|
|
|
|
destChannel = fmt.Sprintf("%s.%s", destChannel, msg.Subtopic)
|
|
|
|
}
|
|
|
|
message := fmt.Sprintf("Method publish to channel %s took %s to complete", destChannel, time.Since(begin))
|
2018-04-04 16:15:23 +08:00
|
|
|
if err != nil {
|
|
|
|
lm.logger.Warn(fmt.Sprintf("%s with error: %s.", message, err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
lm.logger.Info(fmt.Sprintf("%s without errors.", message))
|
2017-09-23 07:55:29 +08:00
|
|
|
}(time.Now())
|
|
|
|
|
2019-07-18 21:01:09 +08:00
|
|
|
return lm.svc.Publish(ctx, token, msg)
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|