CLog
A quick programming tutorial

using namespace CLog;

Table of Content

  1. Introduction
  2. Getting Started
  3. Writing Entries
  4. Feedback

Introduction

CLog was designed as a very simple class that would allow me to simply the handling of error reporting in my various programs. The concept of having a log file that can store runtime generated information in is great but, if your program encounters an error and exits abnormally your entire log file may be lost, because the file descriptor to the log file is still one, and your operating system may have not yet synchronized memory buffers with the hard drive. With the program terminated, the entries your program has written have been lost. The solution to this is simply openning and closing the log file in between writing. This is the very reason I created this class. It takes care of opening and closing the file, as well as prepending a date and time to each log file entry. Besides that it really doesn't do much.

Getting Started

There is only one available public constructor for the class, so we have little choice but to use it.

CLog(const char *path, bool append_mode = false);

At this point we have to decide the location of our log file. When debuging programs I recommend using something as trivial as myprogram.log and during production usage I usally revert to something like /var/myprogram.log or something else usually read from the programs startup config. The second thing you must decide at this point is whether or not to append data to an already existing log file, or replace any existing one. I usually choose to append my entries, as the dates and times that are written with each message help determine the program's instance that wrote it. Remember that when creating a file, your program must have write permissions to the location you are placing it. If it doesn't, the won't work!

Clog *pLog = new CLog("/var/special.log", true);

Writing Entries

This is the real use of this class. Using the only available function write(...) whose arguments are identical to fprintf(...) you can create log entries and have the object take care of writing them to the disk. See example below.

pLog->write("Unable to create thread for handling IPv6 packets. Error code: %s",
	 strerror(herror));

If after making a call like this you open your log file and don't see any entries, make sure your program has write permissions to the log file.

Feedback

If you have any questions or something in this tutorial is unclear please email me.


"Never fear to do something new. Remember, amateurs build the Arc, professionals made the Titanic."

Last update: Wednesday, 11th October, 2023
Copyright © 2001-2024 by Lukasz Tomicki