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");

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 {
    function loadingUser () {};

    function loadUserSuccess() {};

    function loadUserFailed() {};

Now in our user loading code:

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

    // leaving out the user loading code


    // oh, no! Something went wrong here, let's log it!

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