I have a method in one of the shared utility class. It just logs an event when called:
public static newEvent(message: string): void {
const t_option = {
hour: '2-digit',
minute: '2-digit',
fractionalSecondDigits: '3',
hour12: false,
} as Intl.DateTimeFormatOptions;
const now = new Date().toLocaleTimeString([], t_option);
const formattedMessage = `[${now}] ${message}`;
this.eventService.publish(formattedMessage);
console.log(formattedMessage);
}
This sort of logs something like this to console (and saves in a file log somewhere else):
[15:01:13.929] initialising...
[15:01:50.588] connecting to websockets...
[15:02:06.384] websockets connected (3)
[15:04:02.992] fetching weather data...
This log method is being called from pretty much all the services and components in the angular application. There are a LOT of calls. Maybe around 10-12 a second on a busy day.
My issue here is that I’m creating a new Date()
for each message logged. I want the timestamp to be in a human readable format, but I am wondering if creating a new date object is the best way to do it?
If I create one static date outsuide the method then the timestamp is not live, as in, every time the date/time will be the same as when it was created. If use Date.now()
instead, I get unix timestamp, but, it’s not human readable.
So my question I guess is, is there a better way to do what I want without creating a ton of new object? Or is this trivial enough that I don’t have to worry about it?