logger.cpp
Go to the documentation of this file.
1 // Logs all output to a log file for the run
2 // Author: Max Schwarz <max.schwarz@uni-bonn.de>
3 
4 #include "logger.h"
5 
6 #include <cerrno>
7 #include <cstdio>
8 #include <cstring>
9 #include <ctime>
10 #include <stdexcept>
11 
12 #include <sys/time.h>
13 
14 #include <fmt/format.h>
15 
16 namespace rosmon
17 {
18 
19 Logger::Logger(const std::string& path, bool flush)
20  : m_flush(flush)
21 {
22  m_file = fopen(path.c_str(), "we");
23  if(!m_file)
24  {
25  throw std::runtime_error(fmt::format(
26  "Could not open log file: {}", strerror(errno)
27  ));
28  }
29 }
30 
32 {
33  if(m_file)
34  fclose(m_file);
35 }
36 
37 void Logger::log(const LogEvent& event)
38 {
39  struct timeval tv;
40  memset(&tv, 0, sizeof(tv));
41  gettimeofday(&tv, nullptr);
42 
43  struct tm btime;
44  memset(&btime, 0, sizeof(tv));
45  localtime_r(&tv.tv_sec, &btime);
46 
47  char timeString[100];
48  strftime(timeString, sizeof(timeString), "%a %F %T", &btime);
49 
50  unsigned int len = event.message.length();
51  while(len != 0 && (event.message[len-1] == '\n' || event.message[len-1] == '\r'))
52  len--;
53 
54  fmt::print(m_file, "{}.{:03d}: {:>20}: ",
55  timeString, tv.tv_usec / 1000,
56  event.source.c_str()
57  );
58  fwrite(event.message.c_str(), 1, len, m_file);
59  fputc('\n', m_file);
60 
61  if(m_flush)
62  fflush(m_file);
63 }
64 
65 }
FILE * m_file
Definition: logger.h:31
Logger(const std::string &path, bool flush=false)
Constructor.
Definition: logger.cpp:19
void log(const LogEvent &event)
Log message.
Definition: logger.cpp:37
bool m_flush
Definition: logger.h:32
std::string source
Definition: log_event.h:38
std::string message
Definition: log_event.h:39


rosmon_core
Author(s): Max Schwarz
autogenerated on Sat Jan 9 2021 03:35:43