Skip to content

Commit

Permalink
feat(runner): implement custom log writer
Browse files Browse the repository at this point in the history
Signed-off-by: Dwi Siswanto <[email protected]>
  • Loading branch information
dwisiswant0 committed Oct 25, 2023
1 parent 0351fbf commit 107abcc
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 1 deletion.
3 changes: 2 additions & 1 deletion internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ func New(opt *common.Options) error {
}

dest := buildDest(opt.Destination)
writer := &logWriter{Logger: opt.Logger}

tun, err := tunnel.NewTunnel(opt.Port, dest, opt.Config.Path, opt.Config.Format)
tun, err := tunnel.NewTunnel(opt.Port, dest, opt.Config.Path, opt.Config.Format, writer)
if err != nil {
return err
}
Expand Down
84 changes: 84 additions & 0 deletions internal/runner/writer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package runner

import (
"encoding/json"

"github.com/charmbracelet/log"
)

type Writer interface {
Write(p []byte) (n int, err error)
}

type logWriter struct {
*log.Logger
}

type data map[string]any

func (w *logWriter) Write(p []byte) (n int, err error) {
var d data

n = len(p)

err = json.Unmarshal(p, &d)
if err != nil {
return 0, err
}

logger := w.WithPrefix("teler-waf")
w.Logger = logger

w.Logger.With("ts", d["ts"], "msg", d["msg"])
w.write(d)

return
}

func (w *logWriter) write(d data) {
switch level := d["level"].(string); level {
case "debug":
w.writeDebug(d)
case "info":
w.writeInfo(d)
case "warn":
w.writeWarn(d)
case "error":
w.writeError(d)
case "fatal":
w.writeFatal(d)
}
}

func (w *logWriter) writeDebug(d data) {
w.Debug(d["msg"], "ts", d["ts"])
}

func (w *logWriter) writeInfo(d data) {
if opt, ok := d["options"].(data); ok {
w.Info(d["msg"],
"ts", d["ts"],
"options", opt,
)
}
}

func (w *logWriter) writeWarn(d data) {
w.Warn(d["msg"],
"ts", d["ts"],
"id", d["id"],
"threat", d["category"],
"request", d["request"],
)
}

func (w *logWriter) writeError(d data) {
w.Error(d["msg"],
"ts", d["ts"],
"source", d["caller"],
)
}

func (w *logWriter) writeFatal(d data) {
w.writeError(d)
}

0 comments on commit 107abcc

Please sign in to comment.