GGS(GenericGEANT4Simulation)Software  2.7.0
 All Data Structures Namespaces Files Functions Variables Typedefs Macros
GGSSmartLog.cpp
1 /*
2  * SmartLog.cpp
3  *
4  * Created on: 24 Nov 2014
5  * Author: Nicola Mori
6  */
7 
8 #include <fstream>
9 #include <utils/GGSSmartLog.h>
10 
11 namespace GGSSmartLog {
12 
13 const char *levelNames[6] = {"", "ERROR", "WARNING", "INFO", "DEBUG", "DEEPDEB"};
14 int verboseLevel = INFO;
15 int maxRoutineNameLength = 30;
16 
17 const std::string &Format(const std::string &str, unsigned int maxLength) {
18  static std::string returnStr;
19  returnStr = str;
20  if (returnStr.length() > maxLength) {
21  returnStr = returnStr.substr(0, maxLength - 3).append("...");
22  }
23  return returnStr;
24 }
25 
26 // Mute-unmute routines.
27 // From: https://bbs.archlinux.org/viewtopic.php?id=79378
28 // Modified to mute also C-style output.
29 
30 FILE *stdoutSave = NULL;
31 FILE *stderrSave = NULL;
32 
33 std::streambuf *cout_sbuf = NULL;
34 std::streambuf *cerr_sbuf = NULL;
35 
36 class FilesProxy {
37 public:
38  FilesProxy() : fout("/dev/null"), muteOut(fopen("/dev/null", "w")) {}
39  ~FilesProxy() {
40  fout.close();
41  fclose(muteOut);
42  }
43  std::ofstream fout;
44  FILE *muteOut;
45 };
46 
47 FilesProxy muteFiles;
48 
49 bool isMuted = false;
50 
51 void MuteOutput() {
52 
53  if (!isMuted) {
54  stdoutSave = stdout;
55  stdout = muteFiles.muteOut;
56  stderrSave = stderr;
57  stderr = muteFiles.muteOut;
58 
59  cout_sbuf = std::cout.rdbuf();
60  cerr_sbuf = std::cerr.rdbuf();
61  std::cout.rdbuf(muteFiles.fout.rdbuf());
62  std::cerr.rdbuf(muteFiles.fout.rdbuf());
63 
64  isMuted = true;
65  }
66 }
67 
68 void UnmuteOutput() {
69  if (stdoutSave) {
70  stdout = stdoutSave;
71  stdoutSave = NULL;
72  }
73  if (stderrSave) {
74  stderr = stderrSave;
75  stderrSave = NULL;
76  }
77 
78  if (cout_sbuf) {
79  std::cout.rdbuf(cout_sbuf);
80  cout_sbuf = NULL;
81  }
82  if (cerr_sbuf) {
83  std::cerr.rdbuf(cerr_sbuf);
84  cerr_sbuf = NULL;
85  }
86 
87  isMuted = false;
88 }
89 
90 } // namespace GGSSmartLog