CodeCompass

Форк
0
/
logutil.cpp 
146 строк · 3.6 Кб
1
#include <util/logutil.h>
2

3
#include <boost/filesystem.hpp>
4
#include <boost/log/utility/setup.hpp>
5
#include <boost/log/expressions.hpp>
6
#include <boost/log/attributes.hpp>
7
#include <boost/date_time/posix_time/posix_time.hpp>
8

9
namespace fs = boost::filesystem;
10

11
namespace cc
12
{
13
namespace util
14
{
15

16
namespace
17
{
18

19
BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime)
20

21
std::string getFormattedTime(boost::posix_time::ptime ptime_)
22
{
23
  std::stringstream stream;
24
  boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
25
  facet->format("%Y-%m-%d %H:%M:%S");
26
  stream.imbue(std::locale(std::locale::classic(), facet));
27

28
  stream << ptime_;
29

30
  return stream.str();
31
}
32

33
void consoleLogFormatter(
34
  const boost::log::record_view& rec, boost::log::formatting_ostream& strm)
35
{
36
  auto severity = rec[boost::log::trivial::severity];
37

38
  if (severity)
39
  {
40
    // Set the color
41
    switch (severity.get())
42
    {
43
      case boost::log::trivial::debug:
44
        strm << "\033[32m";
45
        break;
46
      case boost::log::trivial::warning:
47
        strm << "\033[33m";
48
        break;
49
      case boost::log::trivial::error:
50
      case boost::log::trivial::fatal:
51
        strm << "\033[31m";
52
        break;
53
      default:
54
        break;
55
    }
56
  }
57

58
  std::string sLevel = boost::log::trivial::to_string(severity.get());
59
  std::transform(sLevel.begin(), sLevel.end(), sLevel.begin(), ::toupper);
60

61
  std::string timeString = getFormattedTime(rec[timestamp].get());
62

63
  strm << timeString << " [" << sLevel << "] " << rec[boost::log::expressions::smessage];
64

65
  // Restore the default color
66
  if (severity)
67
  {
68
    strm << "\033[0m";
69
  }
70
}
71

72
void fileLogFormatter(
73
  const boost::log::record_view& rec, boost::log::formatting_ostream& strm)
74
{
75
  auto severity = rec[boost::log::trivial::severity];
76

77
  std::string sLevel = boost::log::trivial::to_string(severity.get());
78
  std::transform(sLevel.begin(), sLevel.end(), sLevel.begin(), ::toupper);
79

80
  std::string timeString = getFormattedTime(rec[timestamp].get());
81

82
  strm << timeString << " [" << sLevel << "] " << rec[boost::log::expressions::smessage];
83
}
84

85
} // namespace
86

87
boost::log::trivial::severity_level getSeverityLevel()
88
{
89
 return boost::log::attribute_cast<
90
   boost::log::attributes::mutable_constant<boost::log::trivial::severity_level>>(
91
     boost::log::core::get()->get_global_attributes()["Severity"]).get();
92
}
93

94
void initConsoleLogger()
95
{
96
  boost::log::add_common_attributes();
97
  auto fsSink = boost::log::add_console_log(
98
    std::cout,
99
    boost::log::keywords::auto_flush = true);
100

101
  fsSink->set_formatter(&consoleLogFormatter);
102
}
103

104
std::string getLoggingBase(const std::string& path_, const std::string& name_)
105
{
106
  if (path_.find('~') != std::string::npos)
107
  {
108
    throw std::invalid_argument("The path should not contain a \'~\' character. \
109
                                 Please provide an absolute path");
110
  }
111

112
  boost::system::error_code ec;
113
  fs::create_directory(path_, ec);
114
  if (ec)
115
  {
116
    throw std::invalid_argument("Permission denied to create " + path_);
117
  }
118

119
  const std::string fullpath = canonical(absolute(fs::path(path_))).string();
120

121
  return fullpath + (fullpath.back() == '/' ? "" : "/") + name_ + '_';
122
}
123

124
bool initFileLogger(const std::string& path_)
125
{
126
  auto fsSink = boost::log::add_file_log(
127
    boost::log::keywords::file_name = path_,
128
    boost::log::keywords::auto_flush = true
129
    );
130
  fsSink->set_formatter(&fileLogFormatter);
131
  try
132
  {
133
    // check if logging to file is possible
134
    LOG(info) << "Start logging in file: " << path_;
135
  }
136
  catch(...)
137
  {
138
    boost::log::core::get()->remove_sink(fsSink);
139
    LOG(warning) << "Could not open file for logging: " << path_;
140
    return false;
141
  }
142
  return true;
143
}
144

145
} // util
146
} // cc
147

148

149

150

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.