m/p/supervisor: implement sub-loggers
This permits logging from a runnable into a logtree sub-DN that is not
backed by an actualy child runnable. For example, 'root.foo' can request
a SubLogger with name 'bar' to emit logs into 'root.foo.bar'.
This is in preparation for logging RPC calls within supervised
runnables, but can also come in handy in other situations where we'd
like to log to separete 'topics' within a single runnable.
This breaks 1:1 correspondence between logtree DNs and supervisor DNs.
An alternative would be to introduce extra 'tags'/'topics' eg
root.foo:bar, but that would require encoding extra logic to the
logtree. However, that would perhaps allow us to introduce higher
cardinality child loggers, with a logger per RPC. We'll have to consider
this at some later point.
Let's see where this takes us, there's a chance we'll roll this
back if it's too confusing from an UX point of view.
Change-Id: Ibdee5c2b400bb8fce76b0a4f781914748793db0e
Reviewed-on: https://review.monogon.dev/c/monogon/+/536
Reviewed-by: Leopold Schabel <leo@nexantic.com>
diff --git a/metropolis/pkg/supervisor/supervisor.go b/metropolis/pkg/supervisor/supervisor.go
index 77c2d02..ef7b909 100644
--- a/metropolis/pkg/supervisor/supervisor.go
+++ b/metropolis/pkg/supervisor/supervisor.go
@@ -23,6 +23,7 @@
import (
"context"
+ "fmt"
"io"
"sync"
@@ -160,3 +161,29 @@
defer unlock()
return node.sup.logtree.MustRawFor(logtree.DN(node.dn()))
}
+
+// SubLogger returns a LeveledLogger for a given name. The name is used to
+// placed that logger within the logtree hierarchy. For example, if the
+// runnable `root.foo` requests a SubLogger for name `bar`, the returned logger
+// will log to `root.foo.bar` in the logging tree.
+//
+// An error is returned if the given name is invalid or conflicts with a child
+// runnable of the current runnable. In addition, whenever a node uses a
+// sub-logger with a given name, that name also becomes unavailable for use as
+// a child runnable (no runnable and sub-logger may ever log into the same
+// logtree DN).
+func SubLogger(ctx context.Context, name string) (logtree.LeveledLogger, error) {
+ node, unlock := fromContext(ctx)
+ defer unlock()
+
+ if _, ok := node.children[name]; ok {
+ return nil, fmt.Errorf("name %q already in use by child runnable", name)
+ }
+ if !reNodeName.MatchString(name) {
+ return nil, fmt.Errorf("sub-logger name %q is invalid", name)
+ }
+ node.reserved[name] = true
+
+ dn := fmt.Sprintf("%s.%s", node.dn(), name)
+ return node.sup.logtree.LeveledFor(logtree.DN(dn))
+}