-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logging.js
406 lines (347 loc) · 11.4 KB
/
Logging.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*!
* Copyright (c) 2015 Extesla, LLC.
*
* Licensed under the MIT License (http://opensource.org/licenses/MIT)
*
* Permission is hereby granted, free of charge, to any
* person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//=============================================================================
// Logging.js
//=============================================================================
var Logging = Logging || {};
var LogLevel = LogLevel || {};
/*:
* @plugindesc Adds logging functionality to the game.
* @author Sean Quinn
*
* @param Log Level
* @desc The logging level, e.g. DEBUG, INFO, WARN, ERROR
* @default INFO
*
* @param Enable Console Logger
* @desc Enable/disable console logging
* @default True
*
* @param Enable File Logger
* @desc Enable/disable file logging
* @default True
*
* @param Log Filename
* @desc The name of the log file.
* @default game.log
*
* @param Log Directory
* @desc The relative path for your logs
* @default logs
*
* @help
*
*/
(function() {
"use strict"; // ;_;
var fs = require("fs");
var path = require("path");
var util = require("util");
// ===========================================================================
// LogLevel
// ===========================================================================
LogLevel.DEBUG = 10;
LogLevel.INFO = 20;
LogLevel.WARN = 30;
LogLevel.WARNING = LogLevel.WARN;
LogLevel.ERROR = 40;
LogLevel.ALL = 0;
function _levelToName(level) {
if (level === LogLevel.ALL) {
return "ALL";
}
else if (level === LogLevel.DEBUG) {
return "DEBUG";
}
else if (level === LogLevel.ERROR) {
return "ERROR";
}
else if (level === LogLevel.INFO) {
return "INFO";
}
else if (level === LogLevel.WARN) {
return "WARN";
}
throw Error("Unknown level: " + level);
}
function _nameToLevel(level) {
var map = {
"ALL": LogLevel.ALL,
"DEBUG": LogLevel.DEBUG,
"ERROR": LogLevel.ERROR,
"INFO": LogLevel.INFO,
"WARN": LogLevel.WARN,
"WARNING": LogLevel.WARNING
};
return map[level];
}
function _checkLevel(level) {
var rv = null;
if (typeof level === "number") {
rv = level;
}
else if (typeof level === "string") {
rv = _nameToLevel(level);
}
else {
throw Error("Level " + level + " unrecognized.");
}
return rv;
}
/**
* Return the textual representation of logging level "level".
*
* If the level is one of the predefined levels (ERROR, WARNING, INFO, DEBUG)
* then you get the corresponding string.
*
* If a numeric value corresponding to one of the defined levels is passed
* in, the corresponding string representation is returned.
*/
function _getLevelName(level) {
var lvl = null;
lvl = _levelToName(level);
if (!lvl) {
lvl = _nameToLevel(level);
}
return lvl;
}
// ===========================================================================
// Logging
// ===========================================================================
// ** Plugin state constants.
Logging.STATE_DONE = "done";
Logging.STATE_ERR = "err";
Logging.STATE_INITIALIZING = "initializing";
Logging.STATE_RESOLVING_LOGS_PATH = "resolving_logs_path";
// ** The plugin internal state/variables.
Logging.PluginState = null;
Logging.Paths = {};
// ** Plugin variables/parameters.
var parameters = PluginManager.parameters("Logging");
var logging_enable_console_logger = Boolean(parameters["Enable Console Logger"] || "true");
var logging_enable_file_logger = Boolean(parameters["Enable File Logger"] || "true");
var logging_directory = String(parameters["Log Directory"] || "");
var logging_filename = String(parameters["Log Filename"] || "game.log");
var logging_log_level = String(parameters["Log Level"] || "INFO");
var logging_log_format = "%s [%s] - %s";
//============================================================================
// Logger
//============================================================================
/**
*
*/
function Logger() {
this.initialize.apply(this, arguments);
}
Logger.prototype.initialize = function() {
this._handlers = [];
this.format = "";
this.level = LogLevel.INFO;
};
Logger.prototype.addHandler = function(handler) {
this._handlers.push(handler);
};
Logger.prototype.setLevel = function(level) {
this.level = _checkLevel(level);
};
Logger.prototype.log = function(level, message) {
var date = new Date(),
formatted = "";
if (this.level <= level) {
formatted = util.format(Logging.Format, date.toISOString(), _levelToName(level), message);
this._handlers.forEach(function (handler) {
handler.write(formatted);
});
}
};
Logger.prototype.error = function(message) {
this.log(LogLevel.ERROR, message);
};
Logger.prototype.debug = function(message) {
this.log(LogLevel.DEBUG, message);
};
Logger.prototype.info = function(message) {
this.log(LogLevel.INFO, message);
};
Logger.prototype.warn = function(message) {
this.log(LogLevel.WARN, message);
};
//============================================================================
// LogHandler
//============================================================================
function LogHandler() {
this.initialize.apply(this, arguments);
}
LogHandler.prototype.__name__ = "LogHandler";
LogHandler.prototype.initialize = function() {
};
LogHandler.prototype.write = function(message) {
/* no-op */
};
//============================================================================
// ConsoleHandler
//============================================================================
function ConsoleHandler() {
this.initialize.apply(this, arguments);
}
ConsoleHandler.prototype = Object.create(LogHandler.prototype);
ConsoleHandler.prototype.constructor = ConsoleHandler;
ConsoleHandler.prototype.__name__ = "ConsoleHandler";
ConsoleHandler.prototype.initialize = function() {
this._ready = false;
if (console) {
this._ready = true;
}
};
ConsoleHandler.prototype.write = function(message, level) {
if (this._ready) {
if (level === LogLevel.DEBUG) { console.debug(message); }
else if (level === LogLevel.INFO) { console.info(message); }
else if (level === LogLevel.WARN) { console.warn(message); }
else if (level === LogLevel.ERROR) { console.error(message); }
console.log(message);
}
};
//============================================================================
// FileStreamHandler
//============================================================================
/**
*
*/
function FileStreamHandler() {
this.initialize.apply(this, arguments);
}
FileStreamHandler.prototype = Object.create(LogHandler.prototype);
FileStreamHandler.prototype.constructor = FileStreamHandler;
ConsoleHandler.prototype.__name__ = "FileStreamHandler";
FileStreamHandler.prototype.initialize = function(fileName) {
this._ready = false;
this._logfile = path.resolve(Logging.Paths.logs_path, "./", fileName);
// try {
// fs.openSync(this._logfile, "a+");
// }
// finally {
// fs.closeSync(this._logfile);
// }
var self = this;
fs.open(this._logfile, "a+", function(err, fd) {
if (err) {
throw err;
}
self._ready = true;
fs.closeSync(fd);
});
};
FileStreamHandler.prototype.write = function(message, level) {
var buffer;
if (this._ready) {
buffer = new Buffer(message + "\n");
fs.open(this._logfile, "a+", function(err, fd) {
if (err) {
throw "An error was encountered when attemping to open the log file: " + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) {
throw "Error writing file: " + err;
}
fs.closeSync(fd);
});
});
}
};
// **
// If the logging subsystem hasn't initialized in 5 seconds, something has
// gone horribly wrong and we want to abort all further setup operations.
// This should prevent the logging plugin from blocking the normal game
// behavior.
// TODO: Create failsafe...
function initialize() {
// ** Begin initialization.
Logging.PluginState = Logging.STATE_INITIALIZING;
// **
// Assign the log level to the Logging system.
Logging.Level = _nameToLevel(logging_log_level);
Logging.Format = logging_log_format;
// **
// The format of the file directory may be something like: /C:/Path/To/Project
// if it is, the file system module will not be able to resolve the realpath,
// so we need to slice the first character off.
var pathname = fs.realpathSync(getGameDirectory());
Logging.Paths.root_path = pathname;
Logging.Paths.logs_path = pathname;
//
Logging.PluginState = Logging.STATE_RESOLVING_LOGS_PATH;
if (logging_directory) {
logging_directory = resolveToLocalPath(logging_directory);
logging_directory = path.resolve(Logging.Paths.root_path, "./", logging_directory);
Logging.Paths.logs_path = logging_directory;
}
fs.access(Logging.Paths.logs_path, fs.F_OK | fs.R_OK, function(err) {
if (err) {
fs.mkdir(Logging.Paths.logs_path);
}
Logging.logger = createLogger("Game", Logging.Level);
Logging.PluginState = Logging.STATE_DONE;
});
}
/**
*
*/
function createLogger(name, level) {
var logger = new Logger();
logger.setLevel(level);
if (logging_enable_console_logger) {
var consoleHandler = new ConsoleHandler();
logger.addHandler(consoleHandler);
}
if (logging_enable_file_logger) {
var fileStreamHandler = new FileStreamHandler(path.basename(logging_filename));
logger.addHandler(fileStreamHandler);
}
return logger;
}
/**
*
*/
function getGameDirectory() {
var dir = path.dirname(window.location.pathname);
if (dir.match(/^\/([A-Z]\:)/)) {
dir = dir.slice(1);
}
return dir;
}
/**
* Resolve a file path to a local-only file path. This should prevent
* specifying a path outside of the project directory.
*/
function resolveToLocalPath(filePath) {
var pattern = /[\/\\]?(?:.+[\/\\]+?)?(.+?)[\/\\]?/g;
return filePath.replace(pattern, "$1");
}
initialize();
})();