Skip to content

Commit

Permalink
feat(plc4go): use structured loggin when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
sruehl committed Aug 2, 2023
1 parent d343a1b commit 95c4983
Show file tree
Hide file tree
Showing 447 changed files with 4,007 additions and 1,191 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func ${type.name}ParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffe
return <#if type.type.orElseThrow().isStringTypeReference() || type.type.orElseThrow().isVstringTypeReference()>""<#elseif baseType == "bool">false<#else>0</#if>, errors.Wrap(err, "error reading ${type.name}")
}
if enum, ok := ${type.name}ByValue(val); !ok {
log.Debug().Msgf("no value %x found for RequestType", val)
log.Debug().Interface("val", val).Msg("no value val found for ${type.name}")
return ${type.name}(val), nil
} else {
return enum, nil
Expand Down
2 changes: 1 addition & 1 deletion plc4go/examples/ads/subscribe/Subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func main() {
AddChangeOfStateTagAddress("value-int", "MAIN.rivianTest01.HorizontalPosition").
AddPreRegisteredConsumer("value-int", func(event apiModel.PlcSubscriptionEvent) {
value := event.GetValue("value-int")
log.Info().Msgf("Got value: %d", value.GetUint16())
log.Info().Uint16("value", value.GetUint16()).Msg("Got value")
}).
Build()
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func main() {
// Wait for the driver to connect (or not)
connectionResult := <-crc
if connectionResult.GetErr() != nil {
log.Error().Msgf("error connecting to PLC: %s", connectionResult.GetErr().Error())
log.Error().Err(connectionResult.GetErr()).Msg("error connecting to PLC")
return
}
log.Info().Str("connection string", connStr).Msg("Connected")
Expand Down
35 changes: 23 additions & 12 deletions plc4go/examples/knx/discovery/hello_world_plc4go_knx_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
package main

import (
"fmt"
"os"
"time"

Expand Down Expand Up @@ -68,7 +69,7 @@ func main() {
// Wait for the driver to connect (or not)
connectionResult := <-crc
if connectionResult.GetErr() != nil {
log.Error().Msgf("error connecting to PLC: %s", connectionResult.GetErr().Error())
log.Error().Err(connectionResult.GetErr()).Msg("error connecting to PLC")
return
}
log.Info().Str("connection string", connStr).Msg("Connected")
Expand All @@ -88,7 +89,7 @@ func main() {
brr := browseRequest.ExecuteWithInterceptor(func(result apiModel.PlcBrowseItem) bool {
knxTag := result.GetTag()
knxAddress := knxTag.GetAddressString()
log.Info().Msgf("Inspecting detected Device at KNX Address: %s", knxAddress)
log.Info().Str("knxAddress", knxAddress).Msg("Inspecting detected Device at KNX Address")

// Try to get all the com-objects and the group addresses they are attached to.
browseRequest, err := connection.BrowseRequestBuilder().
Expand Down Expand Up @@ -121,23 +122,27 @@ func main() {
} else {
permissions += " "
}
log.Info().Msgf(" - %15s (%s) %s", result.GetTag().GetAddressString(), permissions, result.GetName())
log.Info().
Str("addressString", fmt.Sprintf("%15s", result.GetTag().GetAddressString())).
Str("permissions", permissions).
Str("name", result.GetName()).
Msg(" - addressString (permissions) name")
}

readRequest, err := connection.ReadRequestBuilder().
AddTagAddress("applicationProgramVersion", knxAddress+"#3/13").
AddTagAddress("interfaceProgramVersion", knxAddress+"#4/13").
Build()
if err != nil {
log.Error().Msgf("Error creating read request for scanning %s", knxAddress)
log.Error().Str("knxAddress", knxAddress).Msg("Error creating read request for scanning")
return false
}

rrr := readRequest.Execute()
readRequestResult := <-rrr

if readRequestResult.GetErr() != nil {
log.Error().Msgf("Error executing read request for reading device identification information %s", knxAddress)
log.Error().Str("knxAddress", knxAddress).Msg("Error executing read request for reading device identification information")
return false
}
readResponse := readRequestResult.GetResponse()
Expand All @@ -155,28 +160,34 @@ func main() {
if rb.GetTotalBytes() == 5 {
manufacturerId, err = rb.ReadUint16("manufacturerId", 16)
if err != nil {
log.Error().Err(err).Msgf("Error reading manufacturer id from")
log.Error().Err(err).Msg("Error reading manufacturer id from")
return false
}
applicationId, err = rb.ReadUint16("applicationId", 16)
if err != nil {
log.Error().Err(err).Msgf("Error reading application id from")
log.Error().Err(err).Msg("Error reading application id from")
return false
}
applicationVersionMajor, err = rb.ReadUint8("applicationVersionMajor", 4)
if err != nil {
log.Error().Err(err).Msgf("Error reading application version major from %s", knxAddress)
log.Error().Err(err).Str("knxAddress", knxAddress).Msg("Error reading application version major from knxAddress")
return false
}
applicationVersionMinor, err = rb.ReadUint8("applicationVersionMinor", 4)
if err != nil {
log.Error().Err(err).Msgf("Error reading application version minor from %s", knxAddress)
log.Error().Err(err).Str("knxAddress", knxAddress).Msg("Error reading application version minor from knxAddress")
return false
}
}

log.Info().Msgf(" manufacturer id: %d", manufacturerId)
log.Info().Msgf(" program id: %d version %d.%d", applicationId, applicationVersionMajor, applicationVersionMinor)
log.Info().
Uint16("manufacturerId", manufacturerId).
Msg(" manufacturer id: manufacturerId")
log.Info().
Uint16("applicationId", applicationId).
Uint8("applicationVersionMajor", applicationVersionMajor).
Uint8("applicationVersionMinor", applicationVersionMinor).
Msg(" program id: applicationId version applicationVersionMajor.applicationVersionMinor")

return true
})
Expand All @@ -186,7 +197,7 @@ func main() {
}
select {
case browseRequestResult := <-brr:
log.Info().Msgf("Browse Request Result:\n%v", browseRequestResult)
log.Info().Stringer("browseRequestResult", browseRequestResult).Msg("Browse Request Result")
}
return
}
Expand Down
11 changes: 7 additions & 4 deletions plc4go/internal/ads/Connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,10 @@ func (m *Connection) setupConnection(ctx context.Context, ch chan plc4go.PlcConn
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
for message := range defaultIncomingMessageChannel {
Expand All @@ -190,10 +193,10 @@ func (m *Connection) setupConnection(ctx context.Context, ch chan plc4go.PlcConn
m.handleIncomingDeviceNotificationRequest(
amsTCPPacket.GetUserdata().(readWriteModel.AdsDeviceNotificationRequest))
default:
m.log.Warn().Msgf("Got unexpected type of incoming ADS message %v", message)
m.log.Warn().Stringer("message", message).Msg("Got unexpected type of incoming ADS message")
}
default:
m.log.Warn().Msgf("Got unexpected type of incoming ADS message %v", message)
m.log.Warn().Stringer("message", message).Msg("Got unexpected type of incoming ADS message")
}
}
m.log.Info().Msg("Done waiting for messages ...")
Expand Down Expand Up @@ -411,7 +414,7 @@ func (m *Connection) GetMessageCodec() spi.MessageCodec {
}

func (m *Connection) GetMetadata() apiModel.PlcConnectionMetadata {
return _default.DefaultConnectionMetadata{
return &_default.DefaultConnectionMetadata{
ProvidesReading: true,
ProvidesWriting: true,
ProvidesSubscribing: true,
Expand Down
5 changes: 4 additions & 1 deletion plc4go/internal/ads/Discoverer.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,10 @@ func (d *Discoverer) Discover(ctx context.Context, callback func(event apiModel.
go func(discoveryItem *discovery) {
defer func() {
if err := recover(); err != nil {
d.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
d.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
buf := make([]byte, 1024)
Expand Down
4 changes: 2 additions & 2 deletions plc4go/internal/ads/DiscoveryMessageCodec.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (m *DiscoveryMessageCodec) Send(message spi.Message) error {
func (m *DiscoveryMessageCodec) Receive() (spi.Message, error) {
// We need at least 6 bytes in order to know how big the packet is in total
if num, err := m.GetTransportInstance().GetNumBytesAvailableInBuffer(); (err == nil) && (num >= 6) {
m.log.Debug().Msgf("we got %d readable bytes", num)
m.log.Debug().Uint32("num", num).Msg("we got num readable bytes")
data, err := m.GetTransportInstance().PeekReadableBytes(6)
if err != nil {
m.log.Warn().Err(err).Msg("error peeking")
Expand All @@ -84,7 +84,7 @@ func (m *DiscoveryMessageCodec) Receive() (spi.Message, error) {
// Get the size of the entire packet little endian plus size of header
packetSize := (uint32(data[5]) << 24) + (uint32(data[4]) << 16) + (uint32(data[3]) << 8) + (uint32(data[2])) + 6
if num < packetSize {
m.log.Debug().Msgf("Not enough bytes. Got: %d Need: %d\n", num, packetSize)
m.log.Debug().Uint32("num", num).Uint32("packetSize", packetSize).Msg("Not enough bytes. Got: num Need: packetSize")
return nil, nil
}
data, err = m.GetTransportInstance().Read(packetSize)
Expand Down
20 changes: 15 additions & 5 deletions plc4go/internal/ads/Driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,18 @@ func NewDriver(_options ...options.WithOption) plc4go.PlcDriver {
}

func (m *Driver) GetConnectionWithContext(ctx context.Context, transportUrl url.URL, transports map[string]transports.Transport, driverOptions map[string][]string) <-chan plc4go.PlcConnectionConnectResult {
m.log.Debug().Stringer("transportUrl", &transportUrl).Msgf("Get connection for transport url with %d transport(s) and %d option(s)", len(transports), len(driverOptions))
m.log.Debug().
Stringer("transportUrl", &transportUrl).
Int("nTransports", len(transports)).
Int("nDriverOptions", len(driverOptions)).
Msg("Get connection for transport url with nTransports transport(s) and nDriverOptions option(s)")
// Get the transport specified in the url
transport, ok := transports[transportUrl.Scheme]
if !ok {
m.log.Error().Stringer("transportUrl", &transportUrl).Msgf("We couldn't find a transport for scheme %s", transportUrl.Scheme)
m.log.Error().
Stringer("transportUrl", &transportUrl).
Str("scheme", transportUrl.Scheme).
Msg("We couldn't find a transport for scheme")
ch := make(chan plc4go.PlcConnectionConnectResult, 1)
ch <- _default.NewDefaultPlcConnectionConnectResult(nil, errors.Errorf("couldn't find transport for given transport url %#v", transportUrl))
return ch
Expand All @@ -71,7 +78,10 @@ func (m *Driver) GetConnectionWithContext(ctx context.Context, transportUrl url.
append(m._options, options.WithCustomLogger(m.log))...,
)
if err != nil {
m.log.Error().Stringer("transportUrl", &transportUrl).Msgf("We couldn't create a transport instance for port %#v", driverOptions["defaultTcpPort"])
m.log.Error().
Stringer("transportUrl", &transportUrl).
Strs("defaultTcpPort", driverOptions["defaultTcpPort"]).
Msg("We couldn't create a transport instance for port")
ch := make(chan plc4go.PlcConnectionConnectResult, 1)
ch <- _default.NewDefaultPlcConnectionConnectResult(nil, errors.New("couldn't initialize transport configuration for given transport url "+transportUrl.String()))
return ch
Expand All @@ -82,11 +92,11 @@ func (m *Driver) GetConnectionWithContext(ctx context.Context, transportUrl url.
transportInstance,
append(m._options, options.WithCustomLogger(m.log))...,
)
m.log.Debug().Msgf("working with codec %#v", codec)
m.log.Debug().Stringer("codec", codec).Msg("working with codec")

configuration, err := model.ParseFromOptions(m.log, driverOptions)
if err != nil {
m.log.Error().Err(err).Msgf("Invalid driverOptions")
m.log.Error().Err(err).Msg("Invalid driverOptions")
ch := make(chan plc4go.PlcConnectionConnectResult, 1)
ch <- _default.NewDefaultPlcConnectionConnectResult(nil, errors.Wrap(err, "invalid configuration"))
return ch
Expand Down
30 changes: 24 additions & 6 deletions plc4go/internal/ads/Interactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ func (m *Connection) ExecuteAdsReadDeviceInfoRequest(ctx context.Context) (model
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsReadDeviceInfoRequest()
Expand Down Expand Up @@ -75,7 +78,10 @@ func (m *Connection) ExecuteAdsReadRequest(ctx context.Context, indexGroup uint3
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsReadRequest(indexGroup, indexOffset, length)
Expand Down Expand Up @@ -116,7 +122,10 @@ func (m *Connection) ExecuteAdsWriteRequest(ctx context.Context, indexGroup uint
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsWriteRequest(indexGroup, indexOffset, data)
Expand Down Expand Up @@ -157,7 +166,10 @@ func (m *Connection) ExecuteAdsReadWriteRequest(ctx context.Context, indexGroup
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsReadWriteRequest(indexGroup, indexOffset, readLength, items, writeData)
Expand Down Expand Up @@ -198,7 +210,10 @@ func (m *Connection) ExecuteAdsAddDeviceNotificationRequest(ctx context.Context,
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsAddDeviceNotificationRequest(indexGroup, indexOffset, length, transmissionMode, maxDelay, cycleTime)
Expand Down Expand Up @@ -239,7 +254,10 @@ func (m *Connection) ExecuteAdsDeleteDeviceNotificationRequest(ctx context.Conte
go func() {
defer func() {
if err := recover(); err != nil {
m.log.Error().Msgf("panic-ed %v. Stack: %s", err, debug.Stack())
m.log.Error().
Str("stack", string(debug.Stack())).
Interface("err", err).
Msg("panic-ed")
}
}()
request := m.NewAdsDeleteDeviceNotificationRequest(notificationHandle)
Expand Down
6 changes: 4 additions & 2 deletions plc4go/internal/ads/MessageCodec.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ import (
"github.com/rs/zerolog"
)

//go:generate go run ../../tools/plc4xgenerator/gen.go -type=MessageCodec
type MessageCodec struct {
_default.DefaultCodec
none bool // TODO: just a empty field to satisfy generator (needs fixing because in this case here we have the delegate)

log zerolog.Logger
log zerolog.Logger `ignore:"true"`
}

func NewMessageCodec(transportInstance transports.TransportInstance, _options ...options.WithOption) *MessageCodec {
Expand Down Expand Up @@ -100,7 +102,7 @@ func (m *MessageCodec) Receive() (spi.Message, error) {

// We need at least 6 bytes in order to know how big the packet is in total
if num, err := transportInstance.GetNumBytesAvailableInBuffer(); (err == nil) && (num >= 6) {
m.log.Debug().Msgf("we got %d readable bytes", num)
m.log.Debug().Uint32("num", num).Msg("we got num readable bytes")
data, err := transportInstance.PeekReadableBytes(6)
if err != nil {
m.log.Warn().Err(err).Msg("error peeking")
Expand Down
Loading

0 comments on commit 95c4983

Please sign in to comment.