node.jstimestampwinston

How to change timezone in Winston timestamp ? Node js


How can I change the timezone in this code? I tried some codes but it was not successful for me. I wrote some function for this. For example:

const timezoned = () => {
    return new Date().toLocaleString('en-US', {
      timeZone: 'Europe/Istanbul'
    });

This is my code:

const winston  = require('winston');
const { format, level, prettyPrint } = require('winston');
require('winston-daily-rotate-file');
 
  var transport = new (winston.transports.DailyRotateFile)({
    filename: 'application-%DATE%.log',
    datePattern: 'YYYY-MM-DD-HH',
    zippedArchive: true,
    maxSize: '1g',
    format:format.combine(format.timestamp(),format.prettyPrint()),
    level: 'info'
  });
 
  transport.on('rotate', function(oldFilename, newFilename) {
    // do something fun
  });
 
  var logger = winston.createLogger({
    transports: [
      transport
    ]
  });
 
  };
  module.exports.logger = logger;
 

Solution

  • You can pass a format value to the timestamp formatter, this can be a string or a function.

    The details are here: https://github.com/winstonjs/logform#timestamp

    So we can use your timezoned function and the times will be in Europe/Istanbul time, though formatted as US (because of the 'en-US' locale, you can obviously change this as you wish).

    const winston  = require('winston');
    const { format, level, prettyPrint } = require('winston');
    
    const timezoned = () => {
        return new Date().toLocaleString('en-US', {
            timeZone: 'Europe/Istanbul'
        });
    }
    
    require('winston-daily-rotate-file');
    
    var transport = new (winston.transports.DailyRotateFile)({
        filename: 'application-%DATE%.log',
        datePattern: 'YYYY-MM-DD-HH',
        zippedArchive: true,
        maxSize: '1g',
        format:format.combine(format.timestamp({ format: timezoned }),format.prettyPrint()),
        level: 'info'
    });
    
    transport.on('rotate', function(oldFilename, newFilename) {
        // do something fun
    });
    
    var logger = winston.createLogger({
        transports: [
        transport
        ]
    });
    
    module.exports.logger = logger;
    

    The output will look like this:

    {
        message: 'Log test',
        level: 'info',
        timestamp: '7/16/2020, 12:34:40 PM'
    }