WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
Log.hpp
1 #pragma once
2 
3 #include <sstream>
4 #include <iomanip>
5 #include <string>
6 #include <stdio.h>
7 #ifdef _WIN32
8  #include <Windows.h>
9 #else
10  #include <sys/time.h>
11 #endif
12 
13 inline std::string NowTime();
14 
15 enum TLogLevel {logNONE, logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4};
16 
17 class Log
18 {
19 public:
20  Log();
21  virtual ~Log();
22  std::ostringstream& Get(TLogLevel level = logINFO);
23 public:
24  static TLogLevel& ReportingLevel();
25  static std::string ToString(TLogLevel level);
26  static TLogLevel FromString(const std::string& level);
27 protected:
28  std::ostringstream os;
29 private:
30  Log(const Log&);
31  Log& operator =(const Log&);
32 };
33 
34 inline Log::Log()
35 {
36 }
37 
38 inline std::ostringstream& Log::Get(TLogLevel level)
39 {
40  os << "- " << NowTime();
41  os << " " << ToString(level) << ": ";
42  os << std::string(level > logDEBUG ? level - logDEBUG : 0, '\t');
43  return os;
44 }
45 
46 inline Log::~Log()
47 {
48  os << std::endl;
49  fprintf(stderr, "%s", os.str().c_str());
50  fflush(stderr);
51 }
52 
53 inline TLogLevel& Log::ReportingLevel()
54 {
55  static TLogLevel reportingLevel = logDEBUG4;
56  return reportingLevel;
57 }
58 
59 inline std::string Log::ToString(TLogLevel level)
60 {
61  static const char* const buffer[] = {"NONE", "ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4"};
62  return buffer[level];
63 }
64 
65 inline TLogLevel Log::FromString(const std::string& level)
66 {
67  if (level == "DEBUG4")
68  return logDEBUG4;
69  if (level == "DEBUG3")
70  return logDEBUG3;
71  if (level == "DEBUG2")
72  return logDEBUG2;
73  if (level == "DEBUG1")
74  return logDEBUG1;
75  if (level == "DEBUG")
76  return logDEBUG;
77  if (level == "INFO")
78  return logINFO;
79  if (level == "WARNING")
80  return logWARNING;
81  if (level == "ERROR")
82  return logERROR;
83  if (level == "NONE")
84  return logNONE;
85  Log().Get(logWARNING) << "Unknown logging level '" << level << "'. Using INFO level as default.";
86  return logINFO;
87 }
88 
89 typedef Log FILELog;
90 
91 #define FILE_LOG(level) \
92  if (level > FILELog::ReportingLevel()) ; \
93  else Log().Get(level)
94 
95 
96 #ifdef _WIN32
97 inline std::string NowTime()
98 {
99  SYSTEMTIME st;
100  GetLocalTime(&st);
101  char result[100] = {0};
102  sprintf(result, "%d:%d:%d.%d", st.wHour , st.wMinute , st.wSecond , st.wMilliseconds);
103  return result;
104 }
105 #else
106 inline std::string NowTime()
107 {
108  char buffer[11];
109  time_t t;
110  time(&t);
111  tm * r = gmtime(&t);
112  strftime(buffer, sizeof(buffer), "%H:%M:%S", r);
113  struct timeval tv;
114  gettimeofday(&tv, 0);
115  char result[100] = {0};
116  sprintf(result, "%s.%03ld", buffer, (long)tv.tv_usec / 1000);
117  return result;
118 }
119 #endif
Definition: Log.hpp:17