language: C++11 (gcc-4.7.2)
date: 528 days 12 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* 
Cool! it was fun to try out this ideone.com online compiler! Great for testing code snippets.
 
Silly testing when fiddling with http://www.codeproject.com/KB/library/g2log.aspx
-- for early testing of bitset vs std::atomic --  */
 
#include <iostream>
#include <sstream>
#include <string>
#include <atomic>
#include <cassert>
 
#if !(defined(__PRETTY_FUNCTION__))
#define __PRETTY_FUNCTION__   __FUNCTION__
#endif
 
 
class LogMessage
{
  public:
    LogMessage(const std::string &file, const int line, const std::string& function, const std::string &level)
      : file_(file)
  , line_(line)
  , function_(function)
  , level_(level)
{}
 
    virtual ~LogMessage()
  {
    std::cout << stream_.str() << std::endl;
  }
  
 
    std::ostringstream& messageStream(){return stream_;}
 
  protected:
    const std::string file_;
    const int line_;
    const std::string function_;
    const std::string level_;
    std::ostringstream stream_;
    std::string log_entry_;
};
 
const int DEBUG = 0, INFO = 1, WARNING = 2, FATAL = 3;
namespace internal
{
  std::atomic<bool> g_log_level_status[4]; // DEBUG, INFO, WARNING, FATAL
}
 
void setLogLevel(int level, bool enabled)
{
  assert((level >= DEBUG) && (level <= FATAL));
  (internal::g_log_level_status[level]).store(enabled, std::memory_order_release);
 }
 
 
bool logLevel(int level)
{
  assert((level >= DEBUG) && (level <= FATAL));
  bool status = (internal::g_log_level_status[level]).load(std::memory_order_acquire);
  return status;
}
 
#define G2_LOG_INFO  LogMessage(__FILE__,__LINE__,__PRETTY_FUNCTION__, "INFO")
#define LOG(level) if(logLevel(level)) G2_LOG_##level.messageStream()
 
int main()
{
   setLogLevel(INFO, true);
   LOG(INFO)<< "TEST asf" << std::endl;
   setLogLevel(INFO, false);
   LOG(INFO) << "TEST asf 2 (should not be shown)" << std::endl;
   setLogLevel(INFO, true);
   LOG(INFO) << "TEST asf 3 (SHOULD be shown)" << std::endl;
 
return 0;
}