15 Commits

Author SHA1 Message Date
ee076a4df8 moved to codeberg 2025-12-06 20:58:07 +01:00
T. von Dein
6fed3af065 move to codeberg (#15) 2025-12-06 20:56:16 +01:00
ee3b4e8e9b fix linting errors 2024-02-14 13:14:21 +01:00
9d34e78475 fix #12: unquote eventually quoted keys generated by yaml.Marshall() 2024-02-14 13:06:30 +01:00
e9af16a8a2 bump version 2024-02-10 13:17:57 +01:00
9ede62037a fix #10: check group length before manipulation 2024-02-10 13:17:57 +01:00
5c0aadd54a fix #6: support LogValuer() attributes 2024-01-22 13:59:51 +01:00
33798bddb3 Fix #7: implement AddSource flag, add as message 2024-01-22 13:59:51 +01:00
T.v.Dein
d53c1db7d0 added ref badge (#5) 2024-01-19 18:48:42 +01:00
T.v.Dein
1c65084c37 Develop (#4)
* finalized tests, made .With() work to create sub-loggers
2024-01-19 13:45:25 +01:00
T.v.Dein
7391d990bb Develop (#3)
* finalized tests, made .With() work to create sub-loggers
2024-01-19 13:42:26 +01:00
T.v.Dein
a993959de7 finalized tests, made .With() work to create sub-loggers (#2)
Co-authored-by: Thomas von Dein <tom@vondein.org>
2024-01-19 13:40:00 +01:00
9547dccc7f Merge branch 'main' of github.com:TLINDEN/yadu 2024-01-19 08:33:44 +01:00
f733a30fab url + example fixes 2024-01-19 08:15:06 +01:00
T.v.Dein
ec3f0b7fc3 Add indenter member to clone(), fixes #1 2024-01-18 21:22:25 +01:00
8 changed files with 10 additions and 482 deletions

View File

@@ -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

View File

@@ -1,32 +0,0 @@
# Copyright © 2023 Thomas von Dein
# This module is published under the terms of the BSD 3-Clause
# License. Please read the file LICENSE for details.
#
# no need to modify anything below
all: buildlocal
buildlocal:
go build
clean:
rm -rf $(tool) coverage.out testdata t/out example/example
test: clean
go test $(ARGS)
singletest:
@echo "Call like this: make singletest TEST=TestPrepareColumns ARGS=-v"
go test -run $(TEST) $(ARGS)
cover-report:
go test -cover -coverprofile=coverage.out
go tool cover -html=coverage.out
goupdate:
go get -t -u=patch ./...
lint:
golangci-lint run -p bugs -p unused

View File

@@ -1,10 +1,13 @@
[![Go Report Card](https://goreportcard.com/badge/github.com/tlinden/yadu)](https://goreportcard.com/report/github.com/tlinden/yadu)
[![Actions](https://github.com/tlinden/yadu/actions/workflows/ci.yaml/badge.svg)](https://github.com/tlinden/yadu/actions)
[![Go Coverage](https://github.com/tlinden/yadu/wiki/coverage.svg)](https://raw.githack.com/wiki/tlinden/yadu/coverage.html)
![GitHub License](https://img.shields.io/github/license/tlinden/yadu)
[![status-badge](https://ci.codeberg.org/api/badges/15686/status.svg)](https://ci.codeberg.org/repos/15686)
[![Go Report Card](https://goreportcard.com/badge/github.com/tlinden/yadu)](https://goreportcard.com/report/github.com/tlinden/yadu)
[![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://codeberg.org/scip/yadu/raw/branch/main/LICENSE)
[![GoDoc](https://godoc.org/github.com/tlinden/yadu?status.svg)](https://godoc.org/github.com/tlinden/yadu)
# yadu - a human readable yaml based slog.Handler
> [!CAUTION]
> This software is now being maintained on [Codeberg](https://codeberg.org/scip/yadu/).
## Introduction
Package yadu provides a handler for the log/slog logging framework.
@@ -27,6 +30,8 @@ The log format generated by yadu looks like this:
```go
logger := slog.New(yadu.NewHandler(os.Stdout, nil))
type body string
type Ammo struct {
Forweapon string
Impact int
@@ -71,7 +76,7 @@ See `example/example.go` for usage.
Execute this to add the module to your project:
```sh
go get github.com/tlinden/yadu
go get github.com/tlinden/yadu/v2
```
## Configuration
@@ -118,15 +123,12 @@ handler][humane]. Also helpfull was the [guide to writing `slog` handlers][guid
+ [humane slog handler][humane]
+ [A Guide to Writing `slog` Handlers][guide]
+ [`slog`: Golang's official structured logging package][sobyte]
+ [A Comprehensive Guide to Structured Logging in Go][betterstack]
[humane]: https://github.com/telemachus/humane/tree/main
[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/
## LICENSE
This module is published under the terms of the BSD 3-Clause

View File

@@ -1,52 +0,0 @@
package main
import (
"log/slog"
"os"
"github.com/tlinden/yadu"
)
type body string
type Ammo struct {
Forweapon string
Impact int
Cost int
Range int
}
type Enemy struct {
Alive bool
Health int
Name string
Body body `yaml:"-"`
Ammo []Ammo
}
func removeTime(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}
func main() {
opts := &yadu.Options{
Level: slog.LevelDebug,
ReplaceAttr: removeTime,
}
logger := slog.New(yadu.NewHandler(os.Stdout, opts))
slog.SetDefault(logger)
e := &Enemy{Alive: true, Health: 10, Name: "Bodo", Body: "body\nbody\n",
Ammo: []Ammo{{Forweapon: "Railgun", Range: 400, Impact: 100, Cost: 100000}},
}
slog.Info("info", "enemy", e, "spawn", 199)
slog.Info("connecting", "enemies", 100, "players", 2, "world", "600x800")
slog.Debug("debug text")
slog.Error("error")
}

14
go.mod
View File

@@ -1,14 +0,0 @@
module github.com/tlinden/yadu
go 1.21
require (
github.com/fatih/color v1.16.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
golang.org/x/sys v0.14.0 // indirect
)

15
go.sum
View File

@@ -1,15 +0,0 @@
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/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-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/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
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.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.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/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -1,199 +0,0 @@
package yadu
import (
"bytes"
"context"
"io"
"log/slog"
"regexp"
"slices"
"strings"
"sync"
"gopkg.in/yaml.v3"
"github.com/fatih/color"
)
// We use RFC datestring by default
const DefaultTimeFormat = "2006-01-02T03:04.05 MST"
// Default log level is INFO:
const defaultLevel = slog.LevelInfo
type Handler struct {
writer io.Writer
mu *sync.Mutex
level slog.Leveler
groups []string
attrs string
timeFormat string
replaceAttr func(groups []string, a slog.Attr) slog.Attr
addSource bool
indenter *regexp.Regexp
}
// Options are options for the Yadu [log/slog.Handler].
//
// Level sets the minimum log level.
//
// ReplaceAttr is a function you can define to customize how supplied
// attrs are being handled. It is empty by default, so nothing will be
// altered.
//
// Loglevel and message cannot be altered using ReplaceAttr. Timestamp
// can only be removed, see example. Keep in mind that everything will
// be passed to yaml.Marshal() in the end.
type Options struct {
Level slog.Leveler
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
TimeFormat string
AddSource bool
}
func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
level := r.Level.String() + ":"
switch r.Level {
case slog.LevelDebug:
level = color.MagentaString(level)
case slog.LevelInfo:
level = color.BlueString(level)
case slog.LevelWarn:
level = color.YellowString(level)
case slog.LevelError:
level = color.RedString(level)
}
fields := make(map[string]interface{}, r.NumAttrs())
r.Attrs(func(a slog.Attr) bool {
fields[a.Key] = a.Value.Any()
return true
})
tree := h.attrs
if len(fields) > 0 {
bytetree, err := yaml.Marshal(&fields)
if err != nil {
return err
}
tree = h.Postprocess(bytetree)
}
timeStr := ""
timeAttr := slog.Time(slog.TimeKey, r.Time)
if h.replaceAttr != nil {
timeAttr = h.replaceAttr(nil, timeAttr)
}
if !r.Time.IsZero() && !timeAttr.Equal(slog.Attr{}) {
timeStr = r.Time.Format(h.timeFormat)
}
msg := color.CyanString(r.Message)
buf := bytes.Buffer{}
if len(timeStr) > 0 {
buf.WriteString(timeStr)
buf.WriteString(" ")
}
buf.WriteString(level)
buf.WriteString(" ")
buf.WriteString(msg)
buf.WriteString(" ")
buf.WriteString(color.WhiteString(tree))
buf.WriteString("\n")
h.mu.Lock()
defer h.mu.Unlock()
_, err := h.writer.Write(buf.Bytes())
return err
}
func (h *Handler) Postprocess(yamlstr []byte) string {
return "\n " + strings.TrimSpace(h.indenter.ReplaceAllString(string(yamlstr), " "))
}
// NewHandler returns a [log/slog.Handler] using the receiver's options.
// Default options are used if opts is nil.
func NewHandler(out io.Writer, opts *Options) *Handler {
if opts == nil {
opts = &Options{}
}
h := &Handler{
writer: out,
mu: &sync.Mutex{},
level: opts.Level,
timeFormat: opts.TimeFormat,
replaceAttr: opts.ReplaceAttr,
addSource: opts.AddSource,
indenter: regexp.MustCompile(`(?m)^`),
}
if opts.Level == nil {
h.level = defaultLevel
}
if h.timeFormat == "" {
h.timeFormat = DefaultTimeFormat
}
return h
}
// Enabled indicates whether the receiver logs at the given level.
func (h *Handler) Enabled(_ context.Context, l slog.Level) bool {
return l >= h.level.Level()
}
// attributes plus attrs.
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
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.attrs += string(bytetree)
return h2
}
// WithGroup returns a new [log/slog.Handler] with name appended to the
// receiver's groups.
func (h *Handler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := h.clone()
h2.groups = append(h2.groups, name)
return h2
}
func (h *Handler) clone() *Handler {
return &Handler{
writer: h.writer,
mu: h.mu,
level: h.level,
groups: slices.Clip(h.groups),
attrs: h.attrs,
timeFormat: h.timeFormat,
replaceAttr: h.replaceAttr,
addSource: h.addSource,
}
}

View File

@@ -1,115 +0,0 @@
package yadu_test
import (
"bytes"
"log/slog"
"strings"
"testing"
"time"
"github.com/tlinden/yadu"
)
type body string
type Ammo struct {
Forweapon string
Impact int
Cost int
Range float32
}
type Enemy struct {
Alive bool
Health int
Name string
Body body `yaml:"-"`
Ammo []Ammo
}
type Tests struct {
name string
want string
negate bool
opts *yadu.Options
}
const testTimeFormat = "03:04.05"
var tests = []Tests{
{
name: "has-railgun",
want: "forweapon: Railgun",
negate: false,
},
{
name: "has-ammo",
want: "ammo:",
negate: false,
},
{
name: "has-alive",
want: "alive: true",
negate: false,
},
{
name: "has-no-body",
want: "body:",
negate: true,
},
{
name: "has-time",
want: time.Now().Format(yadu.DefaultTimeFormat),
negate: false,
},
{
name: "has-no-time",
want: time.Now().Format(yadu.DefaultTimeFormat),
opts: &yadu.Options{
ReplaceAttr: removeTime,
},
negate: true,
},
{
name: "has-custom-time",
want: time.Now().Format(testTimeFormat),
opts: &yadu.Options{
TimeFormat: testTimeFormat,
},
negate: false,
},
// FIXME: add WithGroup + WithAttr tests
}
func GetEnemy() *Enemy {
return &Enemy{Alive: true, Health: 10, Name: "Bodo", Body: "body\nbody\n",
Ammo: []Ammo{{Forweapon: "Railgun", Range: 400, Impact: 100, Cost: 100000}},
}
}
func removeTime(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}
func Test(t *testing.T) {
t.Parallel()
for _, tt := range tests {
var buf bytes.Buffer
logger := slog.New(yadu.NewHandler(&buf, tt.opts))
logger.Info("attack", "enemy", GetEnemy())
got := buf.String()
if strings.Contains(got, tt.want) == tt.negate {
t.Errorf("test %s failed.\n want:\n%s\n got: %s\n", tt.name, tt.want, got)
}
buf.Reset()
}
}