comlog_sink.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  2. //
  3. // Redirect LOG() into comlog.
  4. //
  5. // Author: Ge,Jun (gejun@baidu.com)
  6. // Date: Mon Jul 20 12:39:39 CST 2015
  7. #include <com_log.h>
  8. #include "base/memory/singleton.h"
  9. #include "base/comlog_sink.h"
  10. #include "base/files/file_path.h"
  11. #include "base/fd_guard.h"
  12. #include "base/file_util.h"
  13. #include "base/endpoint.h"
  14. namespace logging {
  15. DECLARE_bool(log_year);
  16. DECLARE_bool(log_hostname);
  17. struct ComlogLayoutOptions {
  18. ComlogLayoutOptions() : shorter_log_level(true) {}
  19. bool shorter_log_level;
  20. };
  21. class ComlogLayout : public comspace::Layout {
  22. public:
  23. explicit ComlogLayout(const ComlogLayoutOptions* options);
  24. ~ComlogLayout();
  25. int format(comspace::Event *evt);
  26. private:
  27. ComlogLayoutOptions _options;
  28. };
  29. ComlogLayout::ComlogLayout(const ComlogLayoutOptions* options) {
  30. if (options) {
  31. _options = *options;
  32. }
  33. }
  34. ComlogLayout::~ComlogLayout() {
  35. }
  36. // Override Layout::format to have shorter prefixes. Patterns are just ignored.
  37. int ComlogLayout::format(comspace::Event *evt) {
  38. const int bufsize = evt->_render_msgbuf_size;
  39. char* const buf = evt->_render_msgbuf;
  40. if (bufsize < 2){
  41. return -1;
  42. }
  43. time_t t = evt->_print_time.tv_sec;
  44. struct tm local_tm = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
  45. #if _MSC_VER >= 1400
  46. localtime_s(&local_tm, &t);
  47. #else
  48. localtime_r(&t, &local_tm);
  49. #endif
  50. int len = 0;
  51. if (_options.shorter_log_level) {
  52. buf[len++] = *comspace::getLogName(evt->_log_level);
  53. } else {
  54. const char* const name = comspace::getLogName(evt->_log_level);
  55. int cp_len = std::min(bufsize - len, (int)strlen(name));
  56. memcpy(buf + len, name, cp_len);
  57. len += cp_len;
  58. if (len < bufsize - 1) {
  59. buf[len++] = ' ';
  60. }
  61. }
  62. if (len < bufsize - 1) {
  63. int ret = 0;
  64. if (FLAGS_log_year) {
  65. ret = snprintf(buf + len, bufsize - len,
  66. "%04d%02d%02d %02d:%02d:%02d.%06d %5u ",
  67. local_tm.tm_year + 1900,
  68. local_tm.tm_mon + 1,
  69. local_tm.tm_mday,
  70. local_tm.tm_hour,
  71. local_tm.tm_min,
  72. local_tm.tm_sec,
  73. (int)evt->_print_time.tv_usec,
  74. (unsigned int)evt->_thread_id);
  75. } else {
  76. ret = snprintf(buf + len, bufsize - len,
  77. "%02d%02d %02d:%02d:%02d.%06d %5u ",
  78. local_tm.tm_mon + 1,
  79. local_tm.tm_mday,
  80. local_tm.tm_hour,
  81. local_tm.tm_min,
  82. local_tm.tm_sec,
  83. (int)evt->_print_time.tv_usec,
  84. (unsigned int)evt->_thread_id);
  85. }
  86. if (ret >= 0) {
  87. len += ret;
  88. } else {
  89. // older glibc may return negative which means the buffer is full.
  90. len = bufsize;
  91. }
  92. }
  93. if (len > 0 && len < bufsize - 1) { // not truncated.
  94. // Although it's very stupid, we have to copy the message again due
  95. // to the design of comlog.
  96. int cp_len = std::min(bufsize - len, evt->_msgbuf_len);
  97. memcpy(buf + len, evt->_msgbuf, cp_len);
  98. len += cp_len;
  99. }
  100. if (len >= bufsize - 1) {
  101. len = bufsize - 2;
  102. }
  103. buf[len++] = '\n';
  104. buf[len] = 0;
  105. evt->_render_msgbuf_len = len;
  106. return 0;
  107. }
  108. ComlogSink* ComlogSink::GetInstance() {
  109. return Singleton<ComlogSink, LeakySingletonTraits<ComlogSink> >::get();
  110. }
  111. ComlogSinkOptions::ComlogSinkOptions()
  112. : async(false)
  113. , shorter_log_level(true)
  114. , log_dir("log")
  115. , max_log_length(2048)
  116. , print_vlog_as_warning(true)
  117. , split_type(COMLOG_SPLIT_TRUNCT)
  118. , cut_size_megabytes(2048)
  119. , quota_size(0)
  120. , cut_interval_minutes(60)
  121. , quota_day(0)
  122. , quota_hour(0)
  123. , quota_min(0)
  124. , enable_wf_device(false) {
  125. }
  126. ComlogSink::ComlogSink()
  127. : _init(false), _dev(NULL) {
  128. }
  129. int ComlogSink::SetupFromConfig(const std::string& conf_path_str) {
  130. Unload();
  131. base::FilePath path(conf_path_str);
  132. if (com_loadlog(path.DirName().value().c_str(),
  133. path.BaseName().value().c_str()) != 0) {
  134. LOG(ERROR) << "Fail to create ComlogSink from `" << conf_path_str << "'";
  135. return -1;
  136. }
  137. _init = true;
  138. return 0;
  139. }
  140. // This is definitely linux specific.
  141. static std::string GetProcessName() {
  142. base::fd_guard fd(open("/proc/self/cmdline", O_RDONLY));
  143. if (fd < 0) {
  144. return "unknown";
  145. }
  146. char buf[512];
  147. const ssize_t len = read(fd, buf, sizeof(buf) - 1);
  148. if (len <= 0) {
  149. return "unknown";
  150. }
  151. buf[len] = '\0';
  152. // Not string(buf, len) because we needs to buf to be truncated at first \0.
  153. // Under gdb, the first part of cmdline may include path.
  154. return base::FilePath(std::string(buf)).BaseName().value();
  155. }
  156. int ComlogSink::SetupDevice(com_device_t* dev, const char* type, const char* file, bool is_wf) {
  157. base::FilePath path(file);
  158. snprintf(dev->host, sizeof(dev->host), "%s", path.DirName().value().c_str());
  159. if (!is_wf) {
  160. snprintf(dev->name, sizeof(dev->name), "%s_0", type);
  161. COMLOG_SETSYSLOG(*dev);
  162. //snprintf(dev->file, COM_MAXFILENAME, "%s", file);
  163. snprintf(dev->file, sizeof(dev->file), "%s", path.BaseName().value().c_str());
  164. } else {
  165. snprintf(dev->name, sizeof(dev->name), "%s_1", type);
  166. dev->log_mask = 0;
  167. COMLOG_ADDMASK(*dev, COMLOG_WARNING);
  168. COMLOG_ADDMASK(*dev, COMLOG_FATAL);
  169. //snprintf(dev->file, COM_MAXFILENAME, "%s.wf", file);
  170. snprintf(dev->file, sizeof(dev->file), "%s.wf", path.BaseName().value().c_str());
  171. }
  172. snprintf(dev->type, COM_MAXAPPENDERNAME, "%s", type);
  173. dev->splite_type = static_cast<int>(_options.split_type);
  174. dev->log_size = _options.cut_size_megabytes; // SIZECUT precision in MB
  175. dev->compress = 0;
  176. dev->cuttime = _options.cut_interval_minutes; // DATECUT time precision in min
  177. // set quota conf
  178. int index = dev->reserved_num;
  179. if (dev->splite_type == COMLOG_SPLIT_SIZECUT) {
  180. if (_options.cut_size_megabytes <= 0) {
  181. LOG(ERROR) << "Invalid ComlogSinkOptions.cut_size_megabytes="
  182. << _options.cut_size_megabytes;
  183. return -1;
  184. }
  185. if (_options.quota_size < 0) {
  186. LOG(ERROR) << "Invalid ComlogSinkOptions.quota_size="
  187. << _options.quota_size;
  188. return -1;
  189. }
  190. snprintf(dev->reservedext[index].name, sizeof(dev->reservedext[index].name),
  191. "%s_QUOTA_SIZE", dev->name);
  192. snprintf(dev->reservedext[index].value, sizeof(dev->reservedext[index].value),
  193. "%d", _options.quota_size);
  194. index++;
  195. } else if (dev->splite_type == COMLOG_SPLIT_DATECUT) {
  196. if (_options.quota_day < 0) {
  197. LOG(ERROR) << "Invalid ComlogSinkOptions.quota_day=" << _options.quota_day;
  198. return -1;
  199. }
  200. if (_options.quota_hour < 0) {
  201. LOG(ERROR) << "Invalid ComlogSinkOptions.quota_hour=" << _options.quota_hour;
  202. return -1;
  203. }
  204. if (_options.quota_min < 0) {
  205. LOG(ERROR) << "Invalid ComlogSinkOptions.quota_min=" << _options.quota_min;
  206. return -1;
  207. }
  208. if (_options.quota_day > 0) {
  209. snprintf(dev->reservedext[index].name, sizeof(dev->reservedext[index].name),
  210. "%s_QUOTA_DAY", (char*)dev->name);
  211. snprintf(dev->reservedext[index].value, sizeof(dev->reservedext[index].value),
  212. "%d", _options.quota_day);
  213. index++;
  214. }
  215. if (_options.quota_hour > 0) {
  216. snprintf(dev->reservedext[index].name, sizeof(dev->reservedext[index].name),
  217. "%s_QUOTA_HOUR", (char*)dev->name);
  218. snprintf(dev->reservedext[index].value, sizeof(dev->reservedext[index].value),
  219. "%d", _options.quota_hour);
  220. index++;
  221. }
  222. if (_options.quota_min > 0) {
  223. snprintf(dev->reservedext[index].name, sizeof(dev->reservedext[index].name),
  224. "%s_QUOTA_MIN", (char*)dev->name);
  225. snprintf(dev->reservedext[index].value, sizeof(dev->reservedext[index].value),
  226. "%d", _options.quota_min);
  227. index++;
  228. }
  229. }
  230. dev->reserved_num = index;
  231. dev->reservedconf.item = &dev->reservedext[0];
  232. dev->reservedconf.num = dev->reserved_num;
  233. dev->reservedconf.size = dev->reserved_num;
  234. ComlogLayoutOptions layout_options;
  235. layout_options.shorter_log_level = _options.shorter_log_level;
  236. ComlogLayout* layout = new (std::nothrow) ComlogLayout(&layout_options);
  237. if (layout == NULL) {
  238. LOG(FATAL) << "Fail to new layout";
  239. return -1;
  240. }
  241. dev->layout = layout;
  242. return 0;
  243. }
  244. int ComlogSink::Setup(const ComlogSinkOptions* options) {
  245. Unload();
  246. if (options) {
  247. _options = *options;
  248. }
  249. if (_options.max_log_length > 0) {
  250. comspace::Event::setMaxLogLength(_options.max_log_length);
  251. }
  252. if (_options.process_name.empty()) {
  253. _options.process_name = GetProcessName();
  254. }
  255. char type[COM_MAXAPPENDERNAME];
  256. if (_options.async) {
  257. snprintf(type, COM_MAXAPPENDERNAME, "AFILE");
  258. } else {
  259. snprintf(type, COM_MAXAPPENDERNAME, "FILE");
  260. }
  261. base::FilePath cwd;
  262. if (!_options.log_dir.empty()) {
  263. base::FilePath log_dir(_options.log_dir);
  264. if (log_dir.IsAbsolute()) {
  265. cwd = log_dir;
  266. } else {
  267. if (!base::GetCurrentDirectory(&cwd)) {
  268. LOG(ERROR) << "Fail to get cwd";
  269. return -1;
  270. }
  271. cwd = cwd.Append(log_dir);
  272. }
  273. } else {
  274. if (!base::GetCurrentDirectory(&cwd)) {
  275. LOG(ERROR) << "Fail to get cwd";
  276. return -1;
  277. }
  278. }
  279. base::File::Error err;
  280. if (!base::CreateDirectoryAndGetError(cwd, &err)) {
  281. LOG(ERROR) << "Fail to create directory, " << err;
  282. return -1;
  283. }
  284. char file[COM_MAXFILENAME];
  285. snprintf(file, COM_MAXFILENAME, "%s",
  286. cwd.Append(_options.process_name + ".log").value().c_str());
  287. int dev_num = (_options.enable_wf_device ? 2 : 1);
  288. _dev = new (std::nothrow) com_device_t[dev_num];
  289. if (NULL == _dev) {
  290. LOG(FATAL) << "Fail to new com_device_t";
  291. return -1;
  292. }
  293. if (0 != SetupDevice(&_dev[0], type, file, false)) {
  294. LOG(ERROR) << "Fail to setup first com_device_t";
  295. return -1;
  296. }
  297. if (dev_num == 2) {
  298. if (0 != SetupDevice(&_dev[1], type, file, true)) {
  299. LOG(ERROR) << "Fail to setup second com_device_t";
  300. return -1;
  301. }
  302. }
  303. if (com_openlog(_options.process_name.c_str(), _dev, dev_num, NULL) != 0) {
  304. LOG(ERROR) << "Fail to com_openlog";
  305. return -1;
  306. }
  307. _init = true;
  308. return 0;
  309. }
  310. void ComlogSink::Unload() {
  311. if (_init) {
  312. com_closelog(0);
  313. _init = false;
  314. }
  315. if (_dev) {
  316. // FIXME(gejun): Can't delete layout, somewhere in comlog may still
  317. // reference the layout after com_closelog.
  318. //delete _dev->layout;
  319. delete [] _dev;
  320. _dev = NULL;
  321. }
  322. }
  323. ComlogSink::~ComlogSink() {
  324. Unload();
  325. }
  326. int const comlog_levels[LOG_NUM_SEVERITIES] = {
  327. COMLOG_TRACE, COMLOG_NOTICE, COMLOG_WARNING, COMLOG_FATAL, COMLOG_FATAL };
  328. bool ComlogSink::OnLogMessage(int severity, const char* file, int line,
  329. const base::StringPiece& content) {
  330. // Print warning for VLOG since many online servers do not enable COMLOG_TRACE.
  331. int comlog_level = 0;
  332. if (severity < 0) {
  333. comlog_level = _options.print_vlog_as_warning ? COMLOG_WARNING : COMLOG_TRACE;
  334. } else {
  335. comlog_level = comlog_levels[severity];
  336. }
  337. if (FLAGS_log_hostname) {
  338. base::StringPiece hostname(base::my_hostname());
  339. if (hostname.ends_with(".baidu.com")) { // make it shorter
  340. hostname.remove_suffix(10);
  341. }
  342. return com_writelog(comlog_level, "%.*s %s:%d] %.*s",
  343. (int)hostname.size(), hostname.data(),
  344. file, line,
  345. (int)content.size(), content.data()) == 0;
  346. }
  347. // Using %.*s is faster than %s.
  348. return com_writelog(comlog_level, "%s:%d] %.*s", file, line,
  349. (int)content.size(), content.data()) == 0;
  350. }
  351. } // namespace logging