tslog icon indicating copy to clipboard operation
tslog copied to clipboard

Feature Request: Tagged Template Strings

Open WorldMaker opened this issue 3 years ago • 1 comments

Description / Use Case for a Feature

It would be cool to have log functions that can be used as Tagged Template Strings.

Template strings are a very useful way to format strings in modern JS with all sorts of nice type information and autocomplete in TS:

const aThing = 45
const bThing = true

const logMessage = `this is a log message for aThing at ${aThing} and bThing is ${bThing}`

Template strings are also more powerful than just string formatting, they can be tagged with a tag function. That tag function is given the strings around the "holes" as well as the values to fill the holes with (before they've been stringified).

Tag functions can be handy for structured logging. A hypothetical TemplateLogger could be written that takes a template literal directly and logs it as a structured object.

const coolLogger = new TemplateLogger()

coolLogger.info`this is a log message for aThing at ${aThing} and bThing is ${bThing}`

This would be roughly equivalent to:

logger.info('this is a log message for aThing at ', 45, ' and bThing is ', true)

It's an improvement on "splat-style" logging with better TS language service syntax support.

I may PR an attempt at this if there is interest because that "roughly equivalent to" should be an easy enough transform.

WorldMaker avatar Dec 14 '22 08:12 WorldMaker

I briefly looked into building a PR but your project does not currently build on Windows and so I instead tested the concept in a different repository.

Here's a gist of a simple wrapper class that works/tests (in Mocha):

https://gist.github.com/WorldMaker/25c4cbef665232e93b503e9db0ed33b8

WorldMaker avatar Dec 15 '22 03:12 WorldMaker