Skip to content

Commit

Permalink
slog loging (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
kubaceg authored Nov 4, 2024
1 parent e670723 commit 4c9737f
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 29 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
go-version: 1.21

- name: Build
run: go build -v ./...
Expand Down
5 changes: 3 additions & 2 deletions adapters/comms/serial/serial.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package serial

import (
"fmt"
"io"
"log"
"log/slog"
"time"

"go.bug.st/serial"
Expand Down Expand Up @@ -35,7 +36,7 @@ func New(name string, baud int, dataBits int, parityMode serial.Parity, stopBits
func (s *serialPort) Open() error {
if s.serialPort != nil {
if err := s.Close(); err != nil {
log.Printf("error during serial port connection close: %s", err)
slog.Error(fmt.Sprintf("error during serial port connection close: %s", err))
}
}

Expand Down
5 changes: 3 additions & 2 deletions adapters/devices/sofar/device.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package sofar

import (
"log"
"fmt"
"log/slog"
"regexp"

"github.com/kubaceg/sofar_g3_lsw3_logger_reader/ports"
Expand Down Expand Up @@ -31,7 +32,7 @@ func toREs(patterns []string) []*regexp.Regexp {
if err == nil {
res = append(res, re)
} else {
log.Printf("config attrBlackList item %d '%s' not a valid regexp; %v", idx, p, err)
slog.Warn(fmt.Sprintf("config attrBlackList item %d '%s' not a valid regexp; %v", idx, p, err))
}
}
return res
Expand Down
4 changes: 2 additions & 2 deletions adapters/devices/sofar/lsw.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package sofar
import (
"encoding/binary"
"fmt"
"log"
"log/slog"

"github.com/sigurn/crc16"

Expand Down Expand Up @@ -102,7 +102,7 @@ func readRegisterRange(rr registerRange, connPort ports.CommunicationPort, seria

defer func(connPort ports.CommunicationPort) {
if err := connPort.Close(); err != nil {
log.Printf("error during connection close: %s", err)
slog.Error(fmt.Sprintf("error during connection close: %s", err))
}
}(connPort)

Expand Down
8 changes: 4 additions & 4 deletions adapters/export/mosquitto/mqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package mosquitto
import (
"encoding/json"
"fmt"
"log"
"log/slog"
"strings"
"time"

Expand All @@ -25,11 +25,11 @@ type Connection struct {
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
log.Printf("MQTT Connected")
slog.Debug("MQTT Connected")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
log.Printf("Connect lost: %v", err)
slog.Warn(fmt.Sprintf("Connect lost: %v", err))
}

func New(config *MqttConfig) (*Connection, error) {
Expand Down Expand Up @@ -62,7 +62,7 @@ func (conn *Connection) publish(topic string, msg string, retain bool) {
token := conn.client.Publish(topic, 0, retain, msg)
res := token.WaitTimeout(1 * time.Second)
if !res || token.Error() != nil {
log.Printf("error inserting to MQTT: %s", token.Error())
slog.Error(fmt.Sprintf("error inserting to MQTT: %s", token.Error()))
}
}

Expand Down
7 changes: 4 additions & 3 deletions adapters/export/otlp/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package otlp
import (
"context"
"fmt"
"log/slog"

"github.com/kubaceg/sofar_g3_lsw3_logger_reader/adapters/devices/sofar"
grpc "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
http "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
Expand All @@ -13,7 +15,6 @@ import (
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.opentelemetry.io/otel/sdk/resource"
semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
"log"
)

const (
Expand Down Expand Up @@ -97,12 +98,12 @@ func (s *Service) initGauges() error {
if v, ok := s.measurements[lookup]; ok {
o.ObserveInt64(*g, convertToInt64(v))
} else {
log.Printf("could not find measurement for %s\n", name)
slog.Debug(fmt.Sprintf("could not find measurement for %s\n", name))
}
return nil
}, *g)
if err != nil {
log.Println("error registering gauge callback")
slog.Error(fmt.Sprintf("error registering gauge callback: %s", err))
return err
}
}
Expand Down
1 change: 1 addition & 0 deletions config-example.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# make your own in config.yaml
logLevel: info

inverter:
port: 1.2.3.4:8899 # required, port name e.g. /dev/ttyUSB0 for serial or 1.2.3.4:8899 for TCP/IP
Expand Down
10 changes: 10 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"errors"
"log/slog"
"os"

"github.com/kubaceg/sofar_g3_lsw3_logger_reader/adapters/export/otlp"
Expand All @@ -11,6 +12,7 @@ import (
)

type Config struct {
Debug bool `default:"false" yaml:"debug"`
Inverter struct {
Port string `yaml:"port"`
LoggerSerial uint `yaml:"loggerSerial"`
Expand Down Expand Up @@ -55,3 +57,11 @@ func NewConfig(configPath string) (*Config, error) {

return config, nil
}

func (c Config) getLoglevel() slog.Leveler {
if c.Debug {
return slog.LevelDebug
}

return slog.LevelInfo
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/kubaceg/sofar_g3_lsw3_logger_reader

go 1.19
go 1.21

require (
github.com/eclipse/paho.mqtt.golang v1.3.1
Expand Down
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/eclipse/paho.mqtt.golang v1.3.1 h1:6F5FYb1hxVSZS+p0ji5xBQamc5ltOolTYRy5R15uVmI=
github.com/eclipse/paho.mqtt.golang v1.3.1/go.mod h1:eTzb4gxwwyWpqBUHGQZ4ABAV7+Jgm1PklsYT/eo8Hcc=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
Expand All @@ -76,6 +77,7 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4=
github.com/golang/glog v1.1.0 h1:/d3pCKDPWNnvIWe0vVUpNP32qc8U3PDVxySP/y360qE=
github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down Expand Up @@ -116,6 +118,7 @@ github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
Expand Down Expand Up @@ -158,6 +161,7 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
Expand Down Expand Up @@ -456,6 +460,7 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
32 changes: 18 additions & 14 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package main

import (
"context"
"log"
"fmt"
"log/slog"
_ "net/http/pprof"
"os"
"strings"
"time"

Expand Down Expand Up @@ -34,32 +36,37 @@ func initialize() {
var err error
config, err = NewConfig("config.yaml")
if err != nil {
log.Fatalln(err)
panic(fmt.Sprintf("error during config.yaml file load: %s", err))
}

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: config.getLoglevel()}))
slog.SetDefault(logger)

hasMQTT = config.Mqtt.Url != "" && config.Mqtt.Prefix != ""
hasOTLP = config.Otlp.Grpc.Url != "" || config.Otlp.Http.Url != ""

if isSerialPort(config.Inverter.Port) {
port = serial.New(config.Inverter.Port, 2400, 8, gser.NoParity, gser.OneStopBit)
log.Printf("using serial communcations port %s", config.Inverter.Port)
slog.Debug(fmt.Sprintf("using serial communcations port %s", config.Inverter.Port))
} else {
port = tcpip.New(config.Inverter.Port)
log.Printf("using TCP/IP communications port %s", config.Inverter.Port)
slog.Debug(fmt.Sprintf("using TCP/IP communications port %s", config.Inverter.Port))
}

if hasMQTT {
mqtt, err = mosquitto.New(&config.Mqtt)
if err != nil {
log.Fatalf("MQTT connection failed: %s", err)
slog.Error(fmt.Sprintf("MQTT connection failed: %s", err))
os.Exit(1)
}

}

if hasOTLP {
telem, err = otlp.New(&config.Otlp)
if err != nil {
log.Fatalf("error initializating otlp connection: %s", err)
slog.Error(fmt.Sprintf("error initializating otlp connection: %s", err))
os.Exit(1)
}
}

Expand All @@ -75,15 +82,15 @@ func main() {

for {
if config.Inverter.LoopLogging {
log.Printf("performing measurements")
slog.Debug("performing measurements")
}

var measurements map[string]interface{} = nil
var err error
for retry := 0; measurements == nil && retry < maximumFailedConnections; retry++ {
measurements, err = device.Query()
if err != nil {
log.Printf("failed to perform measurements on retry %d: %s", retry, err)
slog.Warn(fmt.Sprintf("failed to perform measurements on retry %d: %s", retry, err))
// at night, inverter is offline, err = "dial tcp 192.168.xx.xxx:8899: i/o timeout"
// at other times occaisionally: "read tcp 192.168.68.104:38670->192.168.68.106:8899: i/o timeout"
}
Expand All @@ -105,18 +112,15 @@ func main() {
"LastTimestamp": timeStamp,
}
}
err := mqtt.InsertRecord(m) // logs errors, always returns nil
if err != nil {
log.Printf("never happens: %s", err)
}
_ = mqtt.InsertRecord(m) // logs errors, always returns nil
}

if hasOTLP && measurements != nil {
err := telem.CollectAndPushMetrics(context.Background(), measurements)
if err != nil {
log.Printf("error recording telemetry: %s\n", err)
slog.Error(fmt.Sprintf("error recording telemetry: %s\n", err))
} else {
log.Println("measurements pushed via OLTP")
slog.Debug("measurements pushed via OLTP")
}

}
Expand Down

0 comments on commit 4c9737f

Please sign in to comment.