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"
|
|
|
|
|
2020-04-02 03:22:13 +08:00
|
|
|
"github.com/mainflux/mainflux/broker"
|
|
|
|
"github.com/mainflux/mainflux/http"
|
2018-04-04 16:15:23 +08:00
|
|
|
log "github.com/mainflux/mainflux/logger"
|
2017-09-23 07:55:29 +08:00
|
|
|
)
|
|
|
|
|
2020-04-02 03:22:13 +08:00
|
|
|
var _ http.Service = (*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
|
2020-04-02 03:22:13 +08:00
|
|
|
svc http.Service
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
// LoggingMiddleware adds logging facilities to the adapter.
|
2020-04-02 03:22:13 +08:00
|
|
|
func LoggingMiddleware(svc http.Service, logger log.Logger) http.Service {
|
2018-03-12 01:06:01 +08:00
|
|
|
return &loggingMiddleware{logger, svc}
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
|
2020-04-02 03:22:13 +08:00
|
|
|
func (lm *loggingMiddleware) Publish(ctx context.Context, token string, msg broker.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
|
|
|
}
|