110 lines
1.7 KiB
Go
110 lines
1.7 KiB
Go
package slog
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
type LogWriter interface {
|
|
WriteLog(msg string, kvs map[string]interface{})
|
|
}
|
|
|
|
func Printf(format string, args ...any) {
|
|
formatLoc := format
|
|
|
|
optNum := 0
|
|
|
|
for bofs := strings.Index(formatLoc, "{{"); bofs != -1; bofs = strings.Index(formatLoc, "{{") {
|
|
if optNum > len(args) {
|
|
break
|
|
}
|
|
|
|
os.Stdout.Write([]byte(formatLoc[0:bofs]))
|
|
|
|
formatLoc = formatLoc[bofs+2:]
|
|
|
|
eofs := strings.Index(formatLoc, "}}")
|
|
if eofs == -1 {
|
|
break
|
|
}
|
|
|
|
b, _ := json.Marshal(args[optNum])
|
|
|
|
os.Stdout.Write(b)
|
|
|
|
optNum++
|
|
|
|
formatLoc = formatLoc[eofs+2:]
|
|
|
|
}
|
|
os.Stdout.Write([]byte(formatLoc))
|
|
}
|
|
|
|
type Logger struct {
|
|
w LogWriter
|
|
}
|
|
|
|
type KV struct {
|
|
Key string
|
|
Value any
|
|
}
|
|
|
|
func (p *Logger) Printf(format string, args ...interface{}) {
|
|
formatLoc := format
|
|
optNum := 0
|
|
|
|
kvs := make(map[string]interface{})
|
|
for bofs := strings.Index(formatLoc, "{{"); bofs != -1; bofs = strings.Index(formatLoc, "{{") {
|
|
if optNum > len(args) {
|
|
break
|
|
}
|
|
|
|
formatLoc = formatLoc[bofs+2:]
|
|
eofs := strings.Index(formatLoc, "}}")
|
|
if eofs == -1 {
|
|
break
|
|
}
|
|
|
|
key := formatLoc[0:eofs]
|
|
|
|
kvs[key] = args[optNum]
|
|
optNum++
|
|
formatLoc = formatLoc[eofs+2:]
|
|
}
|
|
|
|
p.w.WriteLog(format, kvs)
|
|
}
|
|
|
|
func NewLogger(w LogWriter) *Logger {
|
|
return &Logger{
|
|
w: w,
|
|
}
|
|
}
|
|
|
|
type JsonAdapter struct {
|
|
w io.Writer
|
|
}
|
|
|
|
func NewJsonAdapter(w io.Writer) LogWriter {
|
|
return &JsonAdapter{w: w}
|
|
}
|
|
|
|
func (j *JsonAdapter) WriteLog(msg string, kvs map[string]interface{}) {
|
|
kvs["Log"] = msg
|
|
b, _ := json.Marshal(kvs)
|
|
j.w.Write(b)
|
|
}
|
|
|
|
type NullAdapter struct {
|
|
w io.Writer
|
|
}
|
|
|
|
func NewNullAdapter() LogWriter {
|
|
return &NullAdapter{}
|
|
}
|
|
|
|
func (j *NullAdapter) WriteLog(msg string, kvs map[string]interface{}) {
|
|
}
|