mirror of
https://codeberg.org/scip/yadu.git
synced 2025-12-16 20:21:00 +01:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fed3af065 | ||
| ee3b4e8e9b | |||
| 9d34e78475 | |||
| e9af16a8a2 | |||
| 9ede62037a | |||
| 5c0aadd54a | |||
| 33798bddb3 | |||
|
|
d53c1db7d0 | ||
|
|
1c65084c37 | ||
|
|
7391d990bb | ||
|
|
a993959de7 | ||
| 9547dccc7f | |||
| f733a30fab | |||
|
|
ec3f0b7fc3 |
47
.github/workflows/ci.yaml
vendored
47
.github/workflows/ci.yaml
vendored
@@ -1,47 +0,0 @@
|
|||||||
name: build-and-test
|
|
||||||
on: [push, pull_request]
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
version: [1.21]
|
|
||||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
|
||||||
name: Build
|
|
||||||
runs-on: ${{ matrix.os }}
|
|
||||||
steps:
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: ${{ matrix.version }}
|
|
||||||
id: go
|
|
||||||
|
|
||||||
- name: checkout
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: build
|
|
||||||
run: go build
|
|
||||||
|
|
||||||
- name: test
|
|
||||||
run: make test
|
|
||||||
|
|
||||||
- name: Update coverage report
|
|
||||||
uses: ncruces/go-coverage-report@main
|
|
||||||
with:
|
|
||||||
report: true
|
|
||||||
chart: true
|
|
||||||
amend: true
|
|
||||||
if: |
|
|
||||||
matrix.os == 'ubuntu-latest' &&
|
|
||||||
github.event_name == 'push'
|
|
||||||
continue-on-error: true
|
|
||||||
|
|
||||||
golangci:
|
|
||||||
name: lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: 1.21
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- name: golangci-lint
|
|
||||||
uses: golangci/golangci-lint-action@v3
|
|
||||||
65
.goreleaser.yaml
Normal file
65
.goreleaser.yaml
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
|
||||||
|
|
||||||
|
version: 2
|
||||||
|
|
||||||
|
before:
|
||||||
|
hooks:
|
||||||
|
- go mod tidy
|
||||||
|
|
||||||
|
gitea_urls:
|
||||||
|
api: https://codeberg.org/api/v1
|
||||||
|
download: https://codeberg.org
|
||||||
|
|
||||||
|
builds:
|
||||||
|
- env:
|
||||||
|
- CGO_ENABLED=0
|
||||||
|
goos:
|
||||||
|
- linux
|
||||||
|
- freebsd
|
||||||
|
|
||||||
|
archives:
|
||||||
|
- formats: [tar.gz]
|
||||||
|
# this name template makes the OS and Arch compatible with the results of `uname`.
|
||||||
|
name_template: >-
|
||||||
|
{{ .ProjectName }}_
|
||||||
|
{{- title .Os }}_
|
||||||
|
{{- if eq .Arch "amd64" }}x86_64
|
||||||
|
{{- else if eq .Arch "386" }}i386
|
||||||
|
{{- else }}{{ .Arch }}{{ end }}
|
||||||
|
{{- if .Arm }}v{{ .Arm }}{{ end }}_{{ .Tag }}
|
||||||
|
# use zip for windows archives
|
||||||
|
format_overrides:
|
||||||
|
- goos: windows
|
||||||
|
formats: [zip]
|
||||||
|
- goos: linux
|
||||||
|
formats: [tar.gz,binary]
|
||||||
|
files:
|
||||||
|
- src: "*.md"
|
||||||
|
strip_parent: true
|
||||||
|
- src: Makefile.dist
|
||||||
|
dst: Makefile
|
||||||
|
wrap_in_directory: true
|
||||||
|
|
||||||
|
changelog:
|
||||||
|
sort: asc
|
||||||
|
filters:
|
||||||
|
exclude:
|
||||||
|
- "^docs:"
|
||||||
|
- "^test:"
|
||||||
|
groups:
|
||||||
|
- title: Improved
|
||||||
|
regexp: '^.*?(feat|add|new)(\([[:word:]]+\))??!?:.+$'
|
||||||
|
order: 0
|
||||||
|
- title: Fixed
|
||||||
|
regexp: '^.*?(bug|fix)(\([[:word:]]+\))??!?:.+$'
|
||||||
|
order: 1
|
||||||
|
- title: Changed
|
||||||
|
order: 999
|
||||||
|
|
||||||
|
release:
|
||||||
|
header: "# Release Notes"
|
||||||
|
footer: >-
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Full Changelog: [{{ .PreviousTag }}...{{ .Tag }}](https://codeberg.org/scip/yadu/compare/{{ .PreviousTag }}...{{ .Tag }})
|
||||||
36
.woodpecker/build.yaml
Normal file
36
.woodpecker/build.yaml
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
matrix:
|
||||||
|
platform:
|
||||||
|
- linux/amd64
|
||||||
|
goversion:
|
||||||
|
- 1.24
|
||||||
|
|
||||||
|
labels:
|
||||||
|
platform: ${platform}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
build:
|
||||||
|
when:
|
||||||
|
event: [push]
|
||||||
|
image: golang:${goversion}
|
||||||
|
commands:
|
||||||
|
- go get
|
||||||
|
- go build
|
||||||
|
|
||||||
|
linter:
|
||||||
|
when:
|
||||||
|
event: [push]
|
||||||
|
image: golang:${goversion}
|
||||||
|
commands:
|
||||||
|
- curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.5.0
|
||||||
|
- golangci-lint --version
|
||||||
|
- golangci-lint run ./...
|
||||||
|
depends_on: [build]
|
||||||
|
|
||||||
|
test:
|
||||||
|
when:
|
||||||
|
event: [push]
|
||||||
|
image: golang:${goversion}
|
||||||
|
commands:
|
||||||
|
- go get
|
||||||
|
- go test -v -cover
|
||||||
|
depends_on: [build,linter]
|
||||||
9
Makefile
9
Makefile
@@ -6,10 +6,12 @@
|
|||||||
#
|
#
|
||||||
# no need to modify anything below
|
# no need to modify anything below
|
||||||
|
|
||||||
|
VERSION = $(shell grep VERSION handler.go | head -1 | cut -d '"' -f2)
|
||||||
|
|
||||||
all: buildlocal
|
all: buildlocal
|
||||||
|
|
||||||
buildlocal:
|
buildlocal:
|
||||||
go build
|
go build -o example/example example/example.go
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(tool) coverage.out testdata t/out example/example
|
rm -rf $(tool) coverage.out testdata t/out example/example
|
||||||
@@ -30,3 +32,8 @@ goupdate:
|
|||||||
|
|
||||||
lint:
|
lint:
|
||||||
golangci-lint run -p bugs -p unused
|
golangci-lint run -p bugs -p unused
|
||||||
|
|
||||||
|
release: buildlocal test
|
||||||
|
gh release create v$(VERSION) --generate-notes
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
18
Makefile.dist
Normal file
18
Makefile.dist
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# -*-make-*-
|
||||||
|
|
||||||
|
.PHONY: install all
|
||||||
|
|
||||||
|
tool = rpn
|
||||||
|
PREFIX = /usr/local
|
||||||
|
UID = root
|
||||||
|
GID = 0
|
||||||
|
|
||||||
|
all:
|
||||||
|
@echo "Type 'sudo make install' to install the tool."
|
||||||
|
@echo "To change prefix, type 'sudo make install PREFIX=/opt'"
|
||||||
|
|
||||||
|
install:
|
||||||
|
install -d -o $(UID) -g $(GID) $(PREFIX)/bin
|
||||||
|
install -d -o $(UID) -g $(GID) $(PREFIX)/share/doc
|
||||||
|
install -o $(UID) -g $(GID) -m 555 $(tool) $(PREFIX)/sbin/
|
||||||
|
install -o $(UID) -g $(GID) -m 444 *.md $(PREFIX)/share/doc/
|
||||||
15
README.md
15
README.md
@@ -1,7 +1,7 @@
|
|||||||
[](https://goreportcard.com/report/github.com/tlinden/yadu)
|
[](https://ci.codeberg.org/repos/15686)
|
||||||
[](https://github.com/tlinden/yadu/actions)
|
[](https://goreportcard.com/report/github.com/tlinden/yadu)
|
||||||
[](https://raw.githack.com/wiki/tlinden/yadu/coverage.html)
|
[](https://codeberg.org/scip/yadu/raw/branch/main/LICENSE)
|
||||||

|
[](https://godoc.org/github.com/tlinden/yadu)
|
||||||
|
|
||||||
# yadu - a human readable yaml based slog.Handler
|
# yadu - a human readable yaml based slog.Handler
|
||||||
|
|
||||||
@@ -27,6 +27,8 @@ The log format generated by yadu looks like this:
|
|||||||
```go
|
```go
|
||||||
logger := slog.New(yadu.NewHandler(os.Stdout, nil))
|
logger := slog.New(yadu.NewHandler(os.Stdout, nil))
|
||||||
|
|
||||||
|
type body string
|
||||||
|
|
||||||
type Ammo struct {
|
type Ammo struct {
|
||||||
Forweapon string
|
Forweapon string
|
||||||
Impact int
|
Impact int
|
||||||
@@ -71,7 +73,7 @@ See `example/example.go` for usage.
|
|||||||
|
|
||||||
Execute this to add the module to your project:
|
Execute this to add the module to your project:
|
||||||
```sh
|
```sh
|
||||||
go get github.com/tlinden/yadu
|
go get github.com/tlinden/yadu/v2
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
@@ -118,15 +120,12 @@ handler][humane]. Also helpfull was the [guide to writing `slog` handlers][guid
|
|||||||
|
|
||||||
+ [humane slog handler][humane]
|
+ [humane slog handler][humane]
|
||||||
+ [A Guide to Writing `slog` Handlers][guide]
|
+ [A Guide to Writing `slog` Handlers][guide]
|
||||||
+ [`slog`: Golang's official structured logging package][sobyte]
|
|
||||||
+ [A Comprehensive Guide to Structured Logging in Go][betterstack]
|
+ [A Comprehensive Guide to Structured Logging in Go][betterstack]
|
||||||
|
|
||||||
[humane]: https://github.com/telemachus/humane/tree/main
|
[humane]: https://github.com/telemachus/humane/tree/main
|
||||||
[guide]: https://github.com/golang/example/tree/master/slog-handler-guide
|
[guide]: https://github.com/golang/example/tree/master/slog-handler-guide
|
||||||
[mrkaran]: https://mrkaran.dev/posts/structured-logging-in-go-with-slog/
|
|
||||||
[betterstack]: https://betterstack.com/community/guides/logging/logging-in-go/
|
[betterstack]: https://betterstack.com/community/guides/logging/logging-in-go/
|
||||||
|
|
||||||
|
|
||||||
## LICENSE
|
## LICENSE
|
||||||
|
|
||||||
This module is published under the terms of the BSD 3-Clause
|
This module is published under the terms of the BSD 3-Clause
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/tlinden/yadu"
|
"github.com/tlinden/yadu/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type body string
|
type body string
|
||||||
@@ -16,6 +16,12 @@ type Ammo struct {
|
|||||||
Range int
|
Range int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *Ammo) LogValue() slog.Value {
|
||||||
|
return slog.GroupValue(
|
||||||
|
slog.String("Forweapon", a.Forweapon),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
type Enemy struct {
|
type Enemy struct {
|
||||||
Alive bool
|
Alive bool
|
||||||
Health int
|
Health int
|
||||||
@@ -24,6 +30,12 @@ type Enemy struct {
|
|||||||
Ammo []Ammo
|
Ammo []Ammo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (e *Enemy) LogValue() slog.Value {
|
||||||
|
return slog.GroupValue(
|
||||||
|
slog.String("name", e.Name),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func removeTime(_ []string, a slog.Attr) slog.Attr {
|
func removeTime(_ []string, a slog.Attr) slog.Attr {
|
||||||
if a.Key == slog.TimeKey {
|
if a.Key == slog.TimeKey {
|
||||||
return slog.Attr{}
|
return slog.Attr{}
|
||||||
@@ -35,6 +47,7 @@ func main() {
|
|||||||
opts := &yadu.Options{
|
opts := &yadu.Options{
|
||||||
Level: slog.LevelDebug,
|
Level: slog.LevelDebug,
|
||||||
ReplaceAttr: removeTime,
|
ReplaceAttr: removeTime,
|
||||||
|
AddSource: true,
|
||||||
}
|
}
|
||||||
|
|
||||||
logger := slog.New(yadu.NewHandler(os.Stdout, opts))
|
logger := slog.New(yadu.NewHandler(os.Stdout, opts))
|
||||||
@@ -46,6 +59,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
slog.Info("info", "enemy", e, "spawn", 199)
|
slog.Info("info", "enemy", e, "spawn", 199)
|
||||||
|
slog.Info("info", "ammo", &Ammo{Forweapon: "axe", Impact: 1})
|
||||||
slog.Info("connecting", "enemies", 100, "players", 2, "world", "600x800")
|
slog.Info("connecting", "enemies", 100, "players", 2, "world", "600x800")
|
||||||
slog.Debug("debug text")
|
slog.Debug("debug text")
|
||||||
slog.Error("error")
|
slog.Error("error")
|
||||||
|
|||||||
6
go.mod
6
go.mod
@@ -1,4 +1,4 @@
|
|||||||
module github.com/tlinden/yadu
|
module github.com/tlinden/yadu/v2
|
||||||
|
|
||||||
go 1.21
|
go 1.21
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ require (
|
|||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
golang.org/x/sys v0.14.0 // indirect
|
golang.org/x/sys v0.29.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
6
go.sum
6
go.sum
@@ -2,13 +2,19 @@ github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
|
|||||||
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
|
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
|
||||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||||
|
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/tlinden/yadu v0.1.3 h1:5cRCUmj+l5yvlM2irtpFBIJwVV2DPEgYSaWvF19FtcY=
|
||||||
|
github.com/tlinden/yadu v0.1.3/go.mod h1:l3bRmHKL9zGAR6pnBHY2HRPxBecf7L74BoBgOOpTcUA=
|
||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
|
||||||
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||||
|
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
|||||||
139
handler.go
139
handler.go
@@ -3,9 +3,11 @@ package yadu
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"runtime"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -15,22 +17,56 @@ import (
|
|||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const VERSION = "0.1.3"
|
||||||
|
|
||||||
// We use RFC datestring by default
|
// We use RFC datestring by default
|
||||||
const DefaultTimeFormat = "2006-01-02T03:04.05 MST"
|
const DefaultTimeFormat = "2006-01-02T03:04.05 MST"
|
||||||
|
|
||||||
// Default log level is INFO:
|
// Default log level is INFO:
|
||||||
const defaultLevel = slog.LevelInfo
|
const defaultLevel = slog.LevelInfo
|
||||||
|
|
||||||
|
// holds attributes added with logger.With()
|
||||||
|
type attributes map[string]interface{}
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
writer io.Writer
|
writer io.Writer
|
||||||
mu *sync.Mutex
|
mu *sync.Mutex
|
||||||
level slog.Leveler
|
level slog.Leveler
|
||||||
groups []string
|
groups []string
|
||||||
attrs string
|
attrs attributes
|
||||||
timeFormat string
|
timeFormat string
|
||||||
replaceAttr func(groups []string, a slog.Attr) slog.Attr
|
replaceAttr func(groups []string, a slog.Attr) slog.Attr
|
||||||
addSource bool
|
addSource bool
|
||||||
indenter *regexp.Regexp
|
indenter *regexp.Regexp
|
||||||
|
|
||||||
|
/*
|
||||||
|
This is being used in Postprocess() to fix
|
||||||
|
https://github.com/go-yaml/yaml/issues/1020 and
|
||||||
|
https://github.com/tlinden/yadu/issues/12 respectively.
|
||||||
|
|
||||||
|
yaml.v3 follows the YAML standard and quotes all keys and values
|
||||||
|
matching this regex (see https://yaml.org/type/bool.html):
|
||||||
|
`y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF`
|
||||||
|
|
||||||
|
The problem is, that the YAML "standard" does not state wether
|
||||||
|
this applies to values or keys or values&keys and most
|
||||||
|
implementors, as gopkg.in/yaml.v3, do it just for keys and values.
|
||||||
|
|
||||||
|
Therefore if we dump a struct containing a key "Y" it ends up
|
||||||
|
being quoted, while any other keys remain unquoted, which looks
|
||||||
|
pretty ugly, makes evaluating the output harder, especially in
|
||||||
|
game development where you have to dump coordinates, points etc,
|
||||||
|
all containing X,Y with X unquoted and Y quoted.
|
||||||
|
|
||||||
|
To fix this utter nonsence, I just replace all quotes in all
|
||||||
|
keys. Period. This is just a logging module, nobody will and can
|
||||||
|
use its output to postprocess it with some yaml parser, because
|
||||||
|
we not only dump the structs as yaml, we also write a one liner
|
||||||
|
in front of it with the timestamp and the message. So, we don't
|
||||||
|
output valid YAML anyway and we don't give a shit about
|
||||||
|
compliance because of this. AND because this rule is bullshit.
|
||||||
|
*/
|
||||||
|
yamlcleaner *regexp.Regexp
|
||||||
}
|
}
|
||||||
|
|
||||||
// Options are options for the Yadu [log/slog.Handler].
|
// Options are options for the Yadu [log/slog.Handler].
|
||||||
@@ -49,6 +85,7 @@ type Options struct {
|
|||||||
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
|
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
|
||||||
TimeFormat string
|
TimeFormat string
|
||||||
AddSource bool
|
AddSource bool
|
||||||
|
NoColor bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
||||||
@@ -67,11 +104,28 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
|||||||
|
|
||||||
fields := make(map[string]interface{}, r.NumAttrs())
|
fields := make(map[string]interface{}, r.NumAttrs())
|
||||||
r.Attrs(func(a slog.Attr) bool {
|
r.Attrs(func(a slog.Attr) bool {
|
||||||
fields[a.Key] = a.Value.Any()
|
//fields[a.Key] = a.Value.Any()
|
||||||
|
a.Value = a.Value.Resolve()
|
||||||
|
wa := make(map[string]interface{})
|
||||||
|
h.appendAttr(wa, a)
|
||||||
|
fields[a.Key] = wa[a.Key]
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
tree := h.attrs
|
tree := ""
|
||||||
|
source := ""
|
||||||
|
|
||||||
|
if h.addSource && r.PC != 0 {
|
||||||
|
source = h.getSource(r.PC)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(h.attrs) > 0 {
|
||||||
|
bytetree, err := yaml.Marshal(h.attrs)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tree = h.Postprocess(bytetree)
|
||||||
|
}
|
||||||
|
|
||||||
if len(fields) > 0 {
|
if len(fields) > 0 {
|
||||||
bytetree, err := yaml.Marshal(&fields)
|
bytetree, err := yaml.Marshal(&fields)
|
||||||
@@ -79,7 +133,7 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
tree = h.Postprocess(bytetree)
|
tree += h.Postprocess(bytetree)
|
||||||
}
|
}
|
||||||
|
|
||||||
timeStr := ""
|
timeStr := ""
|
||||||
@@ -105,6 +159,8 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
|||||||
buf.WriteString(" ")
|
buf.WriteString(" ")
|
||||||
buf.WriteString(msg)
|
buf.WriteString(msg)
|
||||||
buf.WriteString(" ")
|
buf.WriteString(" ")
|
||||||
|
buf.WriteString(source)
|
||||||
|
buf.WriteString(" ")
|
||||||
buf.WriteString(color.WhiteString(tree))
|
buf.WriteString(color.WhiteString(tree))
|
||||||
buf.WriteString("\n")
|
buf.WriteString("\n")
|
||||||
|
|
||||||
@@ -115,8 +171,17 @@ func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// report caller source+line as yaml string
|
||||||
|
func (h *Handler) getSource(pc uintptr) string {
|
||||||
|
fs := runtime.CallersFrames([]uintptr{pc})
|
||||||
|
source, _ := fs.Next()
|
||||||
|
return fmt.Sprintf("%s: %d", source.File, source.Line)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) Postprocess(yamlstr []byte) string {
|
func (h *Handler) Postprocess(yamlstr []byte) string {
|
||||||
return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(string(yamlstr), " "))
|
tree := string(yamlstr)
|
||||||
|
clean := h.yamlcleaner.ReplaceAllString(tree, "$1$2:")
|
||||||
|
return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(clean, " "))
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHandler returns a [log/slog.Handler] using the receiver's options.
|
// NewHandler returns a [log/slog.Handler] using the receiver's options.
|
||||||
@@ -134,6 +199,7 @@ func NewHandler(out io.Writer, opts *Options) *Handler {
|
|||||||
replaceAttr: opts.ReplaceAttr,
|
replaceAttr: opts.ReplaceAttr,
|
||||||
addSource: opts.AddSource,
|
addSource: opts.AddSource,
|
||||||
indenter: regexp.MustCompile(`(?m)^`),
|
indenter: regexp.MustCompile(`(?m)^`),
|
||||||
|
yamlcleaner: regexp.MustCompile("(?m)^( *)\"([^\"]*)\":"),
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Level == nil {
|
if opts.Level == nil {
|
||||||
@@ -144,6 +210,10 @@ func NewHandler(out io.Writer, opts *Options) *Handler {
|
|||||||
h.timeFormat = DefaultTimeFormat
|
h.timeFormat = DefaultTimeFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opts.NoColor {
|
||||||
|
color.NoColor = true
|
||||||
|
}
|
||||||
|
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,24 +223,59 @@ func (h *Handler) Enabled(_ context.Context, l slog.Level) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// attributes plus attrs.
|
// attributes plus attrs.
|
||||||
|
func (h *Handler) appendAttr(wa map[string]interface{}, a slog.Attr) {
|
||||||
|
a.Value = a.Value.Resolve()
|
||||||
|
|
||||||
|
if a.Value.Kind() == slog.KindGroup {
|
||||||
|
attrs := a.Value.Group()
|
||||||
|
name := ""
|
||||||
|
if len(attrs) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if a.Key != "" {
|
||||||
|
name = a.Key
|
||||||
|
h.groups = append(h.groups, a.Key)
|
||||||
|
}
|
||||||
|
|
||||||
|
innerwa := make(map[string]interface{})
|
||||||
|
for _, a := range attrs {
|
||||||
|
h.appendAttr(innerwa, a)
|
||||||
|
}
|
||||||
|
wa[name] = innerwa
|
||||||
|
|
||||||
|
if a.Key != "" && len(h.groups) > 0 {
|
||||||
|
h.groups = h.groups[:len(h.groups)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.replaceAttr != nil {
|
||||||
|
a = h.replaceAttr(h.groups, a)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !a.Equal(slog.Attr{}) {
|
||||||
|
wa[a.Key] = a.Value.Any()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sub logger is to be created, possibly with attrs, add them to h.attrs
|
||||||
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||||
if len(attrs) == 0 {
|
if len(attrs) == 0 {
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
fields := make(map[string]interface{}, len(attrs))
|
|
||||||
for _, a := range attrs {
|
|
||||||
fields[a.Key] = a.Value.Any()
|
|
||||||
}
|
|
||||||
|
|
||||||
bytetree, err := yaml.Marshal(&fields)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
h2 := h.clone()
|
h2 := h.clone()
|
||||||
|
|
||||||
h2.attrs += string(bytetree)
|
wa := make(map[string]interface{})
|
||||||
|
|
||||||
|
for _, a := range attrs {
|
||||||
|
h2.appendAttr(wa, a)
|
||||||
|
}
|
||||||
|
|
||||||
|
h2.attrs = wa
|
||||||
|
|
||||||
return h2
|
return h2
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,5 +300,7 @@ func (h *Handler) clone() *Handler {
|
|||||||
timeFormat: h.timeFormat,
|
timeFormat: h.timeFormat,
|
||||||
replaceAttr: h.replaceAttr,
|
replaceAttr: h.replaceAttr,
|
||||||
addSource: h.addSource,
|
addSource: h.addSource,
|
||||||
|
indenter: h.indenter,
|
||||||
|
yamlcleaner: h.yamlcleaner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
148
handler_test.go
148
handler_test.go
@@ -7,7 +7,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/tlinden/yadu"
|
"github.com/fatih/color"
|
||||||
|
"github.com/tlinden/yadu/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type body string
|
type body string
|
||||||
@@ -19,6 +20,12 @@ type Ammo struct {
|
|||||||
Range float32
|
Range float32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *Ammo) LogValue() slog.Value {
|
||||||
|
return slog.GroupValue(
|
||||||
|
slog.String("Forweapon", "Use weapon: "+a.Forweapon),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
type Enemy struct {
|
type Enemy struct {
|
||||||
Alive bool
|
Alive bool
|
||||||
Health int
|
Health int
|
||||||
@@ -27,11 +34,17 @@ type Enemy struct {
|
|||||||
Ammo []Ammo
|
Ammo []Ammo
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Point struct {
|
||||||
|
Y, N, True, False int
|
||||||
|
}
|
||||||
|
|
||||||
type Tests struct {
|
type Tests struct {
|
||||||
name string
|
name string
|
||||||
want string
|
want string
|
||||||
negate bool
|
negate bool
|
||||||
opts *yadu.Options
|
opts yadu.Options
|
||||||
|
with slog.Attr
|
||||||
|
haswith bool
|
||||||
}
|
}
|
||||||
|
|
||||||
const testTimeFormat = "03:04.05"
|
const testTimeFormat = "03:04.05"
|
||||||
@@ -47,6 +60,16 @@ var tests = []Tests{
|
|||||||
want: "ammo:",
|
want: "ammo:",
|
||||||
negate: false,
|
negate: false,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "has-ammo-logvaluer",
|
||||||
|
want: "Use weapon: Axe",
|
||||||
|
negate: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "has-ammo-logvaluer-does-resolve",
|
||||||
|
want: "impact: 50", // should NOT appear
|
||||||
|
negate: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "has-alive",
|
name: "has-alive",
|
||||||
want: "alive: true",
|
want: "alive: true",
|
||||||
@@ -65,7 +88,7 @@ var tests = []Tests{
|
|||||||
{
|
{
|
||||||
name: "has-no-time",
|
name: "has-no-time",
|
||||||
want: time.Now().Format(yadu.DefaultTimeFormat),
|
want: time.Now().Format(yadu.DefaultTimeFormat),
|
||||||
opts: &yadu.Options{
|
opts: yadu.Options{
|
||||||
ReplaceAttr: removeTime,
|
ReplaceAttr: removeTime,
|
||||||
},
|
},
|
||||||
negate: true,
|
negate: true,
|
||||||
@@ -73,21 +96,83 @@ var tests = []Tests{
|
|||||||
{
|
{
|
||||||
name: "has-custom-time",
|
name: "has-custom-time",
|
||||||
want: time.Now().Format(testTimeFormat),
|
want: time.Now().Format(testTimeFormat),
|
||||||
opts: &yadu.Options{
|
opts: yadu.Options{
|
||||||
TimeFormat: testTimeFormat,
|
TimeFormat: testTimeFormat,
|
||||||
},
|
},
|
||||||
negate: false,
|
negate: false,
|
||||||
},
|
},
|
||||||
// FIXME: add WithGroup + WithAttr tests
|
{
|
||||||
|
name: "with-group",
|
||||||
|
want: "pid:",
|
||||||
|
negate: false,
|
||||||
|
with: slog.Group("program_info",
|
||||||
|
slog.Int("pid", 1923),
|
||||||
|
slog.Bool("alive", true),
|
||||||
|
),
|
||||||
|
haswith: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "has-debug",
|
||||||
|
want: "DEBUG",
|
||||||
|
negate: false,
|
||||||
|
opts: yadu.Options{
|
||||||
|
Level: slog.LevelDebug,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "has-warn",
|
||||||
|
want: "WARN",
|
||||||
|
negate: false,
|
||||||
|
opts: yadu.Options{
|
||||||
|
Level: slog.LevelWarn,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "has-error",
|
||||||
|
want: "ERROR",
|
||||||
|
negate: false,
|
||||||
|
opts: yadu.Options{
|
||||||
|
Level: slog.LevelError,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "has-source",
|
||||||
|
want: "handler_test.go",
|
||||||
|
negate: false,
|
||||||
|
opts: yadu.Options{
|
||||||
|
AddSource: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// check if output is NOT colored when disabling it
|
||||||
|
name: "disable-color",
|
||||||
|
want: "\x1b[0m",
|
||||||
|
negate: true,
|
||||||
|
opts: yadu.Options{
|
||||||
|
NoColor: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// check if output is colored
|
||||||
|
name: "enable-color",
|
||||||
|
want: "\x1b[0m",
|
||||||
|
negate: false,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetEnemy() *Enemy {
|
func GetEnemy() *Enemy {
|
||||||
return &Enemy{Alive: true, Health: 10, Name: "Bodo", Body: "body\nbody\n",
|
return &Enemy{Alive: true, Health: 10, Name: "Bodo", Body: "body\nbody\n",
|
||||||
Ammo: []Ammo{{Forweapon: "Railgun", Range: 400, Impact: 100, Cost: 100000}},
|
Ammo: []Ammo{{Forweapon: "Railgun", Range: 400, Impact: 100, Cost: 100000}},
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetAmmo() *Ammo {
|
||||||
|
return &Ammo{Forweapon: "Axe", Range: 50, Impact: 1, Cost: 50}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPoint() *Point {
|
||||||
|
return &Point{}
|
||||||
|
}
|
||||||
func removeTime(_ []string, a slog.Attr) slog.Attr {
|
func removeTime(_ []string, a slog.Attr) slog.Attr {
|
||||||
if a.Key == slog.TimeKey {
|
if a.Key == slog.TimeKey {
|
||||||
return slog.Attr{}
|
return slog.Attr{}
|
||||||
@@ -95,15 +180,35 @@ func removeTime(_ []string, a slog.Attr) slog.Attr {
|
|||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test(t *testing.T) {
|
func TestLogger(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
ttopts := tt.opts
|
||||||
|
logger := slog.New(yadu.NewHandler(&buf, &ttopts))
|
||||||
|
|
||||||
logger := slog.New(yadu.NewHandler(&buf, tt.opts))
|
if !tt.with.Equal(slog.Attr{}) {
|
||||||
|
logger = logger.With(tt.with)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !tt.opts.NoColor {
|
||||||
|
color.NoColor = false
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
switch tt.opts.Level {
|
||||||
|
case slog.LevelDebug:
|
||||||
|
logger.Debug("attack", "enemy", GetEnemy(), "ammo", GetAmmo())
|
||||||
|
case slog.LevelWarn:
|
||||||
|
logger.Warn("attack", "enemy", GetEnemy(), "ammo", GetAmmo())
|
||||||
|
case slog.LevelError:
|
||||||
|
logger.Error("attack", "enemy", GetEnemy(), "ammo", GetAmmo())
|
||||||
|
default:
|
||||||
|
logger.Info("attack", "enemy", GetEnemy(), "ammo", GetAmmo())
|
||||||
|
}
|
||||||
|
|
||||||
logger.Info("attack", "enemy", GetEnemy())
|
|
||||||
got := buf.String()
|
got := buf.String()
|
||||||
|
|
||||||
if strings.Contains(got, tt.want) == tt.negate {
|
if strings.Contains(got, tt.want) == tt.negate {
|
||||||
@@ -113,3 +218,22 @@ func Test(t *testing.T) {
|
|||||||
buf.Reset()
|
buf.Reset()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestYamlCleaner(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
logger := slog.New(yadu.NewHandler(&buf, &yadu.Options{}))
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
|
||||||
|
logger.Info("got a point", "point", GetPoint())
|
||||||
|
|
||||||
|
got := buf.String()
|
||||||
|
|
||||||
|
bools := []string{"y:", "n:", "true:", "false:"}
|
||||||
|
for _, want := range bools {
|
||||||
|
if !strings.Contains(got, want) {
|
||||||
|
t.Errorf("test TestYamlCleaner failed.\n want: %s:\n got: %s\n", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user