Skip to content

Instantly share code, notes, and snippets.

@vishal-keshav
Created February 25, 2019 06:26
Show Gist options
  • Save vishal-keshav/b5091dd5566fe3a68488a21b3c6651f5 to your computer and use it in GitHub Desktop.
Save vishal-keshav/b5091dd5566fe3a68488a21b3c6651f5 to your computer and use it in GitHub Desktop.
A better way to log in C++

Logging in C++

When writing a high performance C++ program, sometimes it become crucial to log what is happening while program execution is in progress. There are several logging libraries like glog (from Google) and log(from Boost), but using those for a simple program can be counter productive as it unneccesarily increases the executable size and takes more time to setup.

I use the below 5 lines code snippet to log in C++ program. Variadic templates are being used to create such a minimilistic logging system.

template <typename T>
void log_it(T t) {
    cout << t << endl;
}
template <typename T>
void log_it(vector<T> vec){
    for(int i=0;i<vec.size();i++){
        cout << vec[i] << " ";
    }
    cout << endl;
}
template<typename T, typename... Args>
void log_it(T t, Args... args){
    cout << t << " ";
    log_it(args...);
}

Just like log_it overloads vector of template type, in addition, any other data structure (like maps) can be overloaded

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment