Blame view

src/log.cpp 1.59 KB
25b0d2f8   Peter M. Groen   Setting up Loggin...
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
  #include "log.h"
  
  // std
  
  
  
  using namespace osdev::components::mqtt;
  
  namespace {
  
  std::string toString( LogLevel level )
  {
      switch (level)
      {
          case LogLevel::Trace:
              return "T";
          case LogLevel::Debug:
              return "D";
          case LogLevel::Info:
              return "I";
          case LogLevel::Warning:
              return "W";
          case LogLevel::Error:
              return "E";
      }
      return "U";
  }
  
  } // namespace
  
  const std::string Log::s_startMarker = std::string("|________________________________________________________________________________________________________________________________|");
  std::string Log::s_context = std::string();
  std::string Log::s_fileName = std::string();
  LogLevel Log::s_logLevel = LogLevel::Info;
  
  void Log::init( const std::string &context, const std::string &logFile, LogLevel logDepth )
  {
      s_logLevel = logDepth;
      s_context = context;
  
      if( !logFile.empty())
      {
          s_fileName = logFile;
      }
  }
  
  void Log::terminate()
  {
      s_context.clear();
      s_fileName.clear();
      s_logLevel = LogLevel::Info;
  }
  
  void Log::log( const std::string &category, const std::string &message, LogLevel level )
  {
      std::string logCategory = s_context + '|' + toString( level ) + '|' + ThreadContext::instance().context() + '|' + category;
      std::string logMessage = message;
      if( logMessage.empty() )
      {
          static const std::string emptyMessage( "--" );
          logMessage = emptyMessage;
      }
      else
      {
          // Replace % signs
          logMessage.replace( '%', "%%");
      }
  
      writeLog( logCategory, logMessage, level );
  }