Update and improve logging library to logrus

This commit is contained in:
Nicholas Thompson
2020-06-15 13:28:03 +02:00
parent c459fb22aa
commit 6ab917d35a
5 changed files with 55 additions and 38 deletions

View File

@@ -31,8 +31,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package main package main
import ( import (
"fmt"
"io" "io"
"log"
"net" "net"
"net/http" "net/http"
"os" "os"
@@ -46,16 +46,23 @@ import (
"github.com/diebietse/invertergui/plugins/webui" "github.com/diebietse/invertergui/plugins/webui"
"github.com/diebietse/invertergui/plugins/webui/static" "github.com/diebietse/invertergui/plugins/webui/static"
"github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"github.com/tarm/serial" "github.com/tarm/serial"
) )
var log = logrus.WithField("ctx", "inverter-gui")
func main() { func main() {
conf, err := parseConfig() conf, err := parseConfig()
if err != nil { if err != nil {
os.Exit(1) os.Exit(1)
} }
log.Info("Starting invertergui")
mk2 := getMk2Device(conf.Data.Source, conf.Data.Host, conf.Data.Device) mk2, err := getMk2Device(conf.Data.Source, conf.Data.Host, conf.Data.Device)
if err != nil {
log.Fatalf("Could not open data source: %v", err)
}
defer mk2.Close() defer mk2.Close()
core := mk2core.NewCore(mk2) core := mk2core.NewCore(mk2)
@@ -88,14 +95,17 @@ func main() {
Password: conf.MQTT.Password, Password: conf.MQTT.Password,
} }
if err := mqttclient.New(core.NewSubscription(), mqttConf); err != nil { if err := mqttclient.New(core.NewSubscription(), mqttConf); err != nil {
log.Printf("Could not setup MQTT client: %v", err) log.Fatalf("Could not setup MQTT client: %v", err)
}
}
log.Infof("Invertergui web server starting on: %v", conf.Address)
if err := http.ListenAndServe(conf.Address, nil); err != nil {
log.Fatal(err)
} }
} }
log.Fatal(http.ListenAndServe(conf.Address, nil)) func getMk2Device(source, ip, dev string) (mk2driver.Mk2, error) {
}
func getMk2Device(source, ip, dev string) mk2driver.Mk2 {
var p io.ReadWriteCloser var p io.ReadWriteCloser
var err error var err error
var tcpAddr *net.TCPAddr var tcpAddr *net.TCPAddr
@@ -105,28 +115,27 @@ func getMk2Device(source, ip, dev string) mk2driver.Mk2 {
serialConfig := &serial.Config{Name: dev, Baud: 2400} serialConfig := &serial.Config{Name: dev, Baud: 2400}
p, err = serial.OpenPort(serialConfig) p, err = serial.OpenPort(serialConfig)
if err != nil { if err != nil {
panic(err) return nil, err
} }
case "tcp": case "tcp":
tcpAddr, err = net.ResolveTCPAddr("tcp", ip) tcpAddr, err = net.ResolveTCPAddr("tcp", ip)
if err != nil { if err != nil {
panic(err) return nil, err
} }
p, err = net.DialTCP("tcp", nil, tcpAddr) p, err = net.DialTCP("tcp", nil, tcpAddr)
if err != nil { if err != nil {
panic(err) return nil, err
} }
case "mock": case "mock":
return mk2driver.NewMk2Mock() return mk2driver.NewMk2Mock(), nil
default: default:
log.Printf("Invalid source selection: %v\nUse \"serial\", \"tcp\" or \"mock\"", source) return nil, fmt.Errorf("Invalid source selection: %v\nUse \"serial\", \"tcp\" or \"mock\"", source)
os.Exit(1)
} }
mk2, err := mk2driver.NewMk2Connection(p) mk2, err := mk2driver.NewMk2Connection(p)
if err != nil { if err != nil {
panic(err) return nil, err
} }
return mk2 return mk2, nil
} }

View File

@@ -1,12 +1,12 @@
package cli package cli
import ( import (
"fmt"
"log"
"github.com/diebietse/invertergui/mk2driver" "github.com/diebietse/invertergui/mk2driver"
"github.com/sirupsen/logrus"
) )
var log = logrus.WithField("ctx", "inverter-gui-cli")
type Cli struct { type Cli struct {
mk2driver.Mk2 mk2driver.Mk2
} }
@@ -27,21 +27,21 @@ func (c *Cli) run() {
} }
func printInfo(info *mk2driver.Mk2Info) { func printInfo(info *mk2driver.Mk2Info) {
out := fmt.Sprintf("Version: %v\n", info.Version) log.Infof("Version: %v", info.Version)
out += fmt.Sprintf("Bat Volt: %.2fV Bat Cur: %.2fA \n", info.BatVoltage, info.BatCurrent) log.Infof("Bat Volt: %.2fV Bat Cur: %.2fA", info.BatVoltage, info.BatCurrent)
out += fmt.Sprintf("In Volt: %.2fV In Cur: %.2fA In Freq %.2fHz\n", info.InVoltage, info.InCurrent, info.InFrequency) log.Infof("In Volt: %.2fV In Cur: %.2fA In Freq %.2fHz", info.InVoltage, info.InCurrent, info.InFrequency)
out += fmt.Sprintf("Out Volt: %.2fV Out Cur: %.2fA Out Freq %.2fHz\n", info.OutVoltage, info.OutCurrent, info.OutFrequency) log.Infof("Out Volt: %.2fV Out Cur: %.2fA Out Freq %.2fHz", info.OutVoltage, info.OutCurrent, info.OutFrequency)
out += fmt.Sprintf("In Power %.2fW Out Power %.2fW\n", info.InVoltage*info.InCurrent, info.OutVoltage*info.OutCurrent) log.Infof("In Power %.2fW Out Power %.2fW", info.InVoltage*info.InCurrent, info.OutVoltage*info.OutCurrent)
out += fmt.Sprintf("Charge State: %.2f%%\n", info.ChargeState*100) log.Infof("Charge State: %.2f%%", info.ChargeState*100)
out += "LEDs state:" log.Info("LEDs state:")
for k, v := range info.LEDs { for k, v := range info.LEDs {
out += fmt.Sprintf(" %s %s", mk2driver.LedNames[k], mk2driver.StateNames[v]) log.Infof(" %s %s", mk2driver.LedNames[k], mk2driver.StateNames[v])
} }
out += "\nErrors:" if len(info.Errors) != 0 {
for _, v := range info.Errors { log.Info("Errors:")
out += " " + v.Error() for _, err := range info.Errors {
log.Error(err)
}
} }
out += "\n"
log.Printf("System Info: \n%v", out)
} }

View File

@@ -2,13 +2,15 @@ package mqttclient
import ( import (
"encoding/json" "encoding/json"
"fmt"
"time" "time"
"github.com/diebietse/invertergui/mk2driver" "github.com/diebietse/invertergui/mk2driver"
mqtt "github.com/eclipse/paho.mqtt.golang" mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/sirupsen/logrus"
) )
var log = logrus.WithField("ctx", "inverter-gui-mqtt")
const keepAlive = 5 * time.Second const keepAlive = 5 * time.Second
// Config sets MQTT client configuration // Config sets MQTT client configuration
@@ -32,14 +34,14 @@ func New(mk2 mk2driver.Mk2, config Config) error {
if e.Valid { if e.Valid {
data, err := json.Marshal(e) data, err := json.Marshal(e)
if err != nil { if err != nil {
fmt.Printf("Data error: %v\n", err) log.Errorf("Could not parse data source: %v", err)
continue continue
} }
t := c.Publish(config.Topic, 0, false, data) t := c.Publish(config.Topic, 0, false, data)
t.Wait() t.Wait()
if t.Error() != nil { if t.Error() != nil {
fmt.Printf("Error: %v\n", t.Error()) log.Errorf("Could not publish data: %v", t.Error())
} }
} }
} }
@@ -61,10 +63,10 @@ func getOpts(config Config) *mqtt.ClientOptions {
opts.SetKeepAlive(keepAlive) opts.SetKeepAlive(keepAlive)
opts.SetOnConnectHandler(func(mqtt.Client) { opts.SetOnConnectHandler(func(mqtt.Client) {
fmt.Print("Client connected to broker") log.Info("Client connected to broker")
}) })
opts.SetConnectionLostHandler(func(cli mqtt.Client, err error) { opts.SetConnectionLostHandler(func(cli mqtt.Client, err error) {
fmt.Printf("Client connection to broker losted: %v", err) log.Errorf("Client connection to broker lost: %v", err)
}) })
return opts return opts

View File

@@ -37,8 +37,11 @@ import (
"time" "time"
"github.com/diebietse/invertergui/mk2driver" "github.com/diebietse/invertergui/mk2driver"
"github.com/sirupsen/logrus"
) )
var log = logrus.WithField("ctx", "inverter-gui-munin")
type Munin struct { type Munin struct {
mk2driver.Mk2 mk2driver.Mk2
muninResponse chan *muninData muninResponse chan *muninData
@@ -63,6 +66,7 @@ func NewMunin(mk2 mk2driver.Mk2) *Munin {
func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) { func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) {
muninDat := <-m.muninResponse muninDat := <-m.muninResponse
if muninDat.timesUpdated == 0 { if muninDat.timesUpdated == 0 {
log.Error("No data returned")
rw.WriteHeader(500) rw.WriteHeader(500)
_, _ = rw.Write([]byte("No data to return.\n")) _, _ = rw.Write([]byte("No data to return.\n"))
return return
@@ -95,7 +99,7 @@ func (m *Munin) ServeMuninHTTP(rw http.ResponseWriter, r *http.Request) {
_, err := rw.Write(outputBuf.Bytes()) _, err := rw.Write(outputBuf.Bytes())
if err != nil { if err != nil {
fmt.Printf("%v\n", err) log.Errorf("Could not write data response: %v", err)
} }
} }
@@ -103,7 +107,7 @@ func (m *Munin) ServeMuninConfigHTTP(rw http.ResponseWriter, r *http.Request) {
output := muninConfig output := muninConfig
_, err := rw.Write([]byte(output)) _, err := rw.Write([]byte(output))
if err != nil { if err != nil {
fmt.Printf("%v\n", err) log.Errorf("Could not write config response: %v", err)
} }
} }

View File

@@ -32,15 +32,17 @@ package webui
import ( import (
"fmt" "fmt"
"log"
"net/http" "net/http"
"sync" "sync"
"time" "time"
"github.com/diebietse/invertergui/mk2driver" "github.com/diebietse/invertergui/mk2driver"
"github.com/diebietse/invertergui/websocket" "github.com/diebietse/invertergui/websocket"
"github.com/sirupsen/logrus"
) )
var log = logrus.WithField("ctx", "inverter-gui-webgui")
const ( const (
LedOff = "dot-off" LedOff = "dot-off"
LedRed = "dot-red" LedRed = "dot-red"
@@ -169,7 +171,7 @@ func (w *WebGui) dataPoll() {
if s.Valid { if s.Valid {
err := w.hub.Broadcast(buildTemplateInput(s)) err := w.hub.Broadcast(buildTemplateInput(s))
if err != nil { if err != nil {
log.Printf("Could not send update to clients: %v", err) log.Errorf("Could not send update to clients: %v", err)
} }
} }
case <-w.stopChan: case <-w.stopChan: