Getting TimeZone code from TZDATA in nodejs

538 views Asked by At

I am creating logger.js to make some clean logs. However I'm struggling to get the time zone in the expected format. I have it format Continent/Zone from process.env.TZ(Unix TZDATA) but would like it in format 000x

This is what I have so far:

/** 
 * Just. Clean. Logs.
 * Usage:
 * const logger = new Logger('mymodule');
 * logger.log('info', 'This is a log message');
 * @summary LOGS!
 * @param {string} stat - Application or module the log data is coming from
 */
class Logger {
    constructor(stat){
        this.stat = stat.toUpperCase();
    }
/** 
* @summary Log to console
* @param {string} level - Log level i.e WARN, INFO, DEBUG, ERROR etc.
* @param {string} message - Log message
*/
    log(level, message){
        const d = new Date(Date.now());
        const timestamp = `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}:${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}.${process.env.TZ}`;
        console.log(`${timestamp} ${level.toUpperCase()}:${this.stat}:${message}`);
    }
}

module.exports = Logger;

If the answer to create an array of sorts and assign the code manually, where could I find a comprehensive list of such data? I have managed to find some codes but not sure if they're what I'm looking for.

1

There are 1 answers

0
stderr On BEST ANSWER

Unfortunately, neither d.getTimezoneOffset() nor process.env.TZ knows anything about DST, so there's not an easy solution to your problem with off-the-shelf javascript.

There are some third-party libraries for dealing with timezones and DST in javascript that might help you. Shameless plug: My own tzdata-javascript.org is one of those libraries.

That being said, I would strongly encourage you to use UTC timestamps in your logs. It makes it a lot easier to compare logs from different systems that might not be in the same timezone and also eliminates the problem of DST.