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 std::string& source, const std::string& msg)
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 = msg.length();
51  while(len != 0 && (msg[len-1] == '\n' || msg[len-1] == '\r'))
52  len--;
53 
54  fmt::print(m_file, "{}.{:03d}: {:>20}: ",
55  timeString, tv.tv_usec / 1000,
56  source.c_str()
57  );
58  fwrite(msg.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:29
Logger(const std::string &path, bool flush=false)
Constructor.
Definition: logger.cpp:19
void log(const std::string &source, const std::string &msg)
Log message.
Definition: logger.cpp:37
bool m_flush
Definition: logger.h:30


rosmon_core
Author(s): Max Schwarz
autogenerated on Wed Jul 10 2019 03:10:12