DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Logging Class( Using Singleton )

11.16.2011
| 5054 views |
  • submit to reddit
        // A logging class, using a singleton.
// Will create a backup file
// Coded in C++
// Doesn't use a pointer for the singleton
// Coded by Ian T. Jacobsen 2011

// Header
#ifndef LOGGING_H
#define LOGGING_H

#include <string>
#include <fstream>

#define LOG CLogging::Inst("log.log").Log

class CLogging
{
public:
    static CLogging& Inst(char* filename);
    void Log(std::string message);
    ~CLogging();
protected:
    CLogging(char* filename);
private:
    char* m_filename;
    std::fstream m_fOut;
};

#endif // LOGGING_H

// Source file
#include "include/logging.h"
#include <time.h>

        CLogging& CLogging::Inst(char* filename)
        {
            static CLogging m_pInstance(filename);
            return m_pInstance;
        }

        CLogging::CLogging(char* filename)
            : m_filename(filename)
        {
            std::fstream temp(filename, std::ios_base::in);

            std::fstream backup(std::string(std::string(m_filename).append(".backup")).c_str(), std::ios_base::out | std::ios_base::trunc);

            temp.seekg(0,std::ios::end);
            int length = temp.tellg();
            temp.seekg(0,std::ios::beg);

            char* buffer = new char[length];

            temp.read(buffer,length);

            backup.write(buffer, length-4);

            delete[] buffer;
            temp.close();
            backup.close();

            m_fOut.open(filename, std::ios_base::out | std::ios_base::trunc);

            char date[9];
            _strdate(date);

            m_fOut<< "Log file started on (mm/dd/year) " << date << "\n\n";
        }

        CLogging::~CLogging() {
            m_fOut<< "\nLogging ended.";

            m_fOut.close();
        }

        void CLogging::Log(std::string message)
        {
            m_fOut<< message << "\n";
        }