Usability - Productivity - Business - The web - Singapore & Twins

Creative logging with $A.log()

In Lightning applications there are two ways to log: console.log(..) and $A.log(...). This has led to some confusion what to use.

The official statement: $A.log() will eventually go away, use console.log()

This is a real pity, since $A.log() is quite powerful and closer to what a developer would expect from logging. One reason for its demise: in a production setting $A.log() would output - nothing. There's no official documentation how to change that and the $A.logger.subscribe(...) method is neither documented nor guaranteed, only mentioned on Stack Exchange. So...

Enjoy it while it lasts

The simple case to activate console output in production is to add a helper function that can be triggered by a button or whatever you find necessary:

$A.logger.subscribe( "INFO", function( level, message, error ) {
                                console.log( message );
                                console.log( error );

Instead of sending output to the console, which could confuse users seeing all that 'tech' stuff, you could redirect it into a custom component (the following snippet fits into an onInit script):

var target = component.find("loggerlist").getElement();
$A.logger.subscribe( "INFO", function( level, message, error ) {
                               target.innerHTML += "<li>"+message+"</li><li>"+error+"</li>";

The target element would be <ol auraid="loggerlist"> so you get a running list.

Across the network

One is not limited to staying on the same machine. With a few lines of code logging can happen on a remote location as well. The following shows logging using websockets. For a production run (e.g. permanent instrumentation) I would make it a little more robust, like keeping the connection open and check if it is still there or send JSON, but for the occasional support this is good enough:

$A.logger.subscribe( "INFO", function( level, message, error ) {
    var wsEndPoint = 'wss://somewebsocket.url/ws/log';
    var connection = new WebSocket(wsEndPoint);
     connection.onopen = function(event) {

I'll show a potential receiving end implementation in a future post.
As I said: enjoy it while it lasts, it might go away soon. YMMV

Posted by on 03 April 2018 | Comments (0) | categories: Salesforce


  1. No comments yet, be the first to comment