Skip to content

Instantly share code, notes, and snippets.

@weigert
Created November 21, 2020 13:11
Show Gist options
  • Save weigert/95e28463d627a7e185bead4842de9890 to your computer and use it in GitHub Desktop.
Save weigert/95e28463d627a7e185bead4842de9890 to your computer and use it in GitHub Desktop.
Simple Templated Recursive Logging Helper
/*===============================================
Logging Helper
Author: Nicholas McDonald
Features:
- Templated Recursive Value Outputs
- Simplified Log File Writing
- Arbitrary Pre-Message Blurbs
- Elegant One-Line Failures / Errors
If a file is opened, all output is directed to the file.
===============================================*/
#include <cstdarg>
#include <string>
#include <iostream>
namespace logg{
using namespace std;
bool debug = true;
function<string()> blurb = [](){ return ""; };
ostream* target = &cout;
ofstream* file = NULL;
/*=============================
Raw Recursion
=============================*/
void raw(){
if(file == NULL) *target<<endl;
else *file<<endl;
}
template <typename T>
void raw(T m){
if(file == NULL) *target<<m<<endl;
else *file<<m<<endl;
}
template <typename T, typename... Types>
void raw(T m, Types... r){
if(file == NULL){ *target<<m; raw( r... ); }
else { *file<<m; raw( r... ); }
}
/*=============================
Regular Output
=============================*/
template <typename... Types>
void out(Types... r){ raw( blurb(), r... ); }
/*=============================
Debugging Messages
=============================*/
template <typename... Types>
void dbg(Types... r){ if(debug) raw( r... ); }
template <typename... Types>
void dbg(bool f, Types... r){ if(f) raw( r... ); }
/*=============================
Errors and Failures
=============================*/
template <typename... Types>
void err(Types... r){ raw( "[Error] ", r... ); }
template <typename... Types>
void fatal(Types... r){ raw( "[Fatal] ", r... ); exit(0); }
/*=============================
Write to File
=============================*/
void close(){
if(file != NULL)
file->close();
file = NULL;
}
void open(string name){
close();
file->open(name, ios::app);
if(!file->is_open())
fatal("Failed to open file ", name);
}
/*=============================
Special Displays
=============================*/
template <typename T>
void progress(T d, T D){
if(d != 0) cout<<"\r";
cout<<"["<<d<<"/"<<D<<"]";
for(int i = 0; i < 25; i++){
if(i < 25*((float)d/(float)D)) cout<<"#";
else cout<<"-";
}
cout<<"]";
if(d == D-1) printf("\n");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment