Skip to content

[Feature Request]: Interpolate log message with variable names #231

@a98c14

Description

@a98c14

The vision

Hi,

I would like to be able to log messages with named parameters like we can do with string interpolation.

// Idea
logger.info("here is a sample log. {logid}", { logid: 12 });

// String Interpolation example
const sample = `test message  ${my_variable}`

Use case

Here is how I am currently doing it with a custom formatter.

const templater = format((info) => {
  info.original_format = info.message;
  let message = info.message as string;
  for (const k in info) {
    message = message.replace(`{${k}}`, JSON.stringify(info[k]));
  }
  info.message = message;
  return info;
});

const logger = winston.createLogger({
  level: "info",
  format: winston.format.combine(templater(), winston.format.json(), winston.format.splat()),
  transports: [new winston.transports.Console()],
});

logger.info("here is a sample log. {logid}", { logid: 12 });

Which produces

{"level":"info","message":"here is a sample log. 12","original_format":"here is a sample log. {logid}","logid":"12"}

Additional information

Custom formatter version works okay (at least gives the desired result) but I am not sure about its performance. Maybe it could be implemented in the library in a better way

🔎 Search Terms

interpolation, format, variable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions