Adding logging to your microservice 

In this section, let us learn how to add transport-level logging and application-level logging to our Go Kit microservices. We use the above example but modify it a little bit. Let us call our new project encryptServiceWithLogging. In the GitHub project of this book, you will find this directory. We visited the concepts of middleware many times in this book. For revision, a middleware is a function that tampers the request/response before/after it reaches the respective request handlers. Go Kit allows us to create logging middleware, which we attach to our service. That middleware will have the logging logic. In this example, we try to log to the Stderr (console). Add one new file called middleware.go to the helpers directory, as shown in the following code:

package helpers
import (
"context"
"time"
log "github.com/go-kit/kit/log"
)
// LoggingMiddleware wraps the logs for incoming requests
type LoggingMiddleware struct {
Logger log.Logger
Next EncryptService
}
// Encrypt logs the encyption requests
func (mw LoggingMiddleware) Encrypt(ctx context.Context, key string, text string) (output string, err error) {
defer func(begin time.Time) {
_ = mw.Logger.Log(
"method", "encrypt",
"key", key,
"text", text,
"output", output,
"err", err,
"took", time.Since(begin),
)
}(time.Now())
output, err = mw.Next.Encrypt(ctx, key, text)
return
}
// Decrypt logs the encyption requests
func (mw LoggingMiddleware) Decrypt(ctx context.Context, key string,
text string) (output string, err error) {
defer func(begin time.Time) {
_ = mw.Logger.Log(
"method", "decrypt",
"key", key,
"message", text,
"output", output,
"err", err,
"took", time.Since(begin),
)
}(time.Now())
output, err = mw.Next.Decrypt(ctx, key, text)
return
}

We need to create a struct that has a logger and our service instance. Then, define a few methods on that whose names are similar to the service methods (in this case, they are encrypt and decrypt). The Logger is the Go Kit's logger that has a Log function. This Log function takes a few arguments. It takes a pair of arguments. The first and second are one set. The third and fourth are another set. Refer to the following code snippet:

mw.Logger.Log(
      "method", "decrypt",
      "key", key,
      "message", text,
      "output", output,
      "err", err,
      "took", time.Since(begin),
    )

We need to maintain the order in which the log should print. After logging our request details, we make sure to allow the request to go to the next middleware/handler using this function. Next is of the type EncryptService, which is our actual implementation:

mw.Next.(Encrypt/Decrypt)

For the encryption function, middleware logs a request for encryption and passes it to the implementation of the service. In order to hook this created middleware into our service, modify main.go to this:

 

package main
import (
"log"
"net/http"
"os"
kitlog "github.com/go-kit/kit/log"
httptransport "github.com/go-kit/kit/transport/http"
"github.com/narenaryan/encryptService/helpers"
)
func main() {
logger := kitlog.NewLogfmtLogger(os.Stderr)
var svc helpers.EncryptService
svc = helpers.EncryptServiceInstance{}
svc = helpers.LoggingMiddleware{Logger: logger, Next: svc}
encryptHandler := httptransport.NewServer(helpers.MakeEncryptEndpoint(svc),
helpers.DecodeEncryptRequest,
helpers.EncodeResponse)
decryptHandler := httptransport.NewServer(helpers.MakeDecryptEndpoint(svc),
helpers.DecodeDecryptRequest,
helpers.EncodeResponse)
http.Handle("/encrypt", encryptHandler)
http.Handle("/decrypt", decryptHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}

We imported the log from Go Kit as kitlog. We created a new logger using NewLogfmtLogger(os.Stderr). This attaches the logging to the console. Now, pass this logger and service to the LoggingMiddleware. It returns the service that can be passed to the HTTP server. Now, let us run the program from encryptServiceWithLogging and see what output logs on the console:

go run main.go

It starts our microservice. Now, fire client requests from the CURL command:

curl -XPOST -d'{"key":"111023043350789514532147", "text": "I am A Message"}' localhost:8080/encrypt

curl -XPOST -d'{"key":"111023043350789514532147", "message": "8/+JCfTb+ibIjzQtmCo="}' localhost:8080/decrypt
{"text":"I am A Message","error":""}

That logs the following messages on the server console:

method=encrypt key=111023043350789514532147 text="I am A Message" output="8/+JCfTb+ibIjzQtmCo=" err=null took=11.32µs

method=decrypt key=111023043350789514532147 message="8/+JCfTb+ibIjzQtmCo=" output="I am A Message" err=null took=6.773µs

This is to log the messages per application/service. System-level logging is also available and can be approached from the Go Kit's documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.37.10