log4r icon indicating copy to clipboard operation
log4r copied to clipboard

Add the concept of subloggers or a `with(...)` syntax

Open atheriel opened this issue 1 year ago • 0 comments

Other structured logging libraries that pass around loggers as values (e.g. most Go libraries) often have syntax for creating a new logger that inherits the configuration of the parent but includes some fields in all messages.

For example, with slog:

logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
logger.Info("hello", "count", 3)
// time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3

logger2 := logger.With("username", "user1")
logger2.Info("hello", "count", 3)
// time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3 username=user1

It shouldn't be too difficult to do this internally (we can store some fields on the logger object and pass it to appenders). The real question is what the end-user interface should look like. Maybe a new from_logger()?

lgr <- logger()
log_info(lgr, "hello", count = 3)
# INFO  [2024-10-18 14:10:44] hello count=3

slgr <- from_logger(lgr, username = "user1")
log_info(slgr, "Started session.")
# INFO  [2024-10-18 14:10:44] hello count=3 username=user1

Other options:

  • slgr <- sublogger(parent = lgr, , username = "user1")
  • slgr <- logger(parent = lgr, , username = "user1")
  • slgr <- with_log_attributes(lgr, username = "user1")

(None of which I like very much.)

atheriel avatar Oct 18 '24 18:10 atheriel