-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b6a3720
commit 8b924d5
Showing
32 changed files
with
1,078 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
version: 2 | ||
updates: | ||
- package-ecosystem: "github-actions" | ||
directory: "/" # Don't change this despite the path being .github/workflows | ||
schedule: | ||
# Check for updates to GitHub Actions on the first day of the month | ||
interval: "monthly" | ||
|
||
- package-ecosystem: "gomod" | ||
directory: "/" | ||
schedule: | ||
# Check for updates to Go modules on the first day of the month | ||
interval: "monthly" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
on: | ||
push: | ||
branches: [main] | ||
tags: ["v*.*.*"] | ||
pull_request: | ||
types: [opened, reopened, synchronize] | ||
jobs: | ||
format-build-test: | ||
strategy: | ||
matrix: | ||
go-version: ['1.19.x', '1.21.x'] | ||
platform: [ubuntu-latest, macos-latest, windows-latest] | ||
runs-on: ${{ matrix.platform }} | ||
steps: | ||
- uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4.1.4 | ||
|
||
- uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0 | ||
with: | ||
go-version: ${{ matrix.go-version }} | ||
|
||
- if: matrix.platform == 'ubuntu-latest' | ||
run: if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then exit 1; fi | ||
|
||
- run: go build -v ./... | ||
|
||
- run: go test -cover -race -v ./... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2024 Jesse Peterson | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
module github.com/micromdm/nanolib | ||
|
||
go 1.19 | ||
|
||
require github.com/peterbourgon/diskv/v3 v3.0.1 | ||
|
||
require github.com/google/btree v1.0.0 // indirect |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= | ||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= | ||
github.com/peterbourgon/diskv/v3 v3.0.1 h1:x06SQA46+PKIUftmEujdwSEpIx8kR+M9eLYsUxeYveU= | ||
github.com/peterbourgon/diskv/v3 v3.0.1/go.mod h1:kJ5Ny7vLdARGU3WUuy6uzO6T0nb/2gWcT1JiBvRmb5o= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
// Package ctxlog allows logging of key-value pairs stored with a context. | ||
// | ||
// At a high level for a package that wants to log data using a [context]: | ||
// | ||
// 1. Create a [CtxKVFunc] function that can turn a context into | ||
// a slice of interfaces. Typically this function will read a context | ||
// key and output a key-value pair for log lines. A helper for these | ||
// functions is [SimpleStringFunc]. | ||
// 2. Attach this function to a context using [AddFunc]. | ||
// 3. At some point later attach a value to a context using | ||
// [context.WithValue]. | ||
// 4. Then, when ready to log, create a "context aware logger" using | ||
// [Logger] which will execute the CtxKVFuncs and return a logger | ||
// With the key-values from the executed functions. | ||
// | ||
// In this way we've decoupled the specific loggers, data types, keys, | ||
// context keys, and other data from themselves but still have convenient | ||
// access to log data from a context. This also allows flexible layering | ||
// of logging locations and middleware that a context may pass through. | ||
package ctxlog | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
|
||
"github.com/micromdm/nanolib/log" | ||
) | ||
|
||
// CtxKVFunc creates logger key-value pairs from a context. | ||
// CtxKVFuncs should aim to be be as efficient as possible—ideally only | ||
// doing the minimum to read context values and generate KV pairs. Each | ||
// associated CtxKVFunc is called every time we adapt a logger with | ||
// Logger. | ||
type CtxKVFunc func(context.Context) []interface{} | ||
|
||
// ctxKeyFuncs is the context key for storing and retriveing | ||
// a funcs{} struct on a context. | ||
type ctxKeyFuncs struct{} | ||
|
||
// funcs holds the associated CtxKVFunc functions to run. | ||
type funcs struct { | ||
sync.RWMutex | ||
funcs []CtxKVFunc | ||
} | ||
|
||
// AddFunc appends f to to ctx. | ||
func AddFunc(ctx context.Context, f CtxKVFunc) context.Context { | ||
if ctx == nil { | ||
return ctx | ||
} | ||
ctxFuncs, ok := ctx.Value(ctxKeyFuncs{}).(*funcs) | ||
if !ok || ctxFuncs == nil { | ||
ctxFuncs = &funcs{} | ||
} | ||
ctxFuncs.Lock() | ||
ctxFuncs.funcs = append(ctxFuncs.funcs, f) | ||
ctxFuncs.Unlock() | ||
return context.WithValue(ctx, ctxKeyFuncs{}, ctxFuncs) | ||
} | ||
|
||
// Logger executes the associated KV funcs on ctx and returns a new Logger with the results. | ||
// If ctx is nil or if there are no KV funcs associated then logger is returned as-is. | ||
func Logger(ctx context.Context, logger log.Logger) log.Logger { | ||
if ctx == nil { | ||
return logger | ||
} | ||
ctxFuncs, ok := ctx.Value(ctxKeyFuncs{}).(*funcs) | ||
if !ok || ctxFuncs == nil { | ||
return logger | ||
} | ||
var acc []interface{} | ||
ctxFuncs.RLock() | ||
for _, f := range ctxFuncs.funcs { | ||
acc = append(acc, f(ctx)...) | ||
} | ||
ctxFuncs.RUnlock() | ||
return logger.With(acc...) | ||
} | ||
|
||
// SimpleStringFunc is a helper that makes a simple CtxKVFunc that | ||
// returns a key-value pair if found on the context. | ||
func SimpleStringFunc(logKey string, ctxKey interface{}) CtxKVFunc { | ||
return func(ctx context.Context) (out []interface{}) { | ||
v, _ := ctx.Value(ctxKey).(string) | ||
if v != "" { | ||
out = []interface{}{logKey, v} | ||
} | ||
return | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package ctxlog | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/micromdm/nanolib/log" | ||
"github.com/micromdm/nanolib/log/test" | ||
) | ||
|
||
func TestCtxLog(t *testing.T) { | ||
ctx := context.Background() | ||
type ctxKeyTest1 struct{} | ||
const test1Value = "test1Value" | ||
|
||
// create a new logger | ||
var logger log.Logger = new(test.Logger) | ||
|
||
// add some initial context | ||
logger = logger.With("context1Key", "context1Value") | ||
|
||
// associate a (simple) KV func with our context key | ||
ctx = AddFunc(ctx, SimpleStringFunc("test1Key", ctxKeyTest1{})) | ||
|
||
// stick a test value on the context with the KV func context key | ||
ctx = context.WithValue(ctx, ctxKeyTest1{}, test1Value) | ||
|
||
// create a logger with context.. er, context | ||
ctxLogger := Logger(ctx, logger) | ||
|
||
// log a line | ||
ctxLogger.Info("log1Key", "log1Value") | ||
|
||
// cast to get back to our test logger (with useful methods) | ||
actuallyTestLogger := ctxLogger.(*test.Logger) | ||
|
||
// verify the original context | ||
test.TestLastLogKeyValueMatches(t, actuallyTestLogger, "context1Key", "context1Value") | ||
|
||
// check the contextually-logged log KV | ||
test.TestLastLogKeyValueMatches(t, actuallyTestLogger, "test1Key", "test1Value") | ||
|
||
// and of course the actual log line args | ||
test.TestLastLogKeyValueMatches(t, actuallyTestLogger, "log1Key", "log1Value") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
// Pacakge log is embedded (not imported) from https://github.com/jessepeterson/go-log | ||
package log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package log | ||
|
||
// Pacakge log is embedded (not imported) from: | ||
// https://github.com/jessepeterson/go-log | ||
|
||
// Logger is a generic logging interface for a structured, levelled, nest-able logger. | ||
type Logger interface { | ||
// Info logs using the info level. | ||
Info(...interface{}) | ||
|
||
// Debug logs using the debug level. | ||
Debug(...interface{}) | ||
|
||
// With returns a new nested Logger. | ||
// Usually for adding logging additional context to an existing logger. | ||
With(...interface{}) Logger | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package log | ||
|
||
// Pacakge log is embedded (not imported) from: | ||
// https://github.com/jessepeterson/go-log | ||
|
||
// nopLogger does nothing. | ||
type nopLogger struct{} | ||
|
||
// Info does nothing. | ||
func (*nopLogger) Info(_ ...interface{}) {} | ||
|
||
// Debug does nothing. | ||
func (*nopLogger) Debug(_ ...interface{}) {} | ||
|
||
// With returns the (the same) logger. | ||
func (logger *nopLogger) With(_ ...interface{}) Logger { | ||
return logger | ||
} | ||
|
||
// NopLogger is a Logger that does nothing. | ||
var NopLogger = &nopLogger{} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
// Package stdlogfmt adapts a NanoLIB Logger to the Golang standard library log package. | ||
package stdlogfmt | ||
|
||
import ( | ||
"fmt" | ||
stdlog "log" | ||
"os" | ||
"path/filepath" | ||
"runtime" | ||
"strings" | ||
"time" | ||
|
||
"github.com/micromdm/nanolib/log" | ||
) | ||
|
||
// Logger adapts a NanoLIB Logger to the Golang standard library log package. | ||
// The output format is similar to logfmt: https://brandur.org/logfmt. | ||
type Logger struct { | ||
logger *stdlog.Logger | ||
context []interface{} | ||
debug bool | ||
depth int | ||
ts bool | ||
} | ||
|
||
type Option func(*Logger) | ||
|
||
// WithLogger sets the Go standard logger to use. | ||
func WithLogger(logger *stdlog.Logger) Option { | ||
return func(l *Logger) { | ||
l.logger = logger | ||
} | ||
} | ||
|
||
// WithDebug turns on debug logging. | ||
func WithDebug() Option { | ||
return func(l *Logger) { | ||
l.debug = true | ||
} | ||
} | ||
|
||
// WithDebugFlag sets debug logging on or off. | ||
func WithDebugFlag(flag bool) Option { | ||
return func(l *Logger) { | ||
l.debug = flag | ||
} | ||
} | ||
|
||
// WithCallerDepth sets the call depth of the logger for filename and line | ||
// logging. Set depth to 0 to disable filename and line logging. | ||
func WithCallerDepth(depth int) Option { | ||
return func(l *Logger) { | ||
l.depth = depth | ||
} | ||
} | ||
|
||
// WithoutTimestamp disables outputting an RFC3339 timestamp. | ||
func WithoutTimestamp() Option { | ||
return func(l *Logger) { | ||
l.ts = false | ||
} | ||
} | ||
|
||
// New creates a new logger that adapts the Go standard log package to Logger. | ||
func New(opts ...Option) *Logger { | ||
l := &Logger{ | ||
logger: stdlog.New(os.Stderr, "", 0), | ||
depth: 1, | ||
ts: true, | ||
} | ||
for _, opt := range opts { | ||
opt(l) | ||
} | ||
return l | ||
} | ||
|
||
func (l *Logger) print(args ...interface{}) { | ||
if l.ts { | ||
args = append([]interface{}{"ts", time.Now().Format(time.RFC3339)}, args...) | ||
} | ||
if l.depth > 0 { | ||
_, filename, line, ok := runtime.Caller(l.depth + 1) | ||
if ok { | ||
caller := fmt.Sprintf("%s:%d", filepath.Base(filename), line) | ||
args = append(args, "caller", caller) | ||
} | ||
} | ||
f := strings.Repeat(" %s=%v", len(args)/2)[1:] | ||
if len(args)%2 == 1 { | ||
f += " UNKNOWN=%v" | ||
} | ||
l.logger.Printf(f, args...) | ||
} | ||
|
||
// Info logs using the info level to the standard Go logger. | ||
func (l *Logger) Info(args ...interface{}) { | ||
logs := []interface{}{"level", "info"} | ||
logs = append(logs, l.context...) | ||
logs = append(logs, args...) | ||
l.print(logs...) | ||
} | ||
|
||
// Debug logs using the debug level to the standard Go logger. | ||
func (l *Logger) Debug(args ...interface{}) { | ||
if l.debug { | ||
logs := []interface{}{"level", "debug"} | ||
logs = append(logs, l.context...) | ||
logs = append(logs, args...) | ||
l.print(logs...) | ||
} | ||
} | ||
|
||
// With returns a new nested Logger that logs to the standard Go logger. | ||
func (l *Logger) With(args ...interface{}) log.Logger { | ||
l2 := *l | ||
l2.context = append(l2.context, args...) | ||
return &l2 | ||
} |
Oops, something went wrong.