OpenXcom  1.0
Open-source clone of the original X-Com
Logger.h
1 #pragma once
2 /*
3  * Copyright 2010-2016 OpenXcom Developers.
4  *
5  * This file is part of OpenXcom.
6  *
7  * OpenXcom is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * OpenXcom is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with OpenXcom. If not, see <http://www.gnu.org/licenses/>.
19  */
20 #ifdef _MSC_VER
21 #define _CRT_SECURE_NO_WARNINGS
22 #endif
23 #include <sstream>
24 #include <string>
25 #include <stdio.h>
26 #include "CrossPlatform.h"
27 
28 namespace OpenXcom
29 {
30 
35 enum SeverityLevel
36 {
37  LOG_FATAL,
38  LOG_ERROR,
39  LOG_WARNING,
40  LOG_INFO,
41  LOG_DEBUG,
42  LOG_VERBOSE
43 };
44 
50 class Logger
51 {
52 public:
53  Logger();
54  virtual ~Logger();
55  std::ostringstream& get(SeverityLevel level = LOG_INFO);
56 
57  static SeverityLevel& reportingLevel();
58  static std::string& logFile();
59  static std::string toString(SeverityLevel level);
60 protected:
61  std::ostringstream os;
62 private:
63  Logger(const Logger&);
64 };
65 
66 inline Logger::Logger()
67 {
68 }
69 
70 inline std::ostringstream& Logger::get(SeverityLevel level)
71 {
72  os << "[" << toString(level) << "]" << "\t";
73  return os;
74 }
75 
76 inline Logger::~Logger()
77 {
78  os << std::endl;
79  std::ostringstream ss;
80  ss << "[" << CrossPlatform::now() << "]" << "\t" << os.str();
81  FILE *file = fopen(logFile().c_str(), "a");
82  if (file)
83  {
84  fprintf(file, "%s", ss.str().c_str());
85  fflush(file);
86  fclose(file);
87  }
88  if (!file || reportingLevel() == LOG_DEBUG || reportingLevel() == LOG_VERBOSE)
89  {
90  fprintf(stderr, "%s", os.str().c_str());
91  fflush(stderr);
92  }
93 }
94 
95 inline SeverityLevel& Logger::reportingLevel()
96 {
97  static SeverityLevel reportingLevel = LOG_DEBUG;
98  return reportingLevel;
99 }
100 
101 inline std::string& Logger::logFile()
102 {
103  static std::string logFile = "openxcom.log";
104  return logFile;
105 }
106 
107 inline std::string Logger::toString(SeverityLevel level)
108 {
109  static const char* const buffer[] = {"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "VERB"};
110  return buffer[level];
111 }
112 
113 #define Log(level) \
114  if (level > Logger::reportingLevel()) ; \
115  else Logger().get(level)
116 
117 }
A basic logging and debugging class, prints output to stdout/files.
Definition: Logger.h:50
std::string now()
Generates a timestamp of the current time.
Definition: CrossPlatform.cpp:1062
Definition: BaseInfoState.cpp:40