Skip to content

Logging with log4javascript

sebez edited this page Nov 20, 2014 · 2 revisions

Introduction

log4javascript can be used for client logging.

It uses log4j-like configuration and API with named loggers, appenders, level, layout, etc. Available appenders include : console appender, DOM appender, popup appender, Server API appender. Adding new appender (for instance a localStorage appender) seems uncomplicated.

Setup

Logger directory

In the application root, a loggers directory is created :

  • app
    • loggers
      • index.js
      • Spa.Application.js
      • Spa.View.js

Declaration

Each logger is declared in its own module as a singleton :

module.exports = log4javascript.getLogger("Spa.Application");

Configuration

The main index.js script sets up the configuration of the loggers.

/* Chargement des singletons de logger */
var logSpaApplication = require('./Spa.Application');
var logSpaView = require('./Spa.View');

/* Définition des appenders */
var consoleAppender = new log4javascript.BrowserConsoleAppender();
consoleAppender.setLayout(new log4javascript.PatternLayout("%d{HH:mm:ss,SSS} %c %p %m"));

/* Configuration des loggers */
logSpaApplication.addAppender(consoleAppender);
logSpaView.addAppender(consoleAppender);

Initialization

In the application intialize script, the first thing to do is to call the loggers main script :

var initialize = {
    init: function init(params) {
        return $(function () {

            /* Init loggers. */
            require('./loggers');            

            /* ... */

            /* Initialize application. */
            application.initialize();
        });
    }
};

module.exports = initialize;

Usage

To use a logger, we require the log singleton and use its log4J-like API :

var log = require('./loggers/Spa.Application');
log.info("Démarrage SPA...");

Result in Chrome console : capture

Clone this wiki locally