Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //=======================================================================================
- // Liquid Plugins - Liquid Logging
- // Liquid_Logging.js
- //=======================================================================================
- var Imported = Imported || {};
- Imported.Liquid_Logging = true;
- var Liquid = Liquid || {};
- Liquid.Logging = Liquid.Logging || {};
- //=======================================================================================
- /*:
- * @plugindesc v1.0 Gives you the ability to log formatted information in various different
- * ways this is useful when you want to have more formatted information when debugging or
- * what have you.
- * @author Liquidize
- *
- * @param Allow Logging
- * @desc Is logging enabled?
- * @default true
- *
- * @param Logging Pattern
- * @desc The pattern used for logging, see the help for more details.
- * for more information.
- * @default [%c] [%-5l]: %m
- *
- *
- * @param Show Stack Trace
- * @desc Show stack trace when given an exception?
- * @default true
- *
- * @param Timestamps in milliseconds
- * @desc Show timestamps (when applicable) in milliseconds?
- * @default false
- *
- * @param Default Log Name
- * @desc Name of the default logger.
- * @default Game
- *
- * @help
- * =======================================================================================
- * Introduction
- * =======================================================================================
- * This plugin adds the ability to log information to a logging system, and then display
- * it in a formatted string through the means of the Browsers Console.
- * Useful for debugging events, as well as debugging your code.
- *
- * =======================================================================================
- * Pattern Formatting
- * =======================================================================================
- * By default the logging system logs information using the Liquid_ConsoleAppender with,
- * the format of the appender being supplied by Liquid_PatternFormat.
- * A pattern format is format given as a pattern, and is then filled with the proper
- * variables associated with the values in the pattern.
- *
- * The Liquid_PatternFormat formatter supports the following pattern variables.
- *
- * VARIABLE : USE
- * %c : substitutes the name of the logger in.
- * %a : supplies the logged message as an array.
- * %m : supplies the logged message as a string.
- * %l : substitutes the logging level in.
- * %d : substitutes the date in, given a format (or default). EXAMPLE: %d{HH:mm:ss} or %d{dd MMM yyyy HH:mm:ss}
- * %n : creates a new line.
- * %t : outputs the time since the logging system/the game started.
- * %% : outputs a single %.
- *----------------------------------------------------------------------------------------
- * EXAMPLES
- *
- * FORMAT : OUTPUT
- *----------------------------------------------------------------------------------------
- * [%c] [%l] %m : [My Log Name] [The Logging Level] The Message given to the logger.
- * [%d] [%l] %m : [The Date (Using the default format)] [The Logging Level] The message.
- * [%d{HH:mm:ss}] [%c - %t] - %m : [The Date as Hours:Minutes:Seconds] [Name of Logger - Time Since Game Start] - The Message.
- *========================================================================================
- * Calling the Logging system from Events
- *========================================================================================
- * You are able to call the logging system from events using the plugin command event.
- *
- * The plugin command(s) are as follows:
- *----------------------------------------------------------------------------------------
- * LiquidLog LogLevel Message
- *
- * Purpose:
- * The purpose of this command is to log a message to the logger.
- *
- * Examples:
- * LiquidLog info This is an info message.
- * LiquidLog error This is an error message.
- * LiquidLog debug this is a debug message.
- * LiquidLog warn This is a warning message.
- * LiquidLog fatal this is another way to call an error message.
- *
- *========================================================================================
- * Calling the logging system from scripts/plugins.
- *========================================================================================
- * Another nice thing about Liquid_Logging is the ability to create your own loggers in
- * your own scripts. Then by doing so have debug messages for private use, or allow your
- * script users to see them by having a parameter to set your personal logger to be enabled.
- * Doing so would require them to have this plugin as well though.
- *
- * To call the logging system from your own script, you must first have this plugin installed
- * above your script in the list.
- *
- * After that you need to create a Liquid_Log object such as so:
- *
- * var mySuperDuperLog = Liquid.Logging.getLogger("My Log Name Here");
- *
- * After the logger is created you need to set some properties though.
- *
- * mySuperDuperLog.setLevel(Liquid_LogLevel.Level);
- *
- * change the "Liquid_LogLevel.Level" to an appropriate level. See further down for more info.
- *
- * var mySuperDuperAppender = new Liquid_ConsoleAppender();
- * var mySuperDuperFormat = new Liquid_PatternFormat("My Logging Pattern Here");
- * mySuperDuperAppender.setFormat(mySuperDuperFormat);
- * mySuperDuperLog.addApender(mySuperDuperAppender);
- *
- * Your "mySuperDuperLog" object is then usable by calling the logging methods.
- * What all of this code does, is create a new Liquid_Log object using the getLogger() method.
- * This method will check to see if a logger by the given name exists, if so it returns it instead.
- * If not however, it will then create a bare-bones logger, that isn't useable until you
- * Setup some of the properties. Such as the logging level threshold, and an appender.
- * An appender is the object that caries out the actual logging of the messages, given the
- * specified format, which is set by the "setFormat(YourFormatObjectHere)" method. A logger
- * may have multiple appenders. This is useful for custom appenders that users can create,
- * such as ones that may send a message to a server, or write to a file, or email a user.
- *
- * After all of this is setup, you can call your lovely logger using the methods below,
- * each of the methods have an option second argument for an exception if one exists.
- *
- * Info:
- * mySuperDuperLog.info("message");
- * Debug:
- * mySuperDuperLog.debug("message");
- * Warn:
- * mySuperDuperLog.warn("message");
- * Error/Fatal:
- * mySuperDuperLog.error("error message");
- *---------------------------------------------------------------------------------------
- * Logging Level
- *---------------------------------------------------------------------------------------
- * When creating a logger, it needs to have a logging level threshold set. This is what
- * determines what type of messages the logger will actually log. Ignoring ones outside of
- * the threshold.
- *
- * Liquid_LogLevel.All : Logs every type.
- * Liquid_LogLevel.Trace : Logs trace.
- * Liquid_LogLevel.Debug : Logs debug and up.
- * Liquid_LogLevel.Info : Logs info and up.
- * Liquid_LogLevel.Warn : Logs warn and up.
- * Liquid_LogLevel.Error : Logs error and up.
- * Liquid_LogLevel.Fatal : Logs fatal only.
- * Liquid_LogLevel.Off : Logs nothing.
- *========================================================================================
- * Custom Appenders and Formatters
- *========================================================================================
- * It is possible to create custom Appenders and Formatters for the logging system, by
- * creating new objects based off Liquid_LogAppender (for custom appenders) or
- * Liquid_LogFormat (for custom formatters).
- *
- * Once your new Appender or Formatter object is created, you need simply to implement your
- * own versions of the required functions. Then simply create a new instance of this object
- * and either do "yourAppenderVar.setFormat(YourInstanceOfNewFormatTypeHere)" or
- * "yourLogVar.addApender(YourInstanceOfNewAppenderTypeHere)" as shown above in using this
- * in custom scripts.
- *
- * More built in appenders and formatters are planned, but I am busy refactoring,optimizing,
- * and cleaning the code up for now.
- *========================================================================================
- * Change Log
- *========================================================================================
- * 1.0: Finished Script!
- *========================================================================================
- */
- //=======================================================================================
- // Parameters
- //=======================================================================================
- Liquid.Parameters = PluginManager.parameters("Liquid_Logging");
- Liquid.Param = Liquid.Param || {};
- Liquid.Param.LoggingEnabled = String(Liquid.Parameters['Allow Logging']);
- Liquid.Param.LogPattern = String(Liquid.Parameters['Logging Pattern']);
- Liquid.Param.LogShowStack = String(Liquid.Parameters['Show Stack Trace']);
- Liquid.Param.LogUseTimeStampsInMillisecs = String(Liquid.Parameters['Timestamps in milliseconds']);
- Liquid.Param.DefaultLogName = String(Liquid.Parameters['Default Log Name']);
- //======================================================================================
- // Utilities
- //======================================================================================
- Liquid.Logging.gameStartDate = new Date();
- // Check if object is undefined.
- Liquid.Logging.isUndefined = function (obj) {
- return typeof obj == "undefined";
- };
- Liquid.Logging.arrayContains = function (arr, val) {
- for (var i = 0, len = arr.length; i < len; i++) {
- if (arr[i] == val) {
- return true;
- }
- }
- return false;
- };
- Liquid.Logging.arrayRemove = function (arr, val) {
- var index = -1;
- for (var i = 0, len = arr.length; i < len; i++) {
- if (arr[i] === val) {
- index = i;
- break;
- }
- }
- if (index >= 0) {
- arr.splice(index, 1);
- return true;
- } else {
- return false;
- }
- };
- Liquid.Logging.toStr = function (obj) {
- if (obj && obj.toString) {
- return obj.toString();
- } else {
- return String(obj);
- }
- };
- Liquid.Logging.getExceptionMessage = function (exception) {
- if (exception.message) {
- return exception.message;
- } else if (exception.description) {
- return exception.description;
- } else {
- return Liquid.Logging.toStr(exception);
- }
- };
- Liquid.Logging.getFileNameFromUrl = function (url) {
- var lastSlashIndex = Math.max(url.lastIndexOf("/"), url.lastIndexOf("\\"));
- return url.subst(lastSlashIndex + 1);
- };
- Liquid.Logging.getPrettyExceptionString = function (exception) {
- var newLine = "\r\n";
- if (exception) {
- var exStr = "Exception: " + Liquid.Logging.getExceptionMessage(exception);
- try {
- if (exception.lineNumber) {
- exStr += " on line number " + exception.lineNumber;
- }
- if (exception.fileName) {
- exStr += " in file " + Liquid.Logging.getUrlFileName(exception.fileName);
- }
- } catch (localEx) {
- LiquidLog.internalLog.warn("Unable to obtain file and line information for error");
- }
- if (eval(Liquid.Param.ShowStack) && exception.stack) {
- exStr += newLine + "Stack trace:" + newLine + exception.stack;
- }
- return exStr;
- }
- return null;
- };
- Liquid.Logging.extractBoolFromParam = function (param, defaultVal) {
- if (Liquid.Logging.isUndefined(param)) {
- return defaultVal;
- } else {
- return Boolean(param);
- }
- };
- Liquid.Logging.extractStringFromParam = function (param, defaultValue) {
- if (Liquid.Logging.isUndefined(param)) {
- return defaultValue;
- } else {
- return String(param);
- }
- };
- Liquid.Logging.extractIntFromParam = function (param, defaultValue) {
- if (Liquid.Logging.isUndefined(param)) {
- return defaultValue;
- } else {
- try {
- var value = parseInt(param, 10);
- return isNaN(value) ? defaultValue : value;
- } catch (ex) {
- LiquidLog.internalLog.warn("Invalid int param " + param, ex);
- return defaultValue;
- }
- }
- };
- Liquid.Logging.extractFunctionFromParam = function (param, defaultValue) {
- if (typeof param == "function") {
- return param;
- } else {
- return defaultValue;
- }
- };
- Liquid.Logging.handleError = function (message, exception) {
- LiquidLog.internalLog.error(message, exception);
- LiquidLog.dispatch("error", { "message": message, "exception": exception });
- };
- //======================================================================================
- // Liquid_InternalLog Object
- //======================================================================================
- function Liquid_InternalLog() {
- };
- Liquid_InternalLog.prototype.debug = function (message) {
- console.log(message);
- };
- Liquid_InternalLog.prototype.warn = function (message, exception) {
- console.warn(message);
- };
- Liquid_InternalLog.prototype.error = function (message, exception) {
- var errorMessage = "Liquid_Log error:" + message;
- if (exception) {
- errorMessage += "\r\n\r\n" + "Original message: " + Liquid.Logging.getPrettyExceptionString(exception);
- }
- console.error(errorMessage);
- };
- //======================================================================================
- // Liquid_EventSupport Object
- // NOTE: This is not for RPGMaker events, though that may come soon!
- //======================================================================================
- function Liquid_EventSupport() {
- this.eventTypes = [];
- this.eventListeners = {};
- };
- Liquid_EventSupport.prototype.setTypes = function (types) {
- if (types instanceof Array) {
- this.eventTypes = types;
- this.eventListeners = {};
- for (var i = 0, l = this.eventTypes.length; i < l; i++) {
- this.eventListeners[this.eventTypes[i]] = [];
- }
- } else {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: setTypes: types parameter must be an Array");
- }
- };
- Liquid_EventSupport.prototype.addListener = function (eventtype, listener) {
- if (typeof listener == "function") {
- if (!Liquid.Logging.arrayContains(this.eventTypes, eventtype)) {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: addEventListener: no event called '" + eventtype + "'");
- }
- this.eventListeners[eventtype].push(listener);
- } else {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: addListener: listener must be a function");
- }
- };
- Liquid_EventSupport.prototype.removeListener = function (eventtype, listener) {
- if (typeof listener == "function") {
- if (!Liquid.Logging.arrayContains(this.eventTypes, eventtype)) {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: removeListener: no event called '" + eventtype + "'");
- }
- Liquid.Logging.arrayRemove(this.eventListeners[eventtype], listener);
- } else {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: removeListener: listener must be a function");
- }
- };
- Liquid_EventSupport.prototype.dispatch = function (eventtype, eventargs) {
- if (Liquid.Logging.arrayContains(this.eventTypes, eventtype)) {
- var listeners = this.eventListeners[eventtype];
- for (var i = 0, l = listeners.length; i < l; i++) {
- listeners[i](this, eventtype, eventargs);
- }
- }
- else {
- Liquid.Logging.handleError("Liquid_Log.EventSupport [" + this + "]: dispatch: no event called '" + eventtype + "'");
- }
- };
- //======================================================================================
- // Liquid_LogLevel Object
- //======================================================================================
- function Liquid_LogLevel(level, name) {
- this.level = level;
- this.name = name;
- };
- Liquid_LogLevel.prototype.toString = function () {
- return this.name;
- };
- Liquid_LogLevel.prototype.equals = function (level) {
- return this.level == level.level;
- };
- Liquid_LogLevel.prototype.isGreaterThanOrEqual = function (level) {
- return this.level >= level.level;
- };
- Liquid_LogLevel.All = new Liquid_LogLevel(0, "All");
- Liquid_LogLevel.Trace = new Liquid_LogLevel(1, "Trace");
- Liquid_LogLevel.Debug = new Liquid_LogLevel(2, "Debug");
- Liquid_LogLevel.Info = new Liquid_LogLevel(3, "Info");
- Liquid_LogLevel.Warn = new Liquid_LogLevel(4, "Warn");
- Liquid_LogLevel.Error = new Liquid_LogLevel(5, "Error");
- Liquid_LogLevel.Fatal = new Liquid_LogLevel(6, "Fatal");
- Liquid_LogLevel.Off = new Liquid_LogLevel(7, "Off");
- //=======================================================================================
- // Liquid_LogTimer Object
- //=======================================================================================
- function Liquid_LogTimer(name, level) {
- this.name = name;
- this.level = Liquid.Logging.isUndefined(level) ? Liquid_LogLevel.Info : level;
- this.start = new Date();
- };
- Liquid_LogTimer.prototype.getElapsedTime = function () {
- return new Date().getTime() - this.start.getTime();
- };
- //=======================================================================================
- // Liquid_LogEvent Object
- //=======================================================================================
- function Liquid_LogEvent(logger, timeStamp, level, messages, exception) {
- this.logger = logger;
- this.level = level;
- this.timeStamp = timeStamp;
- this.timeStampInMilliseconds = timeStamp.getTime();
- this.timeStampInSeconds = Math.floor(this.timeStampInMilliseconds / 1000);
- this.milliseconds = this.timeStamp.getMilliseconds();
- this.messages = messages;
- this.exception = exception;
- };
- Liquid_LogEvent.prototype.getThrowableStr = function () {
- return this.exception ? Liquid.Logging.getExceptionString(this.exception) : "";
- };
- Liquid_LogEvent.prototype.getCombinedMessages = function () {
- return (this.messages.length == 1) ? this.messages[0] : this.messages.join("\r\n");
- };
- Liquid_LogLevel.prototype.toString = function () {
- return "Liquid_LogEvent [" + this.level + "]";
- };
- //=======================================================================================
- // Liquid_LogFormat Object
- //=======================================================================================
- function Liquid_LogFormat() {
- this.defaults = {};
- this.defaults.loggerKey = "logger";
- this.defaults.timeStampKey = "timestamp";
- this.defaults.millisecondsKey = "milliseconds";
- this.defaults.levelKey = "level";
- this.defaults.messageKey = "message";
- this.defaults.exceptionKey = "exception";
- this.defaults.urlKey = "url";
- this.loggerKey = "logger";
- this.timeStampKey = "timestamp";
- this.millisecondsKey = "milliseconds";
- this.levelKey = "level";
- this.messageKey = "message";
- this.exceptionKey = "exception";
- this.urlKey = "url";
- this.overrideTimeStampsSettings = false;
- this.useTimeStampsMilliseconds = null;
- };
- Liquid_LogFormat.prototype.format = function () {
- Liquid.Logging.handleError("Liquid_LogFormat: error Log Formatters must implement a format function.")
- };
- Liquid_LogFormat.prototype.getContentType = function () {
- return "text/plain";
- };
- Liquid_LogFormat.prototype.isTimeStampsInMilliseconds = function () {
- return this.overrideTimeStampsSetting ?
- this.useTimeStampsMilliseconds : eval(Liquid.Param.LogUseTimeStampsInMillisecs);
- };
- Liquid_LogFormat.prototype.setTimeStampsToUseMilliseconds = function (timestampsInMillisecs) {
- this.overrideTimeStampsSettings = true;
- this.useTimeStampsMilliseconds = Boolean(timestampsInMillisecs);
- };
- Liquid_LogFormat.prototype.getTimeStampValue = function (logevent) {
- return this.isTimeStampsInMilliseconds() ? logevent.timeStampInMilliseconds : logevent.timeStampInSeconds;
- };
- Liquid_LogFormat.prototype.getDataValues = function (logevent, combineMessages) {
- var datValues = [
- [this.loggerKey, logevent.logger.name],
- [this.timeStampKey, this.getTimeStampValue(logevent)],
- [this.levelKey, logevent.level.name],
- [this.urlKey, window.location.href],
- [this.messageKey, combineMessages ? logevent.getCombinedMessages() : logevent.messages]
- ];
- if (this.isTimeStampsInMilliseconds() !== true) {
- datValues.push([this.millisecondsKey, logevent.milliseconds]);
- }
- if (logevent.exception) {
- datValues.push([this.exceptionKey, Liquid.Logging.getPrettyExceptionString(logevent.exception)]);
- }
- if (this.hasCustomFields()) {
- for (var i = 0, l = this.customFields.length; i < l; i++) {
- var val = this.customFields[i].value;
- // Is the custom field a function? If so evalute it, then pass it to the logevent and format.
- if (typeof val === "function") {
- val = val(this, logevent);
- }
- datValues.push([this.customFields[i].name, val]);
- }
- }
- return datValues;
- };
- Liquid_LogFormat.prototype.setKeys = function (loggerKey, messageKey, millisecondsKey, timeStampKey,
- levelKey, exceptionKey, urlKey) {
- var extract = Liquid.Logging.extractStringFromParam;
- this.loggerKey = extract(loggerKey, this.defaults.loggerKey);
- this.timeStampKey = extract(timeStampKey, this.defaults.timeStampKey);
- this.levelKey = extract(levelKey, this.defaults.levelKey);
- this.messageKey = extract(messageKey, this.defaults.messageKey);
- this.exceptionKey = extract(exceptionKey, this.defaults.exceptionKey);
- this.urlKey = extract(urlKey, this.defaults.urlKey);
- this.millisecondsKey = extract(millisecondsKey, this.defaults.millisecondsKey);
- };
- Liquid_LogFormat.prototype.setCustomField = function (field, value) {
- var update = false;
- for (var i = 0, l = this.customFields.length; i < l; i++) {
- if (this.customFields[i].name === field) {
- this.customFields[i].value = value;
- update = true;
- }
- }
- if (!update) {
- this.customFields.push({ "name": field, "value": value });
- }
- };
- Liquid_LogFormat.prototype.hasCustomFields = function () {
- return (this.customFields.length > 0);
- };
- Liquid_LogFormat.prototype.ignoresThrowable = function () {
- Liquid.Logging.handleError("Liquid_LogFormat.ignoresThrowable: format has no ignoresThrowable() method");
- };
- Liquid_LogFormat.prototype.formatWithException = function (logevent) {
- var preformatted = this.format(logevent);
- if (logevent.exception && this.ignoresThrowable()) {
- preformatted += logevent.getThrowableStr();
- }
- return preformatted;
- };
- Liquid_LogFormat.prototype.toString = function () {
- Liquid.Logging.handleError("Liquid_LogFormat: error LogFormatters must implement a toString method.")
- };
- //=======================================================================================
- // Liquid_LogAppender Object
- //=======================================================================================
- function Liquid_LogAppender() {
- this.format = new Liquid_PatternFormat();
- this.threshold = Liquid_LogLevel.All;
- this.loggers = [];
- };
- Liquid_LogAppender.prototype = new Liquid_EventSupport();
- Liquid_LogAppender.prototype.doAppend = function (logevent) {
- if ((eval(Liquid.Param.LoggingEnabled)) && logevent.level.level >= this.threshold.level) {
- this.append(logevent);
- }
- };
- Liquid_LogAppender.prototype.append = function (logevent) {
- };
- Liquid_LogAppender.prototype.setFormat = function (format) {
- if (format instanceof Liquid_LogFormat) {
- this.format = format;
- } else {
- Liquid.Logging.handleError("Liquid_LogAppender.setFormat: format supplied is not a subclass of Liquid_LogFormat");
- }
- };
- Liquid_LogAppender.prototype.getFormat = function () {
- return this.format;
- };
- Liquid_LogAppender.prototype.setThreshold = function (threshold) {
- if (threshold instanceof Liquid_LogLevel) {
- this.threshold = threshold;
- } else {
- Liquid.Logging.handleError("Liquid_LogAppender.setThreshold: threshold supplied to " +
- this.toString() + " is not a subclass of Liquid_LogLevel");
- }
- };
- Liquid_LogAppender.prototype.getThreshold = function () {
- return this.threshold;
- };
- Liquid_LogAppender.prototype.setAddedToLogger = function (logger) {
- this.loggers.push(logger);
- };
- Liquid_LogAppender.prototype.setRemovedFromLogger = function (logger) {
- Liquid.Logging.arrayRemove(this.loggers, logger);
- };
- Liquid_LogAppender.prototype.group = function () { };
- Liquid_LogAppender.prototype.groupEnd = function () { };
- Liquid_LogAppender.prototype.toString = function () {
- Liquid.Logging.handleError("Liquid_LogAppender.toString: all appenders must override this method");
- };
- //=======================================================================================
- // Liquid_SimpleDateFormat Object
- //=======================================================================================
- function Liquid_SimpleDateFormat(formatstring) {
- this.formatString = formatstring;
- this.regex = /('[^']*')|(G+|y+|M+|w+|W+|D+|d+|F+|E+|a+|H+|k+|K+|h+|m+|s+|S+|Z+)|([a-zA-Z]+)|([^a-zA-Z']+)/;
- this.monthNames = ["January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"];
- this.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
- this.TEXT2 = 0, this.TEXT3 = 1, this.NUMBER = 2, this.YEAR = 3, this.MONTH = 4, this.TIMEZONE = 5;
- this.types = {
- G: this.TEXT2,
- y: this.YEAR,
- M: this.MONTH,
- w: this.NUMBER,
- W: this.NUMBER,
- D: this.NUMBER,
- d: this.NUMBER,
- F: this.NUMBER,
- E: this.TEXT3,
- a: this.TEXT2,
- H: this.NUMBER,
- k: this.NUMBER,
- K: this.NUMBER,
- h: this.NUMBER,
- m: this.NUMBER,
- s: this.NUMBER,
- S: this.NUMBER,
- Z: this.TIMEZONE
- };
- this.ONE_DAY = 24 * 60 * 60 * 1000;
- this.ONE_WEEK = 7 * this.ONE_DAY;
- this.DEFAULT_MINIMAL_DAYS_IN_FIRST_WEEK = 1;
- var newDateAtMidnight = function (year, month, day) {
- var d = new Date(year, month, day, 0, 0, 0);
- d.setMilliseconds(0);
- return d;
- };
- Date.prototype.getDifference = function (date) {
- return this.getTime() - date.getTime();
- };
- Date.prototype.isBefore = function (d) {
- return this.getTime() < d.getTime();
- };
- Date.prototype.getUTCTime = function () {
- return Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(),
- this.getSeconds(), this.getMilliseconds());
- };
- Date.prototype.getTimeSince = function (d) {
- return this.getUTCTime() - d.getUTCTime();
- };
- Date.prototype.getPreviousSunday = function () {
- // Using midday avoids any possibility of DST messing things up
- var midday = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 12, 0, 0);
- var previousSunday = new Date(midday.getTime() - this.getDay() * this.ONE_DAY);
- return newDateAtMidnight(previousSunday.getFullYear(), previousSunday.getMonth(),
- previousSunday.getDate());
- };
- Date.prototype.getWeekInYear = function (minimalDaysInFirstWeek) {
- if (Liquid.Logging.isUndefined(this.minimalDaysInFirstWeek)) {
- minimalDaysInFirstWeek = this.DEFAULT_MINIMAL_DAYS_IN_FIRST_WEEK;
- }
- var previousSunday = this.getPreviousSunday();
- var startOfYear = newDateAtMidnight(this.getFullYear(), 0, 1);
- var numberOfSundays = previousSunday.isBefore(startOfYear) ?
- 0 : 1 + Math.floor(previousSunday.getTimeSince(startOfYear) / this.ONE_WEEK);
- var numberOfDaysInFirstWeek = 7 - startOfYear.getDay();
- var weekInYear = numberOfSundays;
- if (numberOfDaysInFirstWeek < minimalDaysInFirstWeek) {
- weekInYear--;
- }
- return weekInYear;
- };
- Date.prototype.getWeekInMonth = function (minimalDaysInFirstWeek) {
- if (Liquid.Logging.isUndefined(this.minimalDaysInFirstWeek)) {
- minimalDaysInFirstWeek = this.DEFAULT_MINIMAL_DAYS_IN_FIRST_WEEK;
- }
- var previousSunday = this.getPreviousSunday();
- var startOfMonth = newDateAtMidnight(this.getFullYear(), this.getMonth(), 1);
- var numberOfSundays = previousSunday.isBefore(startOfMonth) ?
- 0 : 1 + Math.floor(previousSunday.getTimeSince(startOfMonth) / this.ONE_WEEK);
- var numberOfDaysInFirstWeek = 7 - startOfMonth.getDay();
- var weekInMonth = numberOfSundays;
- if (numberOfDaysInFirstWeek >= minimalDaysInFirstWeek) {
- weekInMonth++;
- }
- return weekInMonth;
- };
- Date.prototype.getDayInYear = function () {
- var startOfYear = newDateAtMidnight(this.getFullYear(), 0, 1);
- return 1 + Math.floor(this.getTimeSince(startOfYear) / this.ONE_DAY);
- };
- };
- Liquid_SimpleDateFormat.prototype.setMinDaysInFirstWeek = function (days) {
- this.minDaysInFirstWeek = days;
- };
- Liquid_SimpleDateFormat.prototype.getMinDaysInFirstWeek = function () {
- return Liquid.Logging.isUndefined(this.minDaysInFirstWeek) ?
- this.DEFAULT_MINIMAL_DAYS_IN_FIRST_WEEK : this.minimalDaysInFirstWeek;
- };
- var padWithZeroes = function (str, len) {
- while (str.length < len) {
- str = "0" + str;
- }
- return str;
- };
- var formatText = function (data, numberOfLetters, minLength) {
- return (numberOfLetters >= 4) ? data : data.substr(0, Math.max(minLength, numberOfLetters));
- };
- var formatNumber = function (data, numberOfLetters) {
- var dataString = "" + data;
- // Pad with 0s as necessary
- return padWithZeroes(dataString, numberOfLetters);
- };
- Liquid_SimpleDateFormat.prototype.format = function (date) {
- var formattedString = "";
- var result;
- var searchString = this.formatString;
- while ((result = this.regex.exec(searchString))) {
- var quotedString = result[1];
- var patternLetters = result[2];
- var otherLetters = result[3];
- var otherCharacters = result[4];
- // If the pattern matched is quoted string, output the text between the quotes
- if (quotedString) {
- if (quotedString == "''") {
- formattedString += "'";
- } else {
- formattedString += quotedString.substring(1, quotedString.length - 1);
- }
- } else if (otherLetters) {
- // Swallow non-pattern letters by doing nothing here
- } else if (otherCharacters) {
- // Simply output other characters
- formattedString += otherCharacters;
- } else if (patternLetters) {
- // Replace pattern letters
- var patternLetter = patternLetters.charAt(0);
- var numberOfLetters = patternLetters.length;
- var rawData = "";
- switch (patternLetter) {
- case "G":
- rawData = "AD";
- break;
- case "y":
- rawData = date.getFullYear();
- break;
- case "M":
- rawData = date.getMonth();
- break;
- case "w":
- rawData = date.getWeekInYear(this.getMinimalDaysInFirstWeek());
- break;
- case "W":
- rawData = date.getWeekInMonth(this.getMinimalDaysInFirstWeek());
- break;
- case "D":
- rawData = date.getDayInYear();
- break;
- case "d":
- rawData = date.getDate();
- break;
- case "F":
- rawData = 1 + Math.floor((date.getDate() - 1) / 7);
- break;
- case "E":
- rawData = this.dayNames[date.getDay()];
- break;
- case "a":
- rawData = (date.getHours() >= 12) ? "PM" : "AM";
- break;
- case "H":
- rawData = date.getHours();
- break;
- case "k":
- rawData = date.getHours() || 24;
- break;
- case "K":
- rawData = date.getHours() % 12;
- break;
- case "h":
- rawData = (date.getHours() % 12) || 12;
- break;
- case "m":
- rawData = date.getMinutes();
- break;
- case "s":
- rawData = date.getSeconds();
- break;
- case "S":
- rawData = date.getMilliseconds();
- break;
- case "Z":
- rawData = date.getTimezoneOffset(); // This returns the number of minutes since GMT was this time.
- break;
- }
- // Format the raw data depending on the type
- switch (this.types[patternLetter]) {
- case this.TEXT2:
- formattedString += formatText(rawData, numberOfLetters, 2);
- break;
- case this.TEXT3:
- formattedString += formatText(rawData, numberOfLetters, 3);
- break;
- case this.NUMBER:
- formattedString += formatNumber(rawData, numberOfLetters);
- break;
- case this.YEAR:
- if (numberOfLetters <= 3) {
- // Output a 2-digit year
- var dataString = "" + rawData;
- formattedString += dataString.substr(2, 2);
- } else {
- formattedString += formatNumber(rawData, numberOfLetters);
- }
- break;
- case this.MONTH:
- if (numberOfLetters >= 3) {
- formattedString += formatText(this.monthNames[rawData], numberOfLetters, numberOfLetters);
- } else {
- // NB. Months returned by getMonth are zero-based
- formattedString += formatNumber(rawData + 1, numberOfLetters);
- }
- break;
- case this.TIMEZONE:
- var isPositive = (rawData > 0);
- // The following line looks like a mistake but isn't
- // because of the way getTimezoneOffset measures.
- var prefix = isPositive ? "-" : "+";
- var absData = Math.abs(rawData);
- // Hours
- var hours = "" + Math.floor(absData / 60);
- hours = padWithZeroes(hours, 2);
- // Minutes
- var minutes = "" + (absData % 60);
- minutes = padWithZeroes(minutes, 2);
- formattedString += prefix + hours + minutes;
- break;
- }
- }
- searchString = searchString.substr(result.index + result[0].length);
- }
- return formattedString;
- };
- Liquid.Logging.Liquid_SimpleDateFormat = Liquid_SimpleDateFormat;
- //=======================================================================================
- // Liquid_PatternFormat Object
- //=======================================================================================
- function Liquid_PatternFormat(pattern) {
- if (pattern) {
- this.pattern = pattern;
- }
- else {
- this.pattern = Liquid_PatternFormat.DEFAULT_CONVERSION_PATTERN;
- }
- this.customFields = []
- };
- Liquid_PatternFormat.TTCC_CONVERSION_PATTERN = "%t %l %c - %m%n";
- Liquid_PatternFormat.DEFAULT_CONVERSION_PATTERN = "%m%n";
- Liquid_PatternFormat.ISO8601_DATEFORMAT = "yyyy-MM-dd HH:mm:ss,SSS";
- Liquid_PatternFormat.DATETIME_DATEFORMAT = "dd MMM yyyy HH:mm:ss,SSS";
- Liquid_PatternFormat.ABSOLUTETIME_DATEFORMAT = "HH:mm:ss,SSS";
- Liquid_PatternFormat.prototype = new Liquid_LogFormat();
- Liquid_PatternFormat.prototype.format = function (logevent) {
- var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([acdxmMnlt%])(\{([^\}]+)\})?|([^%]+)/;
- var formattedString = "";
- var result;
- var searchString = this.pattern;
- // Cannot use regex global flag since it doesn't work with exec in Internet explorer 5 (compatibility!)
- while ((result = regex.exec(searchString))) {
- var matchedString = result[0];
- var padding = result[1];
- var truncation = result[2];
- var conversionCharacter = result[3];
- var specifier = result[5];
- var text = result[6];
- // Check if the pattern matched was just normal text
- if (text) {
- formattedString += "" + text;
- } else {
- // Create a raw replacement string based on the conversion
- // character and specifier
- var replacement = "";
- switch (conversionCharacter) {
- case "a":
- case "m": // Message
- var depth = 0;
- if (specifier) {
- depth = parseInt(specifier, 10);
- if (isNaN(depth)) {
- Liquid.Logging.handleError("Liquid_PatternFormat.format: invalid specifier '" +
- specifier + "' for conversion character '" + conversionCharacter +
- "' - should be a number");
- depth = 0;
- }
- }
- var messages = (conversionCharacter === "a") ? logevent.messages[0] : logevent.messages;
- for (var i = 0, len = messages.length; i < len; i++) {
- if (i > 0 && (replacement.charAt(replacement.length - 1) !== " ")) {
- replacement += " ";
- }
- if (depth === 0) {
- replacement += messages[i];
- } else {
- replacement += Liquid.Logging.formatObjectExpansion(messages[i], depth);
- }
- }
- break;
- case "c": // Logger name
- var loggerName = logevent.logger.name;
- if (specifier) {
- var precision = parseInt(specifier, 10);
- var loggerNameBits = logevent.logger.name.split(".");
- if (precision >= loggerNameBits.length) {
- replacement = loggerName;
- } else {
- replacement = loggerNameBits.slice(loggerNameBits.length - precision).join(".");
- }
- } else {
- replacement = loggerName;
- }
- break;
- case "d": // Date
- var dateFormat = Liquid_PatternFormat.ABSOLUTETIME_DATEFORMAT;
- if (specifier) {
- dateFormat = specifier;
- // Pick up special cases
- if (dateFormat == "ISO8601") {
- dateFormat = Liquid_PatternFormat.ISO8601_DATEFORMAT;
- } else if (dateFormat == "ABSOLUTE") {
- dateFormat = Liquid_PatternFormat.ABSOLUTETIME_DATEFORMAT;
- } else if (dateFormat == "DATE") {
- dateFormat = Liquid_PatternFormat.DATETIME_DATEFORMAT;
- }
- }
- // Format the date
- replacement = (new Liquid_SimpleDateFormat(dateFormat)).format(logevent.timeStamp);
- break;
- case "x": // Custom field (coming soon!)
- if (this.hasCustomFields()) {
- }
- break;
- case "n": // New line
- replacement = "\r\n";
- break;
- case "l": // Log Level
- replacement = logevent.level.name;
- break;
- case "t": // Time since game startup
- replacement = "" + logevent.timeStamp.getDifference(Liquid.Logging.gameStartDate);
- break;
- case "%": // Literal % sign
- replacement = "%";
- break;
- default:
- replacement = matchedString;
- break;
- }
- // Format the replacement according to any padding or
- // truncation specified
- var l;
- // First, truncation
- if (truncation) {
- l = parseInt(truncation.substr(1), 10);
- var strLen = replacement.length;
- if (l < strLen) {
- replacement = replacement.substring(strLen - l, strLen);
- }
- }
- // Next, padding
- if (padding) {
- if (padding.charAt(0) == "-") {
- l = parseInt(padding.substr(1), 10);
- // Right pad with spaces
- while (replacement.length < l) {
- replacement += " ";
- }
- } else {
- l = parseInt(padding, 10);
- // Left pad with spaces
- while (replacement.length < l) {
- replacement = " " + replacement;
- }
- }
- }
- formattedString += replacement;
- }
- searchString = searchString.substr(result.index + result[0].length);
- }
- return formattedString;
- };
- Liquid_PatternFormat.prototype.ignoresThrowable = function () {
- return true;
- };
- Liquid_PatternFormat.prototype.toString = function () {
- return "PatternFormat";
- };
- //=======================================================================================
- // Liquid_ConsoleAppender Object
- //=======================================================================================
- function Liquid_ConsoleAppender() {
- };
- Liquid_ConsoleAppender.prototype = new Liquid_LogAppender();
- Liquid_ConsoleAppender.prototype.format = new Liquid_PatternFormat();
- Liquid_ConsoleAppender.prototype.threshold = Liquid_LogLevel.Debug;
- Liquid_ConsoleAppender.prototype.append = function (logevent) {
- var appender = this;
- var getFormattedMessage = function (concatenate) {
- var formattedMessage = appender.getFormat().formatWithException(logevent);
- return (typeof formattedMessage == "string") ?
- (concatenate ? formattedMessage : [formattedMessage]) :
- (concatenate ? formattedMessage.join(" ") : formattedMessage);
- };
- var console = window.console;
- if (console && console.log) {
- // Log to console using specific logging
- // methods or revert to console.log otherwise
- var consoleMethodName;
- if (console.debug && Liquid_LogLevel.Debug.isGreaterThanOrEqual(logevent.level)) {
- consoleMethodName = "debug";
- } else if (console.info && Liquid_LogLevel.Info.equals(logevent.level)) {
- consoleMethodName = "info";
- } else if (console.warn && Liquid_LogLevel.Warn.equals(logevent.level)) {
- consoleMethodName = "warn";
- } else if (console.error && logevent.level.isGreaterThanOrEqual(Liquid_LogLevel.Error)) {
- consoleMethodName = "error";
- } else {
- consoleMethodName = "log";
- }
- if (typeof console[consoleMethodName].apply == "function") {
- console[consoleMethodName].apply(console, getFormattedMessage(false));
- } else {
- console[consoleMethodName](getFormattedMessage(true));
- }
- } else if ((typeof opera != "undefined") && opera.postError) { // Opera
- opera.postError(getFormattedMessage(true));
- }
- };
- Liquid_EventSupport.prototype.group = function (name) {
- if (window.console && window.console.group) {
- window.console.group(name);
- }
- };
- Liquid_ConsoleAppender.prototype.groupEnd = function () {
- if (window.console && window.console.groupEnd) {
- window.console.groupEnd();
- }
- };
- Liquid_ConsoleAppender.prototype.toString = function () {
- return "ConsoleAppender";
- };
- //=======================================================================================
- // Liquid_Log Object
- //=======================================================================================
- function Liquid_Log(name) {
- this.name = name;
- this.appenders = [];
- this.loggerlevel = null;
- this.appenderCache = null;
- this.children = [];
- this.parent = null;
- this.appenderCacheInvalidated = false;
- this.additive = true;
- this.isNull = (this.name === "[null]");
- this.isRoot = (this.name === "root");
- this.timers = {};
- };
- Liquid_Log.prototype.addChild = function (childLogger) {
- this.children.push(childLogger);
- childLogger.parent = this;
- childLogger.invalidateAppenderCache();
- };
- Liquid_Log.prototype.getAdditivity = function () {
- return this.additive;
- };
- Liquid_Log.prototype.setAdditivity = function (additivity) {
- var valueChanged = (this.additive != additivity);
- this.additive = additivity;
- if (valueChanged) {
- this.invalidateAppenderCache();
- }
- };
- Liquid_Log.prototype.addAppender = function (appender) {
- if (this.isNull) {
- Liquid.Logging.handleError("Liquid_Log.addAppender: you may not add an appender to the null logger");
- } else {
- if (appender instanceof Liquid_LogAppender) {
- if (!Liquid.Logging.arrayContains(this.appenders, appender)) {
- this.appenders.push(appender);
- appender.setAddedToLogger(this);
- this.invalidateAppenderCache();
- }
- } else {
- Liquid.Logging.handleError("Liquid_Log.addAppender: appender supplied ('" +
- Liquid.Logging.toStr(appender) + "') is not a subclass of Liquid_LogAppender");
- }
- }
- };
- Liquid_Log.prototype.removeAppender = function (appender) {
- Liquid.Logging.arrayRemove(this.appenders, appender);
- appender.setRemovedFromLogger(this);
- this.invalidateAppenderCache();
- };
- Liquid_Log.prototype.removeAllAppenders = function () {
- var appenderCount = this.appenders.length;
- if (appenderCount > 0) {
- for (var i = 0; i < appenderCount; i++) {
- this.appenders[i].setRemovedFromLogger(this);
- }
- this.appenders.length = 0;
- this.invalidateAppenderCache();
- }
- };
- Liquid_Log.prototype.getEffectiveAppenders = function () {
- if (this.appenderCache === null || this.appenderCacheInvalidated) {
- // Build appender cache
- var parentEffectiveAppenders = (this.isRoot || !this.getAdditivity()) ?
- [] : this.parent.getEffectiveAppenders();
- this.appenderCache = parentEffectiveAppenders.concat(this.appenders);
- this.appenderCacheInvalidated = false;
- }
- return this.appenderCache;
- };
- Liquid_Log.prototype.invalidateAppenderCache = function () {
- this.appenderCacheInvalidated = true;
- for (var i = 0, len = this.children.length; i < len; i++) {
- this.children[i].invalidateAppenderCache();
- }
- };
- Liquid_Log.prototype.log = function (level, params) {
- if (eval(Liquid.Param.LoggingEnabled) && level.isGreaterThanOrEqual(this.getEffectiveLevel())) {
- // Check whether last param is an exception
- var exception;
- var finalParamIndex = params.length - 1;
- var lastParam = params[finalParamIndex];
- if (params.length > 1 && lastParam instanceof Error) {
- exception = lastParam;
- finalParamIndex--;
- }
- // Construct genuine array for the params
- var messages = [];
- for (var i = 0; i <= finalParamIndex; i++) {
- messages[i] = params[i];
- }
- var loggingEvent = new Liquid_LogEvent(
- this, new Date(), level, messages, exception);
- this.callAppenders(loggingEvent);
- }
- };
- Liquid_Log.prototype.callAppenders = function (loggingEvent) {
- var effectiveAppenders = this.getEffectiveAppenders();
- for (var i = 0, len = effectiveAppenders.length; i < len; i++) {
- effectiveAppenders[i].doAppend(loggingEvent);
- }
- };
- Liquid_Log.prototype.setLevel = function (level) {
- // Having a level of null on the root logger would be very bad.
- if (this.isRoot && level === null) {
- Liquid.Logging.handleError("Liquid_Log.setLevel: you cannot set the level of the root logger to null");
- } else if (level instanceof Liquid_LogLevel) {
- this.loggerLevel = level;
- } else {
- Liquid.Logging.handleError("Liquid_Log.setLevel: level supplied to logger " +
- this.name + " is not an instance of Liquid_LogLevel");
- }
- };
- Liquid_Log.prototype.getLevel = function () {
- return this.loggerLevel;
- };
- Liquid_Log.prototype.getEffectiveLevel = function () {
- for (var logger = this; logger !== null; logger = logger.parent) {
- var level = logger.getLevel();
- if (level !== null) {
- return level;
- }
- }
- };
- Liquid_Log.prototype.group = function (name, initiallyExpanded) {
- if (eval(Liquid.Param.LoggingEnabled)) {
- var effectiveAppenders = this.getEffectiveAppenders();
- for (var i = 0, len = effectiveAppenders.length; i < len; i++) {
- effectiveAppenders[i].group(name, initiallyExpanded);
- }
- }
- };
- Liquid_Log.prototype.groupEnd = function () {
- if (eval(Liquid.Param.LoggingEnabled)) {
- var effectiveAppenders = this.getEffectiveAppenders();
- for (var i = 0, len = effectiveAppenders.length; i < len; i++) {
- effectiveAppenders[i].groupEnd();
- }
- }
- };
- Liquid_Log.prototype.time = function (name, level) {
- if (eval(Liquid.Param.LoggingEnabled)) {
- if (Liquid.Logging.isUndefined(name)) {
- Liquid.Logging.handleError("Liquid_Log.time: a name for the timer must be supplied");
- } else if (level && !(level instanceof Liquid_LogLevel)) {
- Liquid.logging.handleError("Logger.time: level supplied to timer " +
- name + " is not an instance of Liquid_LogLevel");
- } else {
- this.timers[name] = new Liquid_LogTimer(name, level);
- }
- }
- };
- Liquid_Log.prototype.timeEnd = function (name) {
- if (eval(Liquid.Param.LoggingEnabled)) {
- if (Liquid.Logging.isUndefined(name)) {
- Liquid.Logging.handleError("Liquid_Log.timeEnd: a name for the timer must be supplied");
- } else if (this.timers[name]) {
- var timer = this.timers[name];
- var milliseconds = timer.getElapsedTime();
- this.log(timer.level, ["Timer " + Liquid.Logging.toStr(name) + " completed in " + milliseconds + "ms"]);
- delete this.timers[name];
- } else {
- LiquidLog.internalLog.warn("Liquid_Log.timeEnd: no timer found with name " + name);
- }
- }
- };
- Liquid_Log.prototype.assert = function (expr) {
- if (eval(Liquid.Param.LoggingEnabled) && !expr) {
- var args = [];
- for (var i = 1, len = arguments.length; i < len; i++) {
- args.push(arguments[i]);
- }
- args = (args.length > 0) ? args : ["Assertion Failure"];
- args.push("\r\n");
- args.push(expr);
- this.log(Liquid_LogLevel.Error, args);
- }
- };
- Liquid_Log.prototype.toString = function () {
- return "Liquid_Log [" + this.name + "]";
- };
- Liquid_Log.prototype.isLoggingEnabled = function () {
- return eval(Liquid.Param.LoggingEnabled);
- };
- Liquid_Log.prototype.trace = function () {
- this.log(Liquid_LogLevel.Trace, arguments);
- };
- Liquid_Log.prototype.debug = function () {
- this.log(Liquid_LogLevel.Debug, arguments);
- };
- Liquid_Log.prototype.info = function () {
- this.log(Liquid_LogLevel.Info, arguments);
- };
- Liquid_Log.prototype.warn = function () {
- this.log(Liquid_LogLevel.Warn, arguments);
- };
- Liquid_Log.prototype.error = function () {
- this.log(Liquid_LogLevel.Error, arguments);
- };
- Liquid_Log.prototype.fatal = function () {
- this.log(Liquid_LogLevel.fatal, arguments);
- };
- Liquid_Log.prototype.trace.isEntryPoint = true;
- Liquid_Log.prototype.debug.isEntryPoint = true;
- Liquid_Log.prototype.info.isEntryPoint = true;
- Liquid_Log.prototype.warn.isEntryPoint = true;
- Liquid_Log.prototype.error.isEntryPoint = true;
- Liquid_Log.prototype.fatal.isEntryPoint = true;
- //===========================================================================================
- // Static Methods & Setup
- //===========================================================================================
- // Array of loggers and their names.
- Liquid.Logging.Loggers = [];
- Liquid.Logging.LoggerNames = [];
- // Setup root logger.
- var rootLogger = new Liquid_Log("root");
- rootLogger.setLevel(Liquid_LogLevel.Debug);
- // Static function retrieve the rootLogger
- Liquid.Logging.getRootLogger = function () {
- return rootLogger;
- };
- // Setup null logger.
- var nullLogger = null;
- Liquid.Logging.getNullLogger = function () {
- if (!nullLogger) {
- nullLogger = new Liquid_Log("[null]");
- nullLogger.setLevel(Liquid_LogLevel.Off);
- }
- return nullLogger;
- };
- // Setup default logger.
- var defaultLogger = null;
- Liquid.Logging.getDefaultLogger = function () {
- if (!defaultLogger) {
- defaultLogger = Liquid.Logging.getLogger(Liquid.Param.DefaultLogName);
- var appender = new Liquid_ConsoleAppender();
- appender.setFormat(new Liquid_PatternFormat(Liquid.Param.LogPattern));
- defaultLogger.addAppender(appender);
- defaultLogger.setLevel(Liquid_LogLevel.Debug);
- }
- return defaultLogger;
- };
- // Static function to get a logger by name, if the given logger doesn't exists we create it.
- Liquid.Logging.getLogger = function (loggerName) {
- // Use default logger if loggerName is not specified or invalid
- if (typeof loggerName != "string") {
- loggerName = "[anonymous]";
- LiquidLog.internalLog.warn("Liquid.Logging.getLogger: non-string logger name " +
- Liquid.Logging.toStr(loggerName) + " supplied, returning anonymous logger");
- }
- // Do not allow retrieval of the root logger by name
- if (loggerName == "root") {
- Liquid.Logging.handleError("Liquid.Logging.getLogger: root logger may not be obtained by name");
- }
- // Create the logger for this name if it doesn't already exist
- if (!Liquid.Logging.Loggers[loggerName]) {
- var logger = new Liquid_Log(loggerName);
- Liquid.Logging.Loggers[loggerName] = logger;
- Liquid.Logging.LoggerNames.push(loggerName);
- // Set up parent logger, if it doesn't exist
- var lastDotIndex = loggerName.lastIndexOf(".");
- var parentLogger;
- if (lastDotIndex > -1) {
- var parentLoggerName = loggerName.substring(0, lastDotIndex);
- parentLogger = Liquid.Logging.getLogger(parentLoggerName); // Recursively sets up grandparents etc.
- } else {
- parentLogger = rootLogger;
- }
- parentLogger.addChild(logger);
- }
- return Liquid.Logging.Loggers[loggerName];
- };
- // LiquidLog object, used internally.
- function LiquidLogObj() {
- }
- LiquidLogObj.prototype = Object.create(Liquid_EventSupport.prototype);
- var LiquidLog = new LiquidLogObj();
- LiquidLog.setTypes(["load", "error"]);
- var internalLog = new Liquid_InternalLog();
- LiquidLog.internalLog = internalLog;
- //=======================================================================================
- // Main Execution & Plugin Handling
- //=======================================================================================
- (function () {
- var Liquid_Logging_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
- Game_Interpreter.prototype.pluginCommand = function (command, args) {
- Liquid_Logging_Game_Interpreter_pluginCommand.call(this, command, args);
- // Process event commands.
- if (command === 'LiquidLog') {
- var loglevel = args[0];
- var logger = Liquid.Logging.getDefaultLogger();
- var msgStartIndex = 1;
- if ((loglevel === "info" || loglevel === "error" || loglevel === "warn" || loglevel != "debug" || loglevel === "fatal") != true) {
- loglevel = "info";
- }
- var msg = "";
- for (msgStartIndex; msgStartIndex < args.length; msgStartIndex++) {
- if (msgStartIndex < args.length) {
- msg += args[msgStartIndex] + " ";
- }
- else {
- msg += args[msgStartIndex];
- }
- }
- switch (loglevel) {
- case "info":
- logger.info(msg);
- break;
- case "debug":
- logger.debug(msg);
- break;
- case "warn":
- logger.warn(msg);
- break;
- case "error":
- case "fatal":
- logger.error(msg);
- break;
- }
- }
- };
- })();
- //===========================================================================================
- // End of File
- //===========================================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement