3

I have been searching for examples of how to implement a database logger for uber-go.zip that will insert the message and fields into a database table for querying. (So no encoding) No luck so far finding some examples, so I am starting with the example from here:

How to access Fields in zap Hooks?

But the code doesnt even appear to do what it suggests it should do, here is my example:

https://go.dev/play/p/9AugEsYwA-E

package main

import (
    "errors"
    "fmt"

    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

func main() {
    fmt.Println("Hello, 世界")
    l, _ := zap.NewProduction()
    logger := zap.New(&CqlLogCore{Core: l.Core()})

    logger.Info("some logging info",
        zap.Int("count", 17),
        zap.Error(errors.New("boom")))

}

type CqlLogCore struct {
    zapcore.Core
}

func (c *CqlLogCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
    fmt.Println("hi", entry, fields)
    return c.Core.Write(entry, fields)
}

The test log message with "hi" is not dumped to stdout. Can someone please point me to where I am going wrong, or an example database logger.

Thanks!

Jay
  • 19,649
  • 38
  • 121
  • 184
  • 1
    You need to implement a `zapcore.WriteSyncer` (easy) and feed it to `zapcore.NewCore` constructor. Then you can feed the newly created core to `zap.New` to build some loggers. Optionally, you may need a different encoder as well, that also goes into `NewCore`. – oakad Jan 23 '22 at 13:19
  • 1
    Thanks @oakad , I did look at the `WriteSyncer` interface takes bytes doesnt it? We need to write the `message` and `fields` to the database table so I dont know how using a `WriteSyncer` helps unless we are perhaps writing low level bytes to the cassandra socket?? – Jay Jan 23 '22 at 13:28
  • Thanks, that fixed it in the other one. – Jay Jan 23 '22 at 14:12
  • Yes, my question feels very close to the other one, but not the same, as there are other things to consider. We use cassandra, and my google fu is not strung enough to find a zap cassandra logger, so here I am. – Jay Jan 23 '22 at 23:16
  • With regards to implementation the reason this question feels different as there are other things to consider such as blocking, concurrency, etc... – Jay Jan 23 '22 at 23:16

0 Answers0