How to get an instance of named/module logger during provision phase of module lifecycle

Here is a snippet of module initialization.

type AuthProvider struct {
    Name string `json:"-"`
    CommonParameters
    Azure  *AzureIdp   `json:"azure,omitempty"`
    logger *zap.Logger `json:"-"`
}

// CaddyModule returns the Caddy module information.
func (AuthProvider) CaddyModule() caddy.ModuleInfo {
    return caddy.ModuleInfo{
        ID:  "http.authentication.providers.saml",
        New: func() caddy.Module { return new(AuthProvider) },
    }
}

// Provision provisions SAML authentication provider
func (m *AuthProvider) Provision(ctx caddy.Context) error {
    m.logger = caddy.Log()
    m.logger.Debug("provisioning saml plugin")
    m.Name = "saml"
    return nil
}

After I call caddy.Log(), I get the default logger. The message I would get is:

{"level":"info","ts":1586945928.2531993,"msg":"provisioning saml plugin"}

As you can see the message does not have module name in it. What is the function to initialize a “named” (plugin) logger, such that it would yield the following?

{"level":"info","ts":1586945928.2531993,"logger":"auth.saml","msg":"provisioning saml plugin"}
1 Like

Great question!

caddy.Log() return the current default log: caddy package - github.com/caddyserver/caddy/v2 - pkg.go.dev - usually this should only be used outside of a module context.

ctx.Logger(m) (in your case) will return a logger named after your module: caddy package - github.com/caddyserver/caddy/v2 - pkg.go.dev - that’s probably what you want.

2 Likes

@matt, thank you!

Changed the code to:

// Provision provisions SAML authentication provider
func (m *AuthProvider) Provision(ctx caddy.Context) error {
    m.logger = ctx.Logger(m)
    m.logger.Info("provisioning plugin")
    m.Name = "saml"
    return nil
}

and got the expected output:

{"level":"info","ts":1586946996.3336048,"logger":"http.authentication.providers.saml","msg":"provisioning plugin"}

The http.authentication.providers.saml appears to be long, but that’s ok for now.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.