Type Safe Logger

Type safe destination transparent logger for C++                                                                                                                                                              Home


#pragma once

#include <string>
#include <deque>
#include <map>
#include <sstream>

#include "StreamFormatter.h"

enum LogSection
{
   LOGSECTION_INIT,
   LOGSECTION_SHUTDOWN,
   LOGSECTION_SERVICES
   // Add other logging sections or categories
};

enum LogLevel
{
   LOGLEVEL_TRACE,
   LOGLEVEL_INFO,
   LOGLEVEL_WARNING,
   LOGLEVEL_ERROR
};

class Logger : public StreamFormatter<Logger>
{
   private: LogSection _logSection;
   private: LogLevel _logLevel;

   public: Logger(LogSection logSection, LogLevel logLevel, const std::string& fmtSpec) : StreamFormatter(fmtSpec),
      _logSection(logSection),
      _logLevel(logLevel)
   {
   }

   public: ~Logger()
   {
      try
      {
         const std::string streamText = StreamFormatter::PrepareStream();
         Flush(streamText);
      }
      catch(...)
      {
         _ASSERTE(0);
      }
   }

   public: template<typename T> Logger& operator <<(const T& tObj)
   {
      StreamFormatter::operator <<(tObj);
      return *this;
   }

   private: virtual void Flush(const std::string& streamText)
   {
      std::ostringstream ostr;
      ostr << "!@#[" << this->_logSection << "] [" << this->_logLevel << "] " << streamText;
      OutputDebugString(ostr.str().c_str()); //streamText.c_str());
   }

   private: Logger(const Logger&);
   private: Logger& operator=(const Logger&);
};