[Feature Request]: Interpolate log message with variable names
a98c14 opened this issue · 3 comments
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
Why not just use string interpolation directly, if that does what you're looking for?
logger.info(`test message with my_variable: ${my_variable}`);
Correct me if I am wrong but then I would miss the original format part wouldn't I? It makes searching by format and grouping much easier if I can access that.
You could do something like this:
logger.info({message: `here is a sample log. ${logid}`, logid: 12, original_format:"here is a sample log. {logid}"});
depending on your desire to analyze logid programmatically without parsing it from the string. However, if this is happening at volume, you might want to replace original_format with a numeric code and have some separate lookup table for details on that error. The human-readable format of the message might even then become optional depending on how you plan to use/consume the logs.
logger.info({message: `Sample log ${logid}`, logid: 12, code: 3456});