Semantic logging in JavaScript.

How did I live without semantic logging for so long?

This is how I used to debug running applications:

log("Started reading database");
...
log("Read database");
...
log("Error!");

Look familiar?

Aside from not specifying log levels, you've probably written text to log files before. This works fine as long as you enjoy reading reams of unformatted text.

Semantic logging is a simple concept - create classes with functions to define the log entries then call the functions when you want to log something.

Some magical code will convert the class and function names into a uniform log structure, usually adding metadata like datetimes.

Normally I dislike magical code being too hard to debug, however in this case we want as little boilerplate in our log code as possible.

An example logger class

class UserLogger extends SemanticLogger {
    @info
    function loadingUser () {};

    @info
    function loadUserSuccess() {};

    @warn
    function loadUserFailed() {};
}

Now in our user loading code:

function loadUser (username, password) {
    var logger = new UserLogger();
    logger.loadingUser();

    // leaving out the user loading code

    logger.loadUserSuccess();

    // oh, no! Something went wrong here, let's log it!
    logger.loadUserFailed();
}

You've probably noticed we're using classes and decorators and therefore ES7. The syntactic sugar makes this usable.

Some benefits of semantic logging:

  • More uniform logs - better to consume with analytics or infrastructure automation.
  • Logs are less tightly coupled to the implementation. Changing the implementation doesn't necessarily change the log text.
  • You shouldn't really have string literals in your code, it's bad practice.

I couldn't find a JavaScript library to perform this magic, so I've created one you can clone/fork on GitHub