console-slog icon indicating copy to clipboard operation
console-slog copied to clipboard

Bunch of enhancements...

Open ansel1 opened this issue 11 months ago • 0 comments

I kept going in circles with the figuring out the optimal combination of headers, fixed size headers, and how to handle the source field.

So I decided to instead implement an alternative option which lets the developer design their own header format using a format syntax.

This merge request is the tip of a fork I'm using, which either includes or supercedes some of the other pull requests I've opened. Here's a summary of what this fork does, relative to the base main branch of this project:

  • Uses fmt package for error values, like #11
  • Sorts multi-line values to the end of the attributes, like #13
  • Adds an option for how to trim source paths, superceding #17
  • Slightly tweaks the default theme to make the message field pop a little more. Does add the "dim" theme, obviating #10
  • Adds ReplaceAttr support
  • Introduces the new HeaderFormat option, which allows for configuration the layout of the entire header section of the log line (everything before the attrs are printed). Also supports fixed width and right-aligned headers. The syntax of the format is similar to fmt.Printf()

By default, the HeaderFormat is configured to exactly mimic the standard layout of this project. The default format is expressed like this:

%t %l %{%[source]h >%} %m

That reads like:

(timestamp) (level) (open group) (source header) > (close group) (msg)

The "group" stuff allows strings (like >) to be omitted if all the headers in that group are also omitted.

The new HeaderFormat allows for many customizations:

  • The "source" attr can be presented as a header (as in the standard layout), or as an attribute

  • Other attrs can be pulled out of the attrs list and injected into the headers, just like the source, e.g.

      %t %l %[logger]h > %m
    
  • The order of the headers (including the timestamp, level, and message) can be completely reconfigured by the user, e.g.

      %t %[source]h %l > %m
    
  • The > separator can be swapped for other characters, or moved, headers can be enclosed in brackets, etc., e.g.

      %t %[source]h %[logger]12h %l | %m
    

For details, see the docs for HandlerOptions.HeaderFormat.

All this flexibility does come at a cost:

  • It's slightly slower than this project, but still faster than the slog.TextHandler. On my machine, this project benchmarks around 750ns, while my fork comes in around 920ns. Still no memory allocation though.
  • I made one breaking change, renaming Theme.Source() to Theme.Header(), since that style is used for all header values.

ansel1 avatar Feb 17 '25 21:02 ansel1