CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 3 of 6 · 1 min read

Classes and patterns

Four small patterns in one design.

Class Kind Job in one sentence
Level enum The five levels, ordered by seriousness
LogRecord immutable value Time, level, logger name, message and optional error
Formatter interface Turns a record into text (strategy)
Appender interface Receives a record and writes it somewhere (observer)
MemoryAppender, AsyncAppender classes A list for tests, and a queue and worker around another appender
Logger entity Holds a name, an optional level, a parent and appenders, and filters and dispatches
LogManager entity Creates and finds loggers by name, building the parent chain
Clock injected supplier Gives the time, so tests control it

The patterns, and where each appears:

  • Strategy (Level 4, module 1): the formatter. A new text layout is a new class.
  • Observer (Level 4, module 2): appenders are listeners on a logger. The logger does not know what an appender does with a record.
  • Chain along the hierarchy (close to Level 4, module 8): a record travels up through parents, and each parent's appenders get it. The level is found by walking up until a level is set.
  • Decorator (Level 4, module 5): AsyncAppender wraps another appender and has the same interface, adding the queue.
  • Registry instead of singleton (Level 3, module 4): the manager holds the loggers. It is created in main and passed in, so tests can make their own and no global state is shared. A static getLogger is a convenience on top of this.

The record is immutable (Level 5, module 2). It is created once and handed to many appenders, and possibly to another thread, so no appender can change what the others see.

Check yourself: 1. Which pattern is the formatter, and which is the appender? 2. Why is the record immutable? 3. Why use a manager and not one global logger?