summaryrefslogtreecommitdiff
path: root/src/Log.hpp
blob: abb3639b6cc31232f1b0f17f4b3a9a331de66c12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; coding: utf-8-unix -*-
// ***** BEGIN LICENSE BLOCK *****
//////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2014 RALOVICH, Kristóf                            //
//                                                                      //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 3 of the License, or    //
// (at your option) any later version.                                  //
//                                                                      //
// This program is distributed in the hope that it will be useful,      //
// but WITHOUT ANY WARRANTY; without even the implied warranty of       //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        //
// GNU General Public License for more details.                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
// ***** END LICENSE BLOCK *****

#pragma once

#include "LazySingleton.hpp"
#include <cstdarg>
#include <fstream>
#include <list>
#include <memory>
#include <ostream>
#include <sstream>
#ifdef _MSC_VER
# include <crtdbg.h>
# include <io.h>
#endif
#if defined(__linux__) || defined(__GNU__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
# include <unistd.h>
#endif
#include <iostream>
#include <ctime>


namespace antpm
{
  enum LogLevel
  {
    LOG_RAW,             //< dont insert any prefix
    LOG_ERR,             //< runtime error
    LOG_WARN,            //< suppressable runtime error
    LOG_INF,             //< runtime information
    LOG_DBG,             //< debug info, mainly for developers
    LOG_DBG2,            //< more debug info
    LOG_DBG3             //< even more debug info (function trace, )
  };

#ifndef NDEBUG
# define psoLogMaxLogLevel antpm::LOG_DBG3
#else
# define psoLogMaxLogLevel antpm::LOG_DBG3
#endif

  inline
  const char*
  logLevelToString(const LogLevel& level)
  {
    switch(level)
    {
      case LOG_RAW:             return "";
      case LOG_ERR:             return "ERROR: ";
      case LOG_WARN:            return "WW: ";
      case LOG_INF:             return "II: ";
      case LOG_DBG:             return "DBG: ";
      case LOG_DBG2:            return "DBG: ";
      case LOG_DBG3:            return "DBG: ";
      default:                  return 0;
    }
  }

  inline
  std::ostream&
  operator<< (std::ostream& left, const LogLevel level)
  {
    return left << logLevelToString(level);
  }
  
  extern const std::string getVersionString();


  /**
   * Encapsulates a series of C++ style (<<) writes to a log in a
   * transactional manner.
   */
  template <typename T>
  class LogLine
  {
  public:
    inline LogLine(const LogLevel& level = LOG_INF) : _level(level) {}
    inline virtual             ~LogLine()           { T::instance()->print(_level, _oss.str()); }
    inline std::ostringstream& get()                { return _oss; }
  private:
    LogLine(const LogLine&);
    LogLine& operator= (const LogLine&);
  protected:
    const LogLevel     _level;
    std::ostringstream _oss;
  };

  /**
   *
   */
  class Log
    : public ClassInstantiator<Log>
    , public LazySingleton<Log, Log>
  {
  protected:
    inline Log(const char* logFileName = NULL);
  public:
    inline virtual ~Log();

#ifdef __GNUC__
    inline virtual int lprintf2(const LogLevel level,
                                const char* format,
                                ...) __attribute__ ((format (printf, 3, 4)));
#else // !__GNUC__
    inline virtual int lprintf2(const LogLevel level,
                                const char* format,
                                ...);
#endif // !__GNUC__
    inline virtual int vlprintf(const LogLevel level,
                                const char* format,
                                ::va_list args);
    inline virtual int print(const LogLevel level, const std::string& msg);

    inline virtual void addSink(std::ostream& os);
    inline virtual void delSink(std::ostream& os);

    inline virtual const LogLevel& getLogReportingLevel() const;
    inline virtual void            setLogReportingLevel(const LogLevel& logReportingLevel);
  protected:
    inline int writeStreams(const std::string& s);
  /**
   * getTimeStamp()
   */
  inline
  const std::string
  getTimeStamp()
  {
    ::time_t ltime;
    ::time(&ltime);
    char tmp[26];
    tmp[25] = '\0';
#ifdef _MSC_VER
    ::ctime_s(tmp, 26, &ltime);
#else
    ::ctime_r(&ltime, tmp);
#endif
    return std::string(tmp);
  }
  protected:
    typedef std::list<std::ostream*> SinkList;
    std::ofstream _ofs;
    SinkList      _sinks;
    LogLevel      _logReportingLevel;


    friend class antpm::ClassInstantiator<Log>;
  };

  Log::Log(const char* logFileName)
    : _logReportingLevel(psoLogMaxLogLevel)
  {
    std::ios_base::sync_with_stdio(false);

    if(!logFileName)
    {
      return;
    }

    // rotate previous log file
    if(::access(logFileName, 0x00) != -1)
    {
      std::string old = std::string(logFileName) + std::string(".old");
      ::remove(old.c_str());
      ::rename(logFileName, old.c_str());
    }

    _ofs.open(logFileName, std::ios::out | std::ios::trunc);
    if(!_ofs.is_open())
    {
      std::cerr << LOG_ERR << __FUNCTION__ << ": Unable to open log file \""
                << logFileName << "\" at " << getTimeStamp() << std::endl;
    }
    else
    {
      addSink(_ofs);

      std::string ts(getTimeStamp());
      this->lprintf2(LOG_INF,
                     "%s(): Log file \"%s\" opened at %s",
                     __FUNCTION__,
                     logFileName,
                     ts.c_str());
      std::string v(antpm::getVersionString());
      this->lprintf2(LOG_INF,
                     "%s\n",
                     v.c_str());
      this->lprintf2(LOG_RAW, "logging level: %d\n", this->_logReportingLevel);
    }
  }

  Log::~Log()
  {
    if(_ofs.is_open())
    {
      this->lprintf2(LOG_INF,
                     "%s(): Closing log file at %s",
                     __FUNCTION__,
                     getTimeStamp().c_str());
    }
  }

  int
  Log::lprintf2(const LogLevel level,
                const char* format,
                ...)
  {
    va_list args;
    va_start(args, format);
    int chars = this->vlprintf(level,
                               format,
                               args);
    va_end(args);
    return chars;
  }

  int
  Log::vlprintf(const LogLevel level,
                const char* format,
                ::va_list args)
  {
    std::string s(logLevelToString(level));

    char msg[1023+1];
    msg[1023] = '\0';
    vsnprintf(msg,
              1024,
              format,
              args);
    s.append(msg);

#ifdef __PSO_BUILD_WIN__
    _RPT0(_CRT_WARN, s.c_str());
#endif

    return writeStreams(s);
  }

  int
  Log::print(const LogLevel level, const std::string& msg)
  {
    const std::string s(std::string(logLevelToString(level)) + msg);

#ifdef _MSC_VER
    _RPT0(_CRT_WARN, s.c_str());
#endif

    return writeStreams(s);
  }

  void
  Log::addSink(std::ostream& os)
  {
    _sinks.push_back(&os);
    _sinks.unique();
  }

  void
  Log::delSink(std::ostream& os)
  {
    _sinks.remove(&os);
  }

  const LogLevel&
  Log::getLogReportingLevel() const
  {
    return _logReportingLevel;
  }

  void
  Log::setLogReportingLevel(const LogLevel& logReportingLevel)
  {
    _logReportingLevel = logReportingLevel;
    this->lprintf2(LOG_RAW, "logging level: %d\n", this->_logReportingLevel);
  }

  int
  Log::writeStreams(const std::string& s)
  {
//     static int c = 0;
//     c++;
//     if(!(c % 8))
//     {
//       c = 0;
//     }
    for(SinkList::iterator i = _sinks.begin(); i != _sinks.end(); i++)
    {
      (*i)->write(s.c_str(), s.length());
//       if(!c)
//       {
      (*i)->flush();
//       }
    }

    return (int)s.length();
  }

//  template<>
//  inline
//  Log*
//  ClassInstantiator<Log>::instantiate()
//  {
//    return new Log("antpm.txt");
//  }

//  template<>
//  template<>
//  inline
//  Log*
//  ClassInstantiator<Log>::instantiate<const char*>(const char* p1)
//  {
//    return new Log(p1);
//  }

  /**
   * Start a log line.
   */
#ifdef _MSC_VER
#define lprintf(level, format, ...)                                 \
  if(level > psoLogMaxLogLevel)                                     \
  {}                                                                \
  else if(level > antpm::Log::instance()->getLogReportingLevel())     \
  {}                                                                \
  else antpm::Log::instance()->lprintf2(level, format, __VA_ARGS__)
#else // GCC
#define lprintf(level, format, ...)                                 \
  if(level > psoLogMaxLogLevel)                                     \
  {}                                                                \
  else if(level > antpm::Log::instance()->getLogReportingLevel())     \
  {}                                                                \
  else antpm::Log::instance()->lprintf2(level, format, ##__VA_ARGS__)
#endif

#define LOG(level)                                             \
  if(level > psoLogMaxLogLevel)                                   \
  {}                                                              \
  else if(level > antpm::Log::instance()->getLogReportingLevel())   \
  {}                                                              \
  else antpm::LogLine<antpm::Log>(level).get()

  /**
   * Start a log line beginning with the name of the calling function.
   */
#define LOGT(level)                                              \
  if(level > psoLogMaxLogLevel)                                     \
  {}                                                                \
  else if(level > antpm::Log::instance()->getLogReportingLevel())     \
  {}                                                                \
  else antpm::LogLine<antpm::Log>(level).get()                          \
         << __FILE__ << ":" << __LINE__ << " "                      \
         << __FUNCTION__ << "(): "

//#define logt(level) psoLogt(level)

//#define log(level) psoLog(level)

}