liveBook · Manning

Log

As explained in Secrets of the JavaScript Ninja, Second Edition

The practice of recording useful runtime information to help understand program behavior or diagnose problems.

Logging records useful runtime information to help you understand program behavior or track down bugs. Scattered logging statements can clutter domain code and be easy to forget when new properties are added. section 8.2.1

A JavaScript Proxy can log property reads and writes through its get and set traps. This keeps logging separate from the object’s domain code and applies the same behavior across its properties. section 8.2 section 8.2.1

Listing 8.9. Using proxies makes it easier to add logging to objects
function makeLoggable(target){                             #A
  return new Proxy(target, {                               #B
    get: (target, property) => {                           #C
      report("Reading " + property);                       #C
      return target[property];                             #C
    },                                                     #C

    set: (target, property, value) => {                       #D
      report("Writing value " + value + " to " + property);   #D
      target[property] = value;                               #D
    }                                                         #D
  });
}

let ninja = { name: "Yoshi"};                              #E
ninja = makeLoggable(ninja);                               #E

assert(ninja.name === "Yoshi", "Our ninja Yoshi");         #F
ninja.weapon = "sword";                                    #F

See a makeLoggable function wrap a Ninja object in a Proxy that reports property reads and writes. section 8.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines logging and works through proxy get and set traps, demonstrating property access logging without covering broader instrumentation.
Examples
Uses a Ninja skillLevel getter and setter, then a makeLoggable proxy that reports reads and writes.
What you can do after
Apply it via JavaScript Proxy traps to log property reads and writes without scattering statements through domain code.
How it connects
Connects logging with JavaScript proxies and contrasts proxy traps with getters and setters.

Also explained in

Compare how 14 books explain log →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.