Although there are many nice logging libraries for C++,
sometimes you may simply need a basic level of logging for your application.
STL provides a way to redirect standrad output and standard error to a stream.
Using this feature, we can easily redirect them to a log file.
Logger.h
#pragma once
/*
* Copyright (c) 2007 Onur Cinar.
* All Rights Reserved
*
* Provided under LGPL license.
*/
#include <fstream>
#include <string>
/**
* Logger.
*
* @author Onur Cinar
*/
class Logger
{
public:
/**
* Constructor.
*
* @param[in] logFile log file.
*/
Logger (const std::string& logFile);
/**
* Destructor.
*/
virtual ~Logger ();
private:
/** Log stream. */
std::ofstream logOut;
/** Old cout. */
std::streambuf* oldCout;
/** Old cerr. */
std::streambuf* oldCerr;
/** Old clog. */
std::streambuf* oldClog;
};
Logger.cpp
/*
* Copyright (c) 2007 Onur Cinar.
* All Rights Reserved
*
* Provided under LGPL license.
*/
#include <iostream>
/**
* Logger.
*
* @author Onur Cinar
*/
Logger::Logger (const std::string& logFile)
: logOut(logFile.c_str(), std::ios::out | std::ios::trunc)
{
// Save old stream buffers
oldCout = std::cout.rdbuf();
oldCerr = std::cerr.rdbuf();
oldClog = std::cerr.rdbuf();
// Redirect cout and cerr
std::cout.rdbuf(logOut.rdbuf());
std::cerr.rdbuf(logOut.rdbuf());
std::clog.rdbuf(logOut.rdbuf());
}
Logger::~Logger ()
{
// Restore old stream buffers
std::cout.rdbuf(oldCout);
std::cerr.rdbuf(oldCerr);
std::clog.rdbuf(oldClog);
// Close log
logOut.close();
}
Here is how we can use it:
#include <iostream>
#include <Logger.h>
int main (int argc, char** argv)
{
Logger logger("log.txt");
std::out << "Output" << std::endl;
std::cerr << "Error" << std::endl;
std::clog << "Log" << std::end;
return 0;
}