Search code examples
consoletitanium

Get all the Ti.API.info strings to an array


I need to get all the Ti.API.info strings to an array by using some function at the end of the app.js file, How do I get all those string to array once it has been printed on console. For Example

Ti.API.info("Hello");
Ti.API.info("Good Morning");
Ti.API.info("Good Afternoon");
Ti.API.info("Good Evening");

at the end of the code I need to have an function to retrieve and store all the strings in array. How do I can do that, Can anyone help me?


Solution

  • You can override the existing Ti.API.info function, but, this isn't highly recommended as people might not know that you changed it (even if changes made doesn't impact the initial behavior).

    I think that the best way is to define your own logger.

    customLogger.js

    var Logger = function () {
        /* Define an array to store logs */   
        this._logs = [];
    }
    
    Logger.prototype.info = function () {
        /* Iterate over each msg and store them */
        for(var i = 0, msg; msg = arguments[i]; i++) {
            this._logs.push({date: new Date(), msg: msg.toString()});          
        }
    
        /* Do the classic log */
        Ti.API.info.apply(Ti.API, arguments);
    }
    
    Logger.prototype.getLogs = function () {
        return JSON.stringify(this._logs, null, "\t");
    }
    
    /* Export The API */
    var logger = new Logger(Ti.API);
    exports.info = function() {
        Logger.prototype.info.apply(logger, arguments);
    };
    
    exports.getLogs = function () {
        return Logger.prototype.getLogs.apply(logger);
    };
    

    Then, in your app.js

    var Logger = require("customLogger"); // Adapt the path to suits your architecture
    
    Logger.info("My log message");
    
    // ...
    
    Ti.API.debug("Those are my logs:\n", Logger.getLogs());