This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
microservices-collection/logging/service/main.go

129 lines
2.9 KiB
Go

package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/bdlm/log"
"github.com/bdlm/std/logger"
"github.com/streadway/amqp"
"dev.sum7.eu/genofire/microservices-collection/lib"
srv "dev.sum7.eu/genofire/microservices-collection/logging"
)
var logRecieved = false
func main() {
flag.BoolVar(&logRecieved, "received", logRecieved, "show received log on console")
flag.Parse()
lib.LogUpdateConfig()
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
log.Fatalf("Failed to connect to RabbitMQ: %s", err)
}
defer conn.Close()
ch, err := conn.Channel()
if err != nil {
log.Fatalf("Failed to open a channel: %s", err)
}
defer ch.Close()
if err = srv.ExchangeDeclare(ch); err != nil {
log.Fatalf("Failed to declare an exchange: %s", err)
}
q, err := ch.QueueDeclare(
"", // name
false, // durable
false, // delete when usused
true, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Fatalf("Failed to declare a queue: %s", err)
}
err = ch.QueueBind(
q.Name, // queue name
"", // routing key
srv.EXCHANGE, // exchange
false,
nil)
if err != nil {
log.Fatalf("Failed to bind a queue: %s", err)
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
log.Fatalf("Failed to register a consumer: %s", err)
}
loggerRecieved := log.New()
loggerRecieved.SetLevel(logger.Trace)
go func() {
for d := range msgs {
var logMessage *srv.LogMessage
if err := json.Unmarshal([]byte(d.Body), &logMessage); err != nil {
log.Fatal(err)
}
//TODO write to Database (to get last values for web client)
// output to console
if !logRecieved {
continue
}
e := &log.Entry{
Logger: loggerRecieved,
Time: logMessage.Time,
Data: logMessage.Data,
}
e = e.WithFields(map[string]interface{}{
"service_name": logMessage.ServiceName,
"service_id": logMessage.ServiceID,
"log_level": logMessage.Level,
})
lvl := logger.Level(uint32(logMessage.Level))
if lvl >= logger.Trace {
e.Debug(fmt.Sprintf("[trace] %s", logMessage.Message))
} else if lvl >= logger.Debug {
e.Debug(logMessage.Message)
} else if lvl >= logger.Info {
e.Info(logMessage.Message)
} else if lvl >= logger.Warn {
e.Warn(logMessage.Message)
} else if lvl >= logger.Error {
e.Error(logMessage.Message)
} else if lvl >= logger.Panic {
e.Error(fmt.Sprintf("[panic] %s", logMessage.Message))
} else if lvl >= logger.Fatal {
e.Error(fmt.Sprintf("[fatal] %s", logMessage.Message))
}
}
}()
log.Debug("started")
// Wait for INT/TERM
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigs
log.WithField("received", sig).Info("stopped")
}