import {MessageContext} from './message';
/**
* Allows additional context to be added to the message string.
*/
export interface MessageTemplate {
/**
* Make a string given the `context`.
* @param context
*
*/
format(context: MessageContext): string;
}
/**
* Adds no additonal context to the message string.
*/
export const rawMessageTemplate: MessageTemplate = {
/**
*
* @param context
* @returns context.message
*/
format(context: MessageContext): string {
return context.message;
}
};
/**
* Format a message using a lazily evaluated template string.
*/
export class TemplateStringMessageTemplate implements MessageTemplate {
/**
* Will render logger's fqn and the message.
*/
static readonly DEFAULT_TEMPLATE = '${ctx.data.fqn || ""}: ${ctx.message || ""}';
private readonly fmt: Function;
/**
*
* @param template a template string. **Backticks are not necessary.**
*/
constructor(readonly template = TemplateStringMessageTemplate.DEFAULT_TEMPLATE) {
try {
this.fmt = new Function('ctx', `return \`${this.template}\`;`);
} catch (error) {
console.error('TemplateStringMessageTemplate: Error creating template from `%s`!', this.template, error);
throw error;
}
}
format(context: MessageContext): string {
let result: string;
try {
result = this.fmt(context);
} catch (error) {
console.error('TemplateStringMessageTemplate: Error formatting %o with template %s', context, this.template, error);
result = context.message;
}
return result;
}
}
export function templateString(template?: string): MessageTemplate {
return new TemplateStringMessageTemplate(template);
}
|