An XNA Message Logger

Written by Dean Edis.

Whilst developing Lunar Panda we wrote a very simple logger for capturing messages from the application. They would be written using Debug.WriteLine(), allowing us to examine them using a debugger. This was fine until, during beta testing, we wanted a simpler way for beta testers to be able to describe any issues they might find.

In comes a new message logger, built on top of our powerful ‘Layers’ code.

The implementation is still fairly simple, but the messages can now be accessed at runtime even without a debugger. We use SCROLL LOCK to toggle the visibility of the messages using a ‘layer’ on top of the main game screen.

Here’s an example. Notice how the layer is slightly transparent, allowing us to ‘dim’ the background and make the message text clear to read.

The messages can be scrolled using PAGE UP and PAGE DOWN, or HOME and END will navigate to the start/end of the log.

Adding the logging layer is achieved with a simple two-stage process.

Firstly create a new Logger instance to record your messages. In the sample code do this in the main game’s constructor:

m_logger = new Logger();

Secondly we create a LoggerLayer, giving it our Logger instance and the font to use for display:

// Create a Layers object, and define the order of the layers to 

display.

m_rootLayers = new Layers(m_graphics.GraphicsDevice, 
m_graphics.PreferredBackBufferWidth, 
m_graphics.PreferredBackBufferHeight);
    m_rootLayers.Add(textureLayer);
    m_rootLayers.Add(new LoggerLayer(m_graphics.GraphicsDevice, 
m_graphics.PreferredBackBufferWidth, 
m_graphics.PreferredBackBufferHeight, speccyFont, m_logger));

Now you just need to call m_logger.Log(...) to write your messages! In the sample I do this here:

private void WriteSomeLogMessages()
 {
      m_logger.Log("Content loaded.");
      m_logger.Log("Message 1\nMessage 2\nMessage 3");
      for (int i = 0; i < 100; i++)
           m_logger.Log("Doing something: " + i);

      m_logger.Log("Last message.");
 }

Run the sample application and hit SCROLL LOCK!

You can download the full source from the link below.

Let us know if you find the code useful, and especially if you add your own enhancements!

DOWNLOAD SOURCE