log.cpp
1 //------------------------------------------------------------------------------
2 // log.cpp
3 //------------------------------------------------------------------------------
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 // 02110-1301 USA
19 //
20 //------------------------------------------------------------------------------
21 // Copyright (C) 2009 "Zalewa" <zalewapl@gmail.com>
22 //------------------------------------------------------------------------------
23 #include "log.h"
24 #include "strings.hpp"
25 #include <cstdio>
26 #include <QDateTime>
27 #include <QMutexLocker>
28 
29 DClass<Log>
30 {
31 public:
32  QString logContent;
33  QMutex mutex;
34  bool printToStderr;
35  bool timestamps;
36 };
37 
38 DPointeredNoCopy(Log)
39 
40 Log gLog;
41 
42 Log::Log()
43 {
44  d->timestamps = true;
45  d->printToStderr = true;
46 }
47 
48 Log::~Log()
49 {
50 }
51 
52 void Log::addEntry(const QString &string)
53 {
54  QString timestampString;
56  {
57  timestampString = Strings::timestamp("[hh:mm:ss] ");
58  }
59 
60  QString entry = timestampString + string + "\n";
61  addUnformattedEntry(entry);
62 }
63 
64 void Log::addUnformattedEntry(const QString &string)
65 {
66  QMutexLocker locker(&d->mutex);
67 
68  if (isPrintingToStderr())
69  {
70  fprintf(stderr, "%s", string.toUtf8().constData());
71  }
72 
73  d->logContent += string;
74  emit newEntry(string);
75 }
76 
78 {
79  return d->timestamps;
80 }
81 
83 {
84  d->logContent.clear();
85 }
86 
87 const QString &Log::content() const
88 {
89  return d->logContent;
90 }
91 
93 {
94  return d->printToStderr;
95 }
96 
98 {
99  return isPrintingToStderr();
100 }
101 
102 Log &Log::operator<<(const QString &string)
103 {
104  addEntry(string);
105  return *this;
106 }
107 
109 {
110  setPrintingToStderr(b);
111 }
112 
113 void Log::setPrintingToStderr(bool b)
114 {
115  d->printToStderr = b;
116 }
117 
118 void Log::setTimestampsEnabled(bool b)
119 {
120  d->timestamps = b;
121 }