]> granicus.if.org Git - icinga2/blob - lib/base/logger.cpp
Merge pull request #6573 from Icinga/bugfix/operator-docs-1
[icinga2] / lib / base / logger.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/)  *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program 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              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "base/logger.hpp"
21 #include "base/logger-ti.cpp"
22 #include "base/application.hpp"
23 #include "base/streamlogger.hpp"
24 #include "base/configtype.hpp"
25 #include "base/utility.hpp"
26 #include "base/objectlock.hpp"
27 #include "base/context.hpp"
28 #include "base/scriptglobal.hpp"
29 #include <iostream>
30
31 using namespace icinga;
32
33 template Log& Log::operator<<(const Value&);
34 template Log& Log::operator<<(const String&);
35 template Log& Log::operator<<(const std::string&);
36 template Log& Log::operator<<(const bool&);
37 template Log& Log::operator<<(const unsigned int&);
38 template Log& Log::operator<<(const int&);
39 template Log& Log::operator<<(const unsigned long&);
40 template Log& Log::operator<<(const long&);
41 template Log& Log::operator<<(const double&);
42
43 REGISTER_TYPE(Logger);
44
45 std::set<Logger::Ptr> Logger::m_Loggers;
46 boost::mutex Logger::m_Mutex;
47 bool Logger::m_ConsoleLogEnabled = true;
48 bool Logger::m_TimestampEnabled = true;
49 LogSeverity Logger::m_ConsoleLogSeverity = LogInformation;
50
51 INITIALIZE_ONCE([]() {
52         ScriptGlobal::Set("System.LogDebug", LogDebug, true);
53         ScriptGlobal::Set("System.LogNotice", LogNotice, true);
54         ScriptGlobal::Set("System.LogInformation", LogInformation, true);
55         ScriptGlobal::Set("System.LogWarning", LogWarning, true);
56         ScriptGlobal::Set("System.LogCritical", LogCritical, true);
57 });
58
59 /**
60  * Constructor for the Logger class.
61  */
62 void Logger::Start(bool runtimeCreated)
63 {
64         ObjectImpl<Logger>::Start(runtimeCreated);
65
66         boost::mutex::scoped_lock lock(m_Mutex);
67         m_Loggers.insert(this);
68 }
69
70 void Logger::Stop(bool runtimeRemoved)
71 {
72         {
73                 boost::mutex::scoped_lock lock(m_Mutex);
74                 m_Loggers.erase(this);
75         }
76
77         ObjectImpl<Logger>::Stop(runtimeRemoved);
78 }
79
80 std::set<Logger::Ptr> Logger::GetLoggers()
81 {
82         boost::mutex::scoped_lock lock(m_Mutex);
83         return m_Loggers;
84 }
85
86 /**
87  * Retrieves the minimum severity for this logger.
88  *
89  * @returns The minimum severity.
90  */
91 LogSeverity Logger::GetMinSeverity() const
92 {
93         String severity = GetSeverity();
94         if (severity.IsEmpty())
95                 return LogInformation;
96         else {
97                 LogSeverity ls = LogInformation;
98
99                 try {
100                         ls = Logger::StringToSeverity(severity);
101                 } catch (const std::exception&) { /* use the default level */ }
102
103                 return ls;
104         }
105 }
106
107 /**
108  * Converts a severity enum value to a string.
109  *
110  * @param severity The severity value.
111  */
112 String Logger::SeverityToString(LogSeverity severity)
113 {
114         switch (severity) {
115                 case LogDebug:
116                         return "debug";
117                 case LogNotice:
118                         return "notice";
119                 case LogInformation:
120                         return "information";
121                 case LogWarning:
122                         return "warning";
123                 case LogCritical:
124                         return "critical";
125                 default:
126                         BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid severity."));
127         }
128 }
129
130 /**
131  * Converts a string to a severity enum value.
132  *
133  * @param severity The severity.
134  */
135 LogSeverity Logger::StringToSeverity(const String& severity)
136 {
137         if (severity == "debug")
138                 return LogDebug;
139         else if (severity == "notice")
140                 return LogNotice;
141         else if (severity == "information")
142                 return LogInformation;
143         else if (severity == "warning")
144                 return LogWarning;
145         else if (severity == "critical")
146                 return LogCritical;
147         else
148                 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid severity: " + severity));
149 }
150
151 void Logger::DisableConsoleLog()
152 {
153         m_ConsoleLogEnabled = false;
154 }
155
156 void Logger::EnableConsoleLog()
157 {
158         m_ConsoleLogEnabled = true;
159 }
160
161 bool Logger::IsConsoleLogEnabled()
162 {
163         return m_ConsoleLogEnabled;
164 }
165
166 void Logger::SetConsoleLogSeverity(LogSeverity logSeverity)
167 {
168         m_ConsoleLogSeverity = logSeverity;
169 }
170
171 LogSeverity Logger::GetConsoleLogSeverity()
172 {
173         return m_ConsoleLogSeverity;
174 }
175
176 void Logger::DisableTimestamp()
177 {
178         m_TimestampEnabled = false;
179 }
180
181 void Logger::EnableTimestamp()
182 {
183         m_TimestampEnabled = true;
184 }
185
186 bool Logger::IsTimestampEnabled()
187 {
188         return m_TimestampEnabled;
189 }
190
191 void Logger::ValidateSeverity(const Lazy<String>& lvalue, const ValidationUtils& utils)
192 {
193         ObjectImpl<Logger>::ValidateSeverity(lvalue, utils);
194
195         try {
196                 StringToSeverity(lvalue());
197         } catch (...) {
198                 BOOST_THROW_EXCEPTION(ValidationError(this, { "severity" }, "Invalid severity specified: " + lvalue()));
199         }
200 }
201
202 Log::Log(LogSeverity severity, String facility, const String& message)
203         : m_Severity(severity), m_Facility(std::move(facility))
204 {
205         m_Buffer << message;
206 }
207
208 Log::Log(LogSeverity severity, String facility)
209         : m_Severity(severity), m_Facility(std::move(facility))
210 { }
211
212 /**
213  * Writes the message to the application's log.
214  */
215 Log::~Log()
216 {
217         LogEntry entry;
218         entry.Timestamp = Utility::GetTime();
219         entry.Severity = m_Severity;
220         entry.Facility = m_Facility;
221         entry.Message = m_Buffer.str();
222
223         if (m_Severity >= LogWarning) {
224                 ContextTrace context;
225
226                 if (context.GetLength() > 0) {
227                         std::ostringstream trace;
228                         trace << context;
229                         entry.Message += "\nContext:" + trace.str();
230                 }
231         }
232
233         for (const Logger::Ptr& logger : Logger::GetLoggers()) {
234                 ObjectLock llock(logger);
235
236                 if (!logger->IsActive())
237                         continue;
238
239                 if (entry.Severity >= logger->GetMinSeverity())
240                         logger->ProcessLogEntry(entry);
241
242 #ifdef I2_DEBUG /* I2_DEBUG */
243                 /* Always flush, don't depend on the timer. Enable this for development sprints. */
244                 //logger->Flush();
245 #endif /* I2_DEBUG */
246         }
247
248         if (Logger::IsConsoleLogEnabled() && entry.Severity >= Logger::GetConsoleLogSeverity()) {
249                 StreamLogger::ProcessLogEntry(std::cout, entry);
250
251                 /* "Console" might be a pipe/socket (systemd, daemontools, docker, ...),
252                  * then cout will not flush lines automatically. */
253                 std::cout << std::flush;
254         }
255 }
256
257 Log& Log::operator<<(const char *val)
258 {
259         m_Buffer << val;
260         return *this;
261 }