Click here to Skip to main content
13,868,554 members
Click here to Skip to main content
Add your own
alternative version


3 bookmarked
Posted 20 Jun 2016
Licenced CPOL

Redirecting std::clog to Test Framework Output

, 20 Jun 2016
Rate this:
Please Sign up or sign in to vote.
Wrap writing to the test logger with std::streambuf then substitute in std::clog


You may have code that usually writes to std::cout, etc. but is lost in when using a test framework. This tip extracts some code from my article on using Gherkin DSL to show how a test frameworks' logging function can be wrapped and substituted into std::clog, std::cout, etc. to enhance the test log.

The Wrapper

The content of LogStream.h is a class containing a buffer and two overloaded functions:

#pragma once

#include "stdafx.h"
#include "CppUnitTest.h"

#include <vector>

namespace TestUtils
    class LogStream : public std::streambuf
        std::vector<char> buffer;

        int_type overflow(int_type ch)
            if (ch != traits_type::eof())
            return ch;

        int sync()
            if (buffer.back() == '\n')
            return 0;


// Initialise then swap
newBuffer = std::make_shared<TestUtils::LogStream>();
oldBuffer = std::clog.rdbuf(newBuffer.get());
std::clog << "Entering Tests" << std::endl;

// Run the tests
// ...

// Swap and free
std::clog << "Exiting Tests" << std::endl;
newBuffer = nullptr;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Zebedee Mason
United Kingdom United Kingdom
Mathematician turned freelance Software Engineer with over 20 years experience, mainly in the development of CAD/CAM/CAE software. Generally worked for smaller businesses - although have been at Lloyd's Register, Siemens and Rolls-Royce. Enjoy living on the edge of the Peak District where I go cycling and hiking.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190214.1 | Last Updated 20 Jun 2016
Article Copyright 2016 by Zebedee Mason
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid