Menu

A Conventional Blog for Convention Based Coders

Aurelia – Easy logging with the LogManager

Writing debug output while developing is great. After a few days you have pages and pages of logs in your browser console, and when it comes time to run tests or deploy to UAT you can trawl through thousands of lines of code and comment them all out!

Or… you can use the built in Aurelia logger! This lets turn on or off error output, and even choose the level so you can show only serious errors at deployment time. You can even add runtime options to switch the error level so you can get more detailed output on your live system.

So how do we make this as easy to use as the console? Simple, we simply create a module exposing the Aurelia logger like this:

log.js

log.js

JavaScript

1

2

import{LogManager}from"aurelia-framework";

export varlog=LogManager.getLogger('insight');

Then in out code we say something like

JavaScript

1

import{log}from"../services/log";

Then, whenever we want to simply say

JavaScript

1

2

3

log.debug('Toaster loaded: ',this.toasterService);

log.info('Yes, I made it this far!');

log.error('Serious problem loading waffles');

Now, in our startup code, instead of the usual .developmentLogging() command, we can add something with a little more detail as to what we want to display, such as

JavaScript

1

2

3

4

5

import{LogManager}from"aurelia-framework";

import{ConsoleAppender}from"aurelia-logging-console";

LogManager.addAppender(newConsoleAppender());

LogManager.setLevel(LogManager.logLevel.debug);

This tells Aurelia that by default we want our logs to go to the console, although we could also direct them to a remote logging service, and also sets the level at which we’d like to display them.

We can also now change the log level based on the URL:

JavaScript

1

2

3

LogManager.setLevel(window.location.search.match(/.*\?debug.*/i)

?LogManager.logLevel.debug

:LogManager.logLevel.error);

Alternatively we could look for localhost in the host name to always enable debug logging on local test machines.

Note the use of the name ‘insight’ in the getLogger method. You can add your own application name there, and it will appear in the console log like this: