Console Logging in Phonegap
Writing to the console is an invaluable tool in web development, and many of us keep the console open in Chrome almost indefinitely. Here is how you can get that same functionality in PhoneGap when compiling a native iOS or Android app.
PhoneGap Plugins
Out of the box, PhoneGap doesn’t do much as far as device-level integration. In order to use the phone’s features, you need to add plugins. One such plugin is for console use.
Bash
phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-console.git
phonegap build ios
Run this command in the root of your PhoneGap site, and you’ll now have command line access. As usual, compile your app using the build command, and you can now see console.log statements in your platforms when testing compiled apps. These will show up in the following places by platform:
iOS
Log messages show up in the debug panel at the bottom of Xcode.
Android
Log messages show up in the command line tool logcat. This is also bundled into the Android Eclipse plugin.
Comments (5)
Leave a Reply
okay, so then how do I filter logcat so that I’m only looking at my console logs for my app?
Link to commentThere is an easy way – you can use cloud logger. It will collect all logs and errors from devices and make them available via web – try jslog.me
Link to commentActually, I’m not even getting my console.logs. I searched logcat for my logs and they weren’t even there. Is there some kind of permission I need to enabled?
Link to commentiOS may not be recognizing the console plugin. I’ve noticed this is a bug in Phonegap when adding new plugins. After you add it, try removing both the /plugins/ios.json and /platforms/ios directories. Then build again.
Link to commentYes… but some of us don’t use Xcode to do iOS development. We use PhoneGap. So there’s no debug panel where one might view those log entries. Personally, I just created a quick-and-dirty function in my PhoneGap’s index.html file:
var isDebug = true;
function log(strMsg) {
if (isDebug) {
$.getJSON(strMyServer + ‘/app/log/’ + strMsg, function(jsonData) {
//
});
}
}
…and something in the /routes/app.inc.js file on my server:
router.get(‘/app/log/:msg’, function(req, res, next) {
var strMsg = ‘LOG: ‘ + req.params.msg.replace(/\%20/g, ‘ ‘);
res.sendStatus(200);
setTimeout(function() {console.log(strMsg);}, 100);
});
And now I’m just watching the logs on my server. I just make sure that I toggle that isDebug variable before pushing the code to production.
Link to comment