3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "threading/mutex_auto_lock.h"
27 #include "exceptions.h"
28 #include "util/numeric.h"
37 const int BUFFER_LENGTH = 256;
39 class StringBuffer : public std::streambuf {
46 virtual void flush(const std::string &buf) = 0;
47 std::streamsize xsputn(const char *s, std::streamsize n);
48 void push_back(char c);
51 char buffer[BUFFER_LENGTH];
56 class LogBuffer : public StringBuffer {
58 LogBuffer(Logger &logger, LogLevel lev) :
63 void flush(const std::string &buffer);
71 class RawLogBuffer : public StringBuffer {
73 void flush(const std::string &buffer);
82 StreamLogOutput stdout_output(std::cout);
83 StreamLogOutput stderr_output(std::cerr);
84 std::ostream null_stream(NULL);
88 LogBuffer none_buf(g_logger, LL_NONE);
89 LogBuffer error_buf(g_logger, LL_ERROR);
90 LogBuffer warning_buf(g_logger, LL_WARNING);
91 LogBuffer action_buf(g_logger, LL_ACTION);
92 LogBuffer info_buf(g_logger, LL_INFO);
93 LogBuffer verbose_buf(g_logger, LL_VERBOSE);
96 std::ostream *dout_con_ptr = &null_stream;
97 std::ostream *derr_con_ptr = &verbosestream;
100 std::ostream *dout_server_ptr = &infostream;
101 std::ostream *derr_server_ptr = &errorstream;
105 std::ostream *dout_client_ptr = &infostream;
106 std::ostream *derr_client_ptr = &errorstream;
109 std::ostream rawstream(&raw_buf);
110 std::ostream dstream(&none_buf);
111 std::ostream errorstream(&error_buf);
112 std::ostream warningstream(&warning_buf);
113 std::ostream actionstream(&action_buf);
114 std::ostream infostream(&info_buf);
115 std::ostream verbosestream(&verbose_buf);
120 static unsigned int g_level_to_android[] = {
121 ANDROID_LOG_INFO, // LL_NONE
123 ANDROID_LOG_ERROR, // LL_ERROR
124 ANDROID_LOG_WARN, // LL_WARNING
125 ANDROID_LOG_WARN, // LL_ACTION
127 ANDROID_LOG_DEBUG, // LL_INFO
128 ANDROID_LOG_VERBOSE, // LL_VERBOSE
131 class AndroidSystemLogOutput : public ICombinedLogOutput {
133 AndroidSystemLogOutput()
135 g_logger.addOutput(this);
137 ~AndroidSystemLogOutput()
139 g_logger.removeOutput(this);
141 void logRaw(LogLevel lev, const std::string &line)
143 STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
144 mismatch_between_android_and_internal_loglevels);
145 __android_log_print(g_level_to_android[lev],
146 PROJECT_NAME_C, "%s", line.c_str());
150 AndroidSystemLogOutput g_android_log_output;
154 ///////////////////////////////////////////////////////////////////////////////
161 LogLevel Logger::stringToLevel(const std::string &name)
165 else if (name == "error")
167 else if (name == "warning")
169 else if (name == "action")
171 else if (name == "info")
173 else if (name == "verbose")
179 void Logger::addOutput(ILogOutput *out)
181 addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
184 void Logger::addOutput(ILogOutput *out, LogLevel lev)
186 m_outputs[lev].push_back(out);
189 void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
191 for (size_t i = 0; i < LL_MAX; i++) {
192 if (mask & LOGLEVEL_TO_MASKLEVEL(i))
193 m_outputs[i].push_back(out);
197 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
199 assert(lev < LL_MAX);
200 for (size_t i = 0; i <= lev; i++)
201 m_outputs[i].push_back(out);
204 LogLevelMask Logger::removeOutput(ILogOutput *out)
206 LogLevelMask ret_mask = 0;
207 for (size_t i = 0; i < LL_MAX; i++) {
208 std::vector<ILogOutput *>::iterator it;
210 it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
211 if (it != m_outputs[i].end()) {
212 ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
213 m_outputs[i].erase(it);
219 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
221 m_silenced_levels[lev] = silenced;
224 void Logger::registerThread(const std::string &name)
226 threadid_t id = thr_get_current_thread_id();
227 MutexAutoLock lock(m_mutex);
228 m_thread_names[id] = name;
231 void Logger::deregisterThread()
233 threadid_t id = thr_get_current_thread_id();
234 MutexAutoLock lock(m_mutex);
235 m_thread_names.erase(id);
238 const std::string Logger::getLevelLabel(LogLevel lev)
240 static const std::string names[] = {
248 assert(lev < LL_MAX && lev >= 0);
249 STATIC_ASSERT(ARRLEN(names) == LL_MAX,
250 mismatch_between_loglevel_names_and_enum);
254 const std::string Logger::getThreadName()
256 std::map<threadid_t, std::string>::const_iterator it;
258 threadid_t id = thr_get_current_thread_id();
259 it = m_thread_names.find(id);
260 if (it != m_thread_names.end())
263 std::ostringstream os;
264 os << "#0x" << std::hex << id;
268 void Logger::log(LogLevel lev, const std::string &text)
270 if (m_silenced_levels[lev])
273 const std::string thread_name = getThreadName();
274 const std::string label = getLevelLabel(lev);
275 const std::string timestamp = getTimestamp();
276 std::ostringstream os(std::ios_base::binary);
277 os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
279 logToOutputs(lev, os.str(), timestamp, thread_name, text);
282 void Logger::logRaw(LogLevel lev, const std::string &text)
284 if (m_silenced_levels[lev])
287 logToOutputsRaw(lev, text);
290 void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
292 MutexAutoLock lock(m_mutex);
293 for (size_t i = 0; i != m_outputs[lev].size(); i++)
294 m_outputs[lev][i]->logRaw(lev, line);
297 void Logger::logToOutputs(LogLevel lev, const std::string &combined,
298 const std::string &time, const std::string &thread_name,
299 const std::string &payload_text)
301 MutexAutoLock lock(m_mutex);
302 for (size_t i = 0; i != m_outputs[lev].size(); i++)
303 m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
308 //// *LogOutput methods
311 void FileLogOutput::open(const std::string &filename)
313 m_stream.open(filename.c_str(), std::ios::app | std::ios::ate);
314 if (!m_stream.good())
315 throw FileNotGoodException("Failed to open log file " +
316 filename + ": " + strerror(errno));
318 "-------------" << std::endl
319 << " Separator" << std::endl
320 << "-------------\n" << std::endl;
329 int StringBuffer::overflow(int c)
336 std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
338 for (int i = 0; i < n; ++i)
343 void StringBuffer::push_back(char c)
345 if (c == '\n' || c == '\r') {
347 flush(std::string(buffer, buffer_index));
350 int index = buffer_index;
352 if (index >= BUFFER_LENGTH) {
353 flush(std::string(buffer, buffer_index));
356 buffer_index = index;
362 void LogBuffer::flush(const std::string &buffer)
364 logger.log(level, buffer);
367 void RawLogBuffer::flush(const std::string &buffer)
369 g_logger.logRaw(LL_NONE, buffer);