PPL Assignment
IRM2015006
logger.cpp
Go to the documentation of this file.
1 #include <stdexcept>
2 #include <iostream>
3 
4 #ifndef LOGGER_H
5 #include "logger.h"
6 #endif
7 
8 Logger::Logger(const std::string filename)
9 {
10  if (this->file.is_open())
11  this->file.close();
12  this->file.open(filename.c_str(), std::ios::out | std::ios::app);
13  if (this->file.fail()) {
14  throw std::runtime_error ("Failed to open log file.\n");
15  }
16 }
17 
18 void Logger::info(const std::string msg, bool print)
19 {
20  this->file << msg << std::endl;
21 
22  if (print) {
23  std::cout << msg << std::endl;
24  }
25 }
26 
27 void Logger::log(const std::string type, const std::string msg, bool print)
28 {
29  time(&rawtime);
30  this->tmpstr = ctime(&rawtime);
31  this->tmpstr[this->tmpstr.size() - 1] = '\0';
32  this->file << this->tmpstr << " | ";
33  this->file.width(10);
34  this->file << std::left << type << " -- ";
35  this->file.width(0);
36  this->file << msg << std::endl;
37 
38  if (print) {
39  std::cout << this->tmpstr << " | ";
40  std::cout << type << " -- " << msg << std::endl;
41  }
42 }
43 
45 {
46  if (this->file.is_open())
47  this->file.close();
48 }
void info(const std::string msg, bool print=false)
Definition: logger.cpp:18
~Logger()
Definition: logger.cpp:44
void log(const std::string type, const std::string msg, bool print=false)
Definition: logger.cpp:27
time_t rawtime
Definition: logger.h:11
std::string tmpstr
Definition: logger.h:12
std::fstream file
Definition: logger.h:13
Logger(const std::string filename)
Definition: logger.cpp:8