How to create a log file to write logs and timestamp using C++

  • Thread starter Thread starter aditya satya prakash
  • Start date Start date
A

aditya satya prakash

Guest
Hi,

I am working on my first C++ project and wanted to create a simple log to write logs and timestamp in that project to know the project workflow and the result.

I created the log file with class "logstream", in mainserv.h like as shown below:

In the mainserv.h file,

#include <fstream>

class logstream :
public std::ofstream
{
public:
logstream();
~logstream();

protected:
std::streambuf *psbuf, *backup;
std::ofstream filestr;
};

I am using the "logstrem" class and it's object in another file "apcserv.cpp" like as shown below:

in apcserv.cpp file,

#include "mainserv.h"
logstream::logstream()
{
filestr.open("test_streaming.txt", std::ofstream::app);

backup = std::clog.rdbuf();
psbuf = filestr.rdbuf();
std::clog.rdbuf(psbuf);
}

logstream::~logstream()
{
std::clog.rdbuf(backup);

filestr.close();
}

And in the below function i am using the log object.

int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
TCHAR serviceDesc[MAX_PATH] = _T("");
TCHAR servicePath[MAX_PATH] = _T("");

logstream log; // redirects clog and restores it when it goes out of scope

std::clog << "We are in the Entry Point Function : WinMain" << std::endl;
OS_VERSION osVersion = APCWindowsVersion::GetOperatingSystemVerson();

resource.GetString(serviceDesc, IDS_SERVICE_DESCRIPTION);
std::clog << "Service Description " << serviceDesc << "Checking Service Description" << std::endl;
RegisterService(servicePath, APC_DALI_SERVICE_NAME, APC_DALI_SERVICE_NAME, serviceDesc);
std::clog << "Service Path " << servicePath << "Checking Service Path" << std::endl;

return 0;
}

I wanted to know is it the correct way? And also I heard singleton pattern is used to create a log file . Can I use Singleton pattern here in this case? In which real time scenario can i use Singleton pattern?

Please provide your valuable thoughts on this.


Y A S Prakash

Continue reading...
 
Back
Top