Conditional logging encoder

Hello everybody again! :wave:

I’ve built another Caddy log encoder that lets you log depending on conditions.

In fact, I called it if. :smiley:

You can find its implementation at leodido/caddy-conditional-logging.

You can combine it with other Caddy logging encoders (for example the console or the json one, or even another custom one I’ve built jsonselect).

You can define the conditions with Go-like expressions.

The parsing and the compilation of the expressions happen at unmarshalling and provisioning time. The matching, clearly, happens at encoding time.

But, let’s take a look at examples to better get a sense of it…

Log only the GETs:

log {
  format if "request>method == `GET`" console

Log only requests coming from Gecko browsers:

log {
  format if "request>headers>User-Agent>[0] ~~ `Gecko`" json

Log only 4** and 5** (eg., 404, 409, 500…):

log {
  format if "status ~~ `^4` || status ~~ `^5`" json

I think these are self-explanatory, isn’t it? :slight_smile:

There’s a lot you can do!

The expression language is documented here. It also supports grouping - ie., (...) - and operators precedence.

Lemme know what y’all think of it! :slightly_smiling_face:




You may want to consider using CEL for your condition expressions, since Caddy already uses it for the expression matcher:

1 Like

Wow that’s cool. Thanks for sharing this!

1 Like

Great suggestion!

I’ll look into CEL :slight_smile:


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