GGS(GenericGEANT4Simulation)Software  2.6.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 <utils/GGSSmartLog.h>
9 #include <fstream>
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() :
39  fout("/dev/null"), muteOut(fopen("/dev/null", "w")) {
40  }
41  ~FilesProxy() {
42  fout.close();
43  fclose(muteOut);
44  }
45  std::ofstream fout;
46  FILE* muteOut;
47 };
48 
49 FilesProxy muteFiles;
50 
51 bool isMuted = false;
52 
53 void MuteOutput() {
54 
55  if (!isMuted) {
56  stdoutSave = stdout;
57  stdout = muteFiles.muteOut;
58  stderrSave = stderr;
59  stderr = muteFiles.muteOut;
60 
61  cout_sbuf = std::cout.rdbuf();
62  cerr_sbuf = std::cerr.rdbuf();
63  std::cout.rdbuf(muteFiles.fout.rdbuf());
64  std::cerr.rdbuf(muteFiles.fout.rdbuf());
65 
66  isMuted = true;
67  }
68 }
69 
70 void UnmuteOutput() {
71  if (stdoutSave) {
72  stdout = stdoutSave;
73  stdoutSave = NULL;
74  }
75  if (stderrSave) {
76  stderr = stderrSave;
77  stderrSave = NULL;
78  }
79 
80  if (cout_sbuf) {
81  std::cout.rdbuf(cout_sbuf);
82  cout_sbuf = NULL;
83  }
84  if (cerr_sbuf) {
85  std::cerr.rdbuf(cerr_sbuf);
86  cerr_sbuf = NULL;
87  }
88 
89  isMuted = false;
90 
91 
92 }
93 
94 }
95