Add optional timezoneOffset config for appenders

Example:
    log4js.configure({
        appenders: [{type: 'console', timezoneOffset: -540}],
        replaceConsole: true
    });

The expected value is the equivalent of (new Date).getTimezoneOffset()
In this example, -540 is the value for JST.
This allows machines members of world-wide-spread cluster to all report
log time-stamps using the same timezone (or adapt the timezone to a
local different from the system)
This commit is contained in:
Quentin Brandon
2015-03-20 11:51:23 +09:00
parent 4a217afc37
commit af69eddd1c
7 changed files with 44 additions and 33 deletions

View File

@@ -21,9 +21,9 @@ function addZero(vNumber) {
* Thanks to http://www.svendtofte.com/code/date_format/
* @private
*/
function offset(date) {
function offset(timezoneOffset) {
// Difference to Greenwich time (GMT) in hours
var os = Math.abs(date.getTimezoneOffset());
var os = Math.abs(timezoneOffset);
var h = String(Math.floor(os/60));
var m = String(os%60);
if (h.length == 1) {
@@ -32,26 +32,31 @@ function offset(date) {
if (m.length == 1) {
m = "0" + m;
}
return date.getTimezoneOffset() < 0 ? "+"+h+m : "-"+h+m;
return timezoneOffset < 0 ? "+"+h+m : "-"+h+m;
}
exports.asString = function(/*format,*/ date) {
exports.asString = function(/*format,*/ date, timezoneOffset) {
var format = exports.ISO8601_FORMAT;
if (typeof(date) === "string") {
format = arguments[0];
date = arguments[1];
timezoneOffset = arguments[2];
}
var vDay = addZero(date.getDate());
var vMonth = addZero(date.getMonth()+1);
var vYearLong = addZero(date.getFullYear());
var vYearShort = addZero(date.getFullYear().toString().substring(2,4));
// make the date independent of the system timezone by working with UTC
if (timezoneOffset === undefined) {
timezoneOffset = date.getTimezoneOffset();
}
date.setUTCMinutes(date.getUTCMinutes() - timezoneOffset);
var vDay = addZero(date.getUTCDate());
var vMonth = addZero(date.getUTCMonth()+1);
var vYearLong = addZero(date.getUTCFullYear());
var vYearShort = addZero(date.getUTCFullYear().toString().substring(2,4));
var vYear = (format.indexOf("yyyy") > -1 ? vYearLong : vYearShort);
var vHour = addZero(date.getHours());
var vMinute = addZero(date.getMinutes());
var vSecond = addZero(date.getSeconds());
var vMillisecond = padWithZeros(date.getMilliseconds(), 3);
var vTimeZone = offset(date);
var vHour = addZero(date.getUTCHours());
var vMinute = addZero(date.getUTCMinutes());
var vSecond = addZero(date.getUTCSeconds());
var vMillisecond = padWithZeros(date.getUTCMilliseconds(), 3);
var vTimeZone = offset(timezoneOffset);
var formatted = format
.replace(/dd/g, vDay)
.replace(/MM/g, vMonth)