RegisterContextTag registers a contextual tag that can be used by SetContextTemplate. Re-registering a tag replaces the existing tag function. Registration is package-global; prefer ContextConfig.CustomTags for per-application overrides. The reserved TagContextValue tag cannot be registered.
(tag string, fn ContextTagFunc)
| 135 | // prefer ContextConfig.CustomTags for per-application overrides. The reserved TagContextValue |
| 136 | // tag cannot be registered. |
| 137 | func RegisterContextTag(tag string, fn ContextTagFunc) error { |
| 138 | if tag == "" || fn == nil { |
| 139 | return ErrContextTagInvalid |
| 140 | } |
| 141 | if tag == TagContextValue { |
| 142 | return ErrContextTagReserved |
| 143 | } |
| 144 | |
| 145 | contextMu.Lock() |
| 146 | defer contextMu.Unlock() |
| 147 | |
| 148 | tags := maps.Clone(contextTags) |
| 149 | tags[tag] = fn |
| 150 | |
| 151 | var tmpl *logtemplate.Template[any, ContextData] |
| 152 | if contextFormat != "" { |
| 153 | var err error |
| 154 | tmpl, err = logtemplate.Build[any, ContextData](contextFormat, tags) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | contextTags = tags |
| 161 | contextTemplate.Store(tmpl) |
| 162 | return nil |
| 163 | } |
| 164 | |
| 165 | // MustRegisterContextTag registers a contextual tag and panics if registration fails. |
| 166 | func MustRegisterContextTag(tag string, fn ContextTagFunc) { |