How to properly add logging to a module?

I’d like to add logging capability to my plugin, so users can see what’s going on in the background and if an issue arises, they could notify me with the relevant logs. One option is “normal” printing with fmt.Println(), but that’s not that pretty. I could add something like this:

logger := caddy.Log().Named("my_module")
logger.Debug("hello from my module")

This can work, but it feels wrong to add caddy dependency for a libdns implementation (that should be in my opinion independent from caddy). So what is the correct way?

If it’s a Caddy plugin, use the Logger() from the caddy.Context. You get that object in the Provision call of your module. If it’s not a Caddy plugin, which seems to be the case since you mentioned libdns, you can use Zap or slog, the latter is a package in Go standard library.

If you want to use slog, then you’d call caddy.Slogger() instead of caddy.Logger(), but yeah.

It’s a Caddy DNS module which uses implementation of libdns interface as another library (https://github.com/libdns/wedos) and I’d like to log this implementation if that makes sense. I can use the Logger() and pass it down, but that would force me to also put caddy as a dependency if that makes sense

It already is a dependency

1 Like

Actually it does not, if you use slog then you add no additional dependency, because it’s from stdlib.

2 Likes

Caddy is already a dependency in the caddy-dns repo. (In the libdns repo, it is not, for which you can use zap or slog directly.)

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.