Menu
Coddy logo textTech

Recap - Logger Factory

Part of the Object Oriented Programming section of Coddy's Lua journey — lesson 66 of 70.

challenge icon

Challenge

Easy

Let's build a logging system using the Factory pattern! You'll create different types of loggers that share a common interface, then use a factory function to produce the right logger based on a simple string argument.

You'll organize your code across four files:

  • ConsoleLogger.lua: Create a ConsoleLogger class with a :new() constructor and a :log(message) method. When :log() is called, it should print the message with a [CONSOLE] prefix, like [CONSOLE] Your message here.
  • FileLogger.lua: Create a FileLogger class with the same structure—a :new() constructor and a :log(message) method. This logger should print messages with a [FILE] prefix instead.
  • LoggerFactory.lua: This is where the Factory pattern comes together! Create a createLogger(loggerType) function that accepts a string argument. If the type is "console", return a new ConsoleLogger. If the type is "file", return a new FileLogger. The factory handles all the details of which class to instantiate.
  • main.lua: Require your LoggerFactory module. Read two inputs: the logger type and a message to log. Use your factory to create the appropriate logger, then call its :log() method with the message.

The elegance of this design is that your main code only interacts with the factory—it doesn't need to know about ConsoleLogger or FileLogger directly. Both loggers implement the same :log() interface, so they can be used interchangeably.

You will receive two inputs:

  1. Logger type (either "console" or "file")
  2. The message to log

For example, if the inputs are console and Application started, the output should be:

[CONSOLE] Application started

If the inputs are file and Saving user data..., the output should be:

[FILE] Saving user data...

Try it yourself

-- main.lua
-- Main entry point for the logging system

local LoggerFactory = require('LoggerFactory')

-- Read inputs
local loggerType = io.read()
local message = io.read()

-- TODO: Use the LoggerFactory to create the appropriate logger
-- Then call the :log() method with the message

All lessons in Object Oriented Programming