Skip to content

Commit

Permalink
Merge pull request eclipse-ditto#5 from bosch-io/readme-logging-example
Browse files Browse the repository at this point in the history
1. Update README with logger examples
  • Loading branch information
thjaeckle committed Jul 28, 2021
2 parents 4bca68f + edf0dce commit 850f1bf
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 6 deletions.
38 changes: 33 additions & 5 deletions README.md
Expand Up @@ -48,8 +48,7 @@ client = ditto.NewClient(config)
After you have configured and created your client instance, it's ready to be connected.
```go
if err := client.Connect(); err != nil {
fmt.Errorf("%v", err)
panic("cannot connect to broker")
panic(fmt.Errorf("cannot connect to broker: %v", err))
}
defer disconnect(client)
```
Expand Down Expand Up @@ -83,7 +82,7 @@ Send the Ditto command.
```go
envelope := command.Envelope(protocol.WithResponseRequired(false))
if err := client.Send(envelope); err != nil {
fmt.Errorf("could not send Ditto message: %v", err)
fmt.Printf("could not send Ditto message: %v\n", err)
}
```

Expand Down Expand Up @@ -133,8 +132,37 @@ func messagesHandler(requestID string, msg *protocol.Envelope) {
responseMsg := response.Envelope(protocol.WithCorrelationID(msg.Headers.CorrelationID()), protocol.WithResponseRequired(false))
responseMsg.Status = 200
if replyErr := client.Reply(requestID, responseMsg); replyErr != nil {
fmt.Errorf("failed to send response to request Id %s: %v", requestID, replyErr)
fmt.Printf("failed to send response to request Id %s: %v\n", requestID, replyErr)
}
}
}
```
```

## Logging

A custom logger could be implemented based on ditto.Logger interface. For example:

```go
type logger struct {
prefix string
}

func (l logger) Println(v ...interface{}) {
fmt.Println(l.prefix, fmt.Sprint(v...))
}

func (l logger) Printf(format string, v ...interface{}) {
fmt.Printf(fmt.Sprint(l.prefix, " ", format), v...)
}
```

Then the Ditto library could be configured to use the logger by assigning the logging endpoints - ERROR, WARN, INFO and DEBUG.

```go
func init() {
ditto.ERROR = logger{prefix: "ERROR "}
ditto.WARN = logger{prefix: "WARN "}
ditto.INFO = logger{prefix: "INFO "}
ditto.DEBUG = logger{prefix: "DEBUG "}
}
```
3 changes: 3 additions & 0 deletions client.go
Expand Up @@ -33,6 +33,7 @@ type Client struct {
handlers map[string]Handler
handlersLock sync.RWMutex
externalMqttClient bool
wgConnectHandler sync.WaitGroup
}

// NewClient creates a new Client instance with the provided Configuration.
Expand Down Expand Up @@ -83,7 +84,9 @@ func NewClientMqtt(mqttClient MQTT.Client, cfg *Configuration) (*Client, error)
// In the case of an external MQTT client, if any error occurs during the internal preparations - it's returned here.
func (client *Client) Connect() error {
if client.externalMqttClient {
client.wgConnectHandler.Add(1)
if token := client.pahoClient.Subscribe(honoMQTTTopicSubscribeCommands, 1, client.honoMessageHandler); token.Wait() && token.Error() != nil {
client.wgConnectHandler.Done()
return token.Error()
}
go client.notifyClientConnected()
Expand Down
5 changes: 4 additions & 1 deletion client_handlers.go
Expand Up @@ -22,10 +22,13 @@ func (client *Client) defaultMessageHandler(mqttClient MQTT.Client, message MQTT

func (client *Client) honoMessageHandler(mqttClient MQTT.Client, message MQTT.Message) {
DEBUG.Printf("received message for client subscription: %v", message)
// wait for handlers added in the ConnectHandler
client.wgConnectHandler.Wait()

client.handlersLock.RLock()
defer client.handlersLock.RUnlock()

if client.handlers == nil || len(client.handlers) == 0 {
if len(client.handlers) == 0 {
WARN.Printf("message received, but no handlers were found")
return
}
Expand Down
2 changes: 2 additions & 0 deletions client_internal.go
Expand Up @@ -29,13 +29,15 @@ const (
)

func (client *Client) clientConnectHandler(pahoClient MQTT.Client) {
client.wgConnectHandler.Add(1)
if token := client.pahoClient.Subscribe(honoMQTTTopicSubscribeCommands, 1, client.honoMessageHandler); token.Wait() && token.Error() != nil {
ERROR.Printf("error subscribing to root Hono topic %s : %v", honoMQTTTopicSubscribeCommands, token.Error())
}
client.notifyClientConnected()
}

func (client *Client) notifyClientConnected() {
defer client.wgConnectHandler.Done()
if client.cfg == nil {
return
}
Expand Down

0 comments on commit 850f1bf

Please sign in to comment.