easylogging++.h 190.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
//
//  Bismillah ar-Rahmaan ar-Raheem
//
//  Easylogging++ v9.96.7
//  Single-header only, cross-platform logging library for C++ applications
//
//  Copyright (c) 2012-2018 Zuhd Web Services
//  Copyright (c) 2012-2018 @abumusamq
//
//  This library is released under the MIT Licence.
//  https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE
//
//  https://zuhd.org
//  http://muflihun.com
//

#ifndef EASYLOGGINGPP_H
#define EASYLOGGINGPP_H
// Compilers and C++0x/C++11 Evaluation
#if __cplusplus >= 201103L
Y
youny626 已提交
21
#define ELPP_CXX11 1
22 23
#endif  // __cplusplus >= 201103L
#if (defined(__GNUC__))
Y
youny626 已提交
24
#define ELPP_COMPILER_GCC 1
25
#else
Y
youny626 已提交
26
#define ELPP_COMPILER_GCC 0
27 28
#endif
#if ELPP_COMPILER_GCC
Y
youny626 已提交
29 30 31 32
#define ELPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#if defined(__GXX_EXPERIMENTAL_CXX0X__)
#define ELPP_CXX0X 1
#endif
33 34 35
#endif
// Visual C++
#if defined(_MSC_VER)
Y
youny626 已提交
36
#define ELPP_COMPILER_MSVC 1
37
#else
Y
youny626 已提交
38
#define ELPP_COMPILER_MSVC 0
39 40 41
#endif
#define ELPP_CRT_DBG_WARNINGS ELPP_COMPILER_MSVC
#if ELPP_COMPILER_MSVC
Y
youny626 已提交
42 43 44 45 46
#if (_MSC_VER == 1600)
#define ELPP_CXX0X 1
#elif (_MSC_VER >= 1700)
#define ELPP_CXX11 1
#endif
47 48 49
#endif
// Clang++
#if (defined(__clang__) && (__clang__ == 1))
Y
youny626 已提交
50
#define ELPP_COMPILER_CLANG 1
51
#else
Y
youny626 已提交
52
#define ELPP_COMPILER_CLANG 0
53 54
#endif
#if ELPP_COMPILER_CLANG
Y
youny626 已提交
55 56 57 58 59 60
#if __has_include(<thread>)
#include <cstddef>  // Make __GLIBCXX__ defined when using libstdc++
#if !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
#define ELPP_CLANG_SUPPORTS_THREAD
#endif  // !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
#endif  // __has_include(<thread>)
61 62
#endif
#if (defined(__MINGW32__) || defined(__MINGW64__))
Y
youny626 已提交
63
#define ELPP_MINGW 1
64
#else
Y
youny626 已提交
65
#define ELPP_MINGW 0
66 67
#endif
#if (defined(__CYGWIN__) && (__CYGWIN__ == 1))
Y
youny626 已提交
68
#define ELPP_CYGWIN 1
69
#else
Y
youny626 已提交
70
#define ELPP_CYGWIN 0
71 72
#endif
#if (defined(__INTEL_COMPILER))
Y
youny626 已提交
73
#define ELPP_COMPILER_INTEL 1
74
#else
Y
youny626 已提交
75
#define ELPP_COMPILER_INTEL 0
76 77 78 79
#endif
// Operating System Evaluation
// Windows
#if (defined(_WIN32) || defined(_WIN64))
Y
youny626 已提交
80
#define ELPP_OS_WINDOWS 1
81
#else
Y
youny626 已提交
82
#define ELPP_OS_WINDOWS 0
83 84 85
#endif
// Linux
#if (defined(__linux) || defined(__linux__))
Y
youny626 已提交
86
#define ELPP_OS_LINUX 1
87
#else
Y
youny626 已提交
88
#define ELPP_OS_LINUX 0
89 90
#endif
#if (defined(__APPLE__))
Y
youny626 已提交
91
#define ELPP_OS_MAC 1
92
#else
Y
youny626 已提交
93
#define ELPP_OS_MAC 0
94 95
#endif
#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
Y
youny626 已提交
96
#define ELPP_OS_FREEBSD 1
97
#else
Y
youny626 已提交
98
#define ELPP_OS_FREEBSD 0
99 100
#endif
#if (defined(__sun))
Y
youny626 已提交
101
#define ELPP_OS_SOLARIS 1
102
#else
Y
youny626 已提交
103
#define ELPP_OS_SOLARIS 0
104 105
#endif
#if (defined(_AIX))
Y
youny626 已提交
106
#define ELPP_OS_AIX 1
107
#else
Y
youny626 已提交
108
#define ELPP_OS_AIX 0
109 110
#endif
#if (defined(__NetBSD__))
Y
youny626 已提交
111
#define ELPP_OS_NETBSD 1
112
#else
Y
youny626 已提交
113
#define ELPP_OS_NETBSD 0
114 115
#endif
#if defined(__EMSCRIPTEN__)
Y
youny626 已提交
116
#define ELPP_OS_EMSCRIPTEN 1
117
#else
Y
youny626 已提交
118
#define ELPP_OS_EMSCRIPTEN 0
119 120
#endif
// Unix
Y
youny626 已提交
121 122 123 124
#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS || ELPP_OS_AIX || \
      ELPP_OS_EMSCRIPTEN) &&                                                                                 \
     (!ELPP_OS_WINDOWS))
#define ELPP_OS_UNIX 1
125
#else
Y
youny626 已提交
126
#define ELPP_OS_UNIX 0
127 128
#endif
#if (defined(__ANDROID__))
Y
youny626 已提交
129
#define ELPP_OS_ANDROID 1
130
#else
Y
youny626 已提交
131
#define ELPP_OS_ANDROID 0
132 133 134
#endif
// Evaluating Cygwin as *nix OS
#if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
Y
youny626 已提交
135 136 137 138 139
#undef ELPP_OS_UNIX
#undef ELPP_OS_LINUX
#define ELPP_OS_UNIX 1
#define ELPP_OS_LINUX 1
#endif  //  !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
140
#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO)
Y
youny626 已提交
141 142
#define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout
#endif  // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
143
#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR)
Y
youny626 已提交
144 145
#define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr
#endif  // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
146
#if !defined(ELPP_INTERNAL_DEBUGGING_ENDL)
Y
youny626 已提交
147 148
#define ELPP_INTERNAL_DEBUGGING_ENDL std::endl
#endif  // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
149
#if !defined(ELPP_INTERNAL_DEBUGGING_MSG)
Y
youny626 已提交
150 151
#define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg
#endif  // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
152 153
// Internal Assertions and errors
#if !defined(ELPP_DISABLE_ASSERT)
Y
youny626 已提交
154 155 156 157 158 159 160 161 162 163
#if (defined(ELPP_DEBUG_ASSERT_FAILURE))
#define ELPP_ASSERT(expr, msg)                                                                                \
    if (!(expr)) {                                                                                            \
        std::stringstream internalInfoStream;                                                                 \
        internalInfoStream << msg;                                                                            \
        ELPP_INTERNAL_DEBUGGING_OUT_ERROR                                                                     \
            << "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \""     \
            << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; \
        base::utils::abort(1, "ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE");             \
    }
164
#else
Y
youny626 已提交
165 166 167 168 169 170 171 172 173 174 175
#define ELPP_ASSERT(expr, msg)                                                                                  \
    if (!(expr)) {                                                                                              \
        std::stringstream internalInfoStream;                                                                   \
        internalInfoStream << msg;                                                                              \
        ELPP_INTERNAL_DEBUGGING_OUT_ERROR                                                                       \
            << "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \
            << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL;   \
    }
#endif  // (defined(ELPP_DEBUG_ASSERT_FAILURE))
#else
#define ELPP_ASSERT(x, y)
176 177
#endif  //(!defined(ELPP_DISABLE_ASSERT)
#if ELPP_COMPILER_MSVC
Y
youny626 已提交
178 179 180 181 182 183 184
#define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR                                       \
    {                                                                              \
        char buff[256];                                                            \
        strerror_s(buff, 256, errno);                                              \
        ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]"; \
    }                                                                              \
    (void)0
185
#else
Y
youny626 已提交
186 187 188
#define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR                                              \
    ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; \
    (void)0
189 190
#endif  // ELPP_COMPILER_MSVC
#if defined(ELPP_DEBUG_ERRORS)
Y
youny626 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
#if !defined(ELPP_INTERNAL_ERROR)
#define ELPP_INTERNAL_ERROR(msg, pe)                                                                \
    {                                                                                               \
        std::stringstream internalInfoStream;                                                       \
        internalInfoStream << "<ERROR> " << msg;                                                    \
        ELPP_INTERNAL_DEBUGGING_OUT_ERROR << "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \
                                          << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str())  \
                                          << ELPP_INTERNAL_DEBUGGING_ENDL;                          \
        if (pe) {                                                                                   \
            ELPP_INTERNAL_DEBUGGING_OUT_ERROR << "    ";                                            \
            ELPP_INTERNAL_DEBUGGING_WRITE_PERROR;                                                   \
        }                                                                                           \
    }                                                                                               \
    (void)0
#endif
206
#else
Y
youny626 已提交
207 208
#undef ELPP_INTERNAL_INFO
#define ELPP_INTERNAL_ERROR(msg, pe)
209 210
#endif  // defined(ELPP_DEBUG_ERRORS)
#if (defined(ELPP_DEBUG_INFO))
Y
youny626 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224
#if !(defined(ELPP_INTERNAL_INFO_LEVEL))
#define ELPP_INTERNAL_INFO_LEVEL 9
#endif  // !(defined(ELPP_INTERNAL_INFO_LEVEL))
#if !defined(ELPP_INTERNAL_INFO)
#define ELPP_INTERNAL_INFO(lvl, msg)                                                                  \
    {                                                                                                 \
        if (lvl <= ELPP_INTERNAL_INFO_LEVEL) {                                                        \
            std::stringstream internalInfoStream;                                                     \
            internalInfoStream << "<INFO> " << msg;                                                   \
            ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \
                                             << ELPP_INTERNAL_DEBUGGING_ENDL;                         \
        }                                                                                             \
    }
#endif
225
#else
Y
youny626 已提交
226 227
#undef ELPP_INTERNAL_INFO
#define ELPP_INTERNAL_INFO(lvl, msg)
228 229
#endif  // (defined(ELPP_DEBUG_INFO))
#if (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
Y
youny626 已提交
230 231 232 233 234 235 236 237 238 239
#if (ELPP_COMPILER_GCC && !ELPP_MINGW && !ELPP_OS_ANDROID && !ELPP_OS_EMSCRIPTEN)
#define ELPP_STACKTRACE 1
#else
#if ELPP_COMPILER_MSVC
#pragma message("Stack trace not available for this compiler")
#else
#warning "Stack trace not available for this compiler";
#endif  // ELPP_COMPILER_MSVC
#define ELPP_STACKTRACE 0
#endif  // ELPP_COMPILER_GCC
240
#else
Y
youny626 已提交
241
#define ELPP_STACKTRACE 0
242 243 244 245 246
#endif  // (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
// Miscellaneous macros
#define ELPP_UNUSED(x) (void)x
#if ELPP_OS_UNIX
// Log file permissions for unix-based systems
Y
youny626 已提交
247
#define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH
248 249
#endif  // ELPP_OS_UNIX
#if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
Y
youny626 已提交
250 251
#if defined(ELPP_EXPORT_SYMBOLS)
#define ELPP_EXPORT __declspec(dllexport)
252
#else
Y
youny626 已提交
253 254 255 256
#define ELPP_EXPORT __declspec(dllimport)
#endif  // defined(ELPP_EXPORT_SYMBOLS)
#else
#define ELPP_EXPORT
257 258 259 260 261 262 263
#endif  // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
// Some special functions that are VC++ specific
#undef STRTOK
#undef STRERROR
#undef STRCAT
#undef STRCPY
#if ELPP_CRT_DBG_WARNINGS
Y
youny626 已提交
264 265 266 267
#define STRTOK(a, b, c) strtok_s(a, b, c)
#define STRERROR(a, b, c) strerror_s(a, b, c)
#define STRCAT(a, b, len) strcat_s(a, len, b)
#define STRCPY(a, b, len) strcpy_s(a, len, b)
268
#else
Y
youny626 已提交
269 270 271 272
#define STRTOK(a, b, c) strtok(a, b)
#define STRERROR(a, b, c) strerror(c)
#define STRCAT(a, b, len) strcat(a, b)
#define STRCPY(a, b, len) strcpy(a, b)
273 274 275
#endif
// Compiler specific support evaluations
#if (ELPP_MINGW && !defined(ELPP_FORCE_USE_STD_THREAD))
Y
youny626 已提交
276 277 278 279 280
#define ELPP_USE_STD_THREADING 0
#else
#if ((ELPP_COMPILER_CLANG && defined(ELPP_CLANG_SUPPORTS_THREAD)) || (!ELPP_COMPILER_CLANG && defined(ELPP_CXX11)) || \
     defined(ELPP_FORCE_USE_STD_THREAD))
#define ELPP_USE_STD_THREADING 1
281
#else
Y
youny626 已提交
282 283
#define ELPP_USE_STD_THREADING 0
#endif
284 285 286
#endif
#undef ELPP_FINAL
#if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
Y
youny626 已提交
287
#define ELPP_FINAL
288
#else
Y
youny626 已提交
289
#define ELPP_FINAL final
290 291
#endif  // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
#if defined(ELPP_EXPERIMENTAL_ASYNC)
Y
youny626 已提交
292
#define ELPP_ASYNC_LOGGING 1
293
#else
Y
youny626 已提交
294 295
#define ELPP_ASYNC_LOGGING 0
#endif  // defined(ELPP_EXPERIMENTAL_ASYNC)
296
#if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
Y
youny626 已提交
297
#define ELPP_THREADING_ENABLED 1
298
#else
Y
youny626 已提交
299
#define ELPP_THREADING_ENABLED 0
300 301 302 303
#endif  // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
// Function macro ELPP_FUNC
#undef ELPP_FUNC
#if ELPP_COMPILER_MSVC  // Visual C++
Y
youny626 已提交
304
#define ELPP_FUNC __FUNCSIG__
305
#elif ELPP_COMPILER_GCC  // GCC
Y
youny626 已提交
306
#define ELPP_FUNC __PRETTY_FUNCTION__
307
#elif ELPP_COMPILER_INTEL  // Intel C++
Y
youny626 已提交
308
#define ELPP_FUNC __PRETTY_FUNCTION__
309
#elif ELPP_COMPILER_CLANG  // Clang++
Y
youny626 已提交
310
#define ELPP_FUNC __PRETTY_FUNCTION__
311
#else
Y
youny626 已提交
312 313 314 315 316
#if defined(__func__)
#define ELPP_FUNC __func__
#else
#define ELPP_FUNC ""
#endif  // defined(__func__)
317 318 319 320
#endif  // defined(_MSC_VER)
#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED
// Keep following line commented until features are fixed
#define ELPP_VARIADIC_TEMPLATES_SUPPORTED \
Y
youny626 已提交
321
    (ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800))
322 323 324 325 326 327 328
// Logging Enable/Disable macros
#if defined(ELPP_DISABLE_LOGS)
#define ELPP_LOGGING_ENABLED 0
#else
#define ELPP_LOGGING_ENABLED 1
#endif
#if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
329
#define ELPP_DEBUG_LOG 1
330
#else
Y
youny626 已提交
331
#define ELPP_DEBUG_LOG 0
332 333
#endif  // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
334
#define ELPP_INFO_LOG 1
335
#else
Y
youny626 已提交
336
#define ELPP_INFO_LOG 0
337 338
#endif  // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
339
#define ELPP_WARNING_LOG 1
340
#else
Y
youny626 已提交
341
#define ELPP_WARNING_LOG 0
342 343
#endif  // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
344
#define ELPP_ERROR_LOG 1
345
#else
Y
youny626 已提交
346
#define ELPP_ERROR_LOG 0
347 348
#endif  // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
349
#define ELPP_FATAL_LOG 1
350
#else
Y
youny626 已提交
351
#define ELPP_FATAL_LOG 0
352 353
#endif  // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
354
#define ELPP_TRACE_LOG 1
355
#else
Y
youny626 已提交
356
#define ELPP_TRACE_LOG 0
357 358
#endif  // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
Y
youny626 已提交
359
#define ELPP_VERBOSE_LOG 1
360
#else
Y
youny626 已提交
361
#define ELPP_VERBOSE_LOG 0
362 363
#endif  // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
#if (!(ELPP_CXX0X || ELPP_CXX11))
Y
youny626 已提交
364
#error "C++0x (or higher) support not detected! (Is `-std=c++11' missing?)"
365 366 367
#endif  // (!(ELPP_CXX0X || ELPP_CXX11))
// Headers
#if defined(ELPP_SYSLOG)
Y
youny626 已提交
368
#include <syslog.h>
369 370 371
#endif  // defined(ELPP_SYSLOG)
#include <cctype>
#include <cerrno>
Y
youny626 已提交
372
#include <csignal>
373
#include <cstdarg>
Y
youny626 已提交
374 375 376 377
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
378
#if defined(ELPP_UNICODE)
Y
youny626 已提交
379 380 381 382
#include <locale>
#if ELPP_OS_WINDOWS
#include <codecvt>
#endif  // ELPP_OS_WINDOWS
383 384
#endif  // defined(ELPP_UNICODE)
#if ELPP_STACKTRACE
Y
youny626 已提交
385 386
#include <cxxabi.h>
#include <execinfo.h>
387 388
#endif  // ELPP_STACKTRACE
#if ELPP_OS_ANDROID
Y
youny626 已提交
389
#include <sys/system_properties.h>
390 391
#endif  // ELPP_OS_ANDROID
#if ELPP_OS_UNIX
Y
youny626 已提交
392 393
#include <sys/stat.h>
#include <sys/time.h>
394
#elif ELPP_OS_WINDOWS
Y
youny626 已提交
395 396 397 398 399 400 401 402 403
#include <direct.h>
#include <windows.h>
#if defined(WIN32_LEAN_AND_MEAN)
#if defined(ELPP_WINSOCK2)
#include <winsock2.h>
#else
#include <winsock.h>
#endif  // defined(ELPP_WINSOCK2)
#endif  // defined(WIN32_LEAN_AND_MEAN)
404 405 406
#endif  // ELPP_OS_UNIX
#include <algorithm>
#include <fstream>
Y
youny626 已提交
407
#include <functional>
408
#include <iostream>
Y
youny626 已提交
409
#include <map>
410
#include <memory>
Y
youny626 已提交
411 412
#include <sstream>
#include <string>
413
#include <type_traits>
Y
youny626 已提交
414 415 416
#include <unordered_map>
#include <utility>
#include <vector>
417
#if ELPP_THREADING_ENABLED
Y
youny626 已提交
418 419 420 421 422 423 424 425
#if ELPP_USE_STD_THREADING
#include <mutex>
#include <thread>
#else
#if ELPP_OS_UNIX
#include <pthread.h>
#endif  // ELPP_OS_UNIX
#endif  // ELPP_USE_STD_THREADING
426 427
#endif  // ELPP_THREADING_ENABLED
#if ELPP_ASYNC_LOGGING
Y
youny626 已提交
428 429 430 431 432 433
#if defined(ELPP_NO_SLEEP_FOR)
#include <unistd.h>
#endif  // defined(ELPP_NO_SLEEP_FOR)
#include <condition_variable>
#include <queue>
#include <thread>
434 435 436
#endif  // ELPP_ASYNC_LOGGING
#if defined(ELPP_STL_LOGGING)
// For logging STL based templates
Y
youny626 已提交
437 438 439 440 441 442 443 444 445 446 447 448
#include <bitset>
#include <deque>
#include <list>
#include <queue>
#include <set>
#include <stack>
#if defined(ELPP_LOG_STD_ARRAY)
#include <array>
#endif  // defined(ELPP_LOG_STD_ARRAY)
#if defined(ELPP_LOG_UNORDERED_SET)
#include <unordered_set>
#endif  // defined(ELPP_UNORDERED_SET)
449 450 451
#endif  // defined(ELPP_STL_LOGGING)
#if defined(ELPP_QT_LOGGING)
// For logging Qt based classes & templates
Y
youny626 已提交
452 453 454 455 456 457 458 459 460 461 462 463
#include <QByteArray>
#include <QHash>
#include <QLinkedList>
#include <QList>
#include <QMap>
#include <QMultiHash>
#include <QPair>
#include <QQueue>
#include <QSet>
#include <QStack>
#include <QString>
#include <QVector>
464 465 466
#endif  // defined(ELPP_QT_LOGGING)
#if defined(ELPP_BOOST_LOGGING)
// For logging boost based classes & templates
Y
youny626 已提交
467 468 469 470 471 472 473 474
#include <boost/container/deque.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/list.hpp>
#include <boost/container/map.hpp>
#include <boost/container/set.hpp>
#include <boost/container/stable_vector.hpp>
#include <boost/container/vector.hpp>
475 476 477
#endif  // defined(ELPP_BOOST_LOGGING)
#if defined(ELPP_WXWIDGETS_LOGGING)
// For logging wxWidgets based classes & templates
Y
youny626 已提交
478
#include <wx/vector.h>
479 480
#endif  // defined(ELPP_WXWIDGETS_LOGGING)
#if defined(ELPP_UTC_DATETIME)
Y
youny626 已提交
481 482 483
#define elpptime_r gmtime_r
#define elpptime_s gmtime_s
#define elpptime gmtime
484
#else
Y
youny626 已提交
485 486 487
#define elpptime_r localtime_r
#define elpptime_s localtime_s
#define elpptime localtime
488 489 490 491 492 493 494 495
#endif  // defined(ELPP_UTC_DATETIME)
// Forward declarations
namespace el {
class Logger;
class LogMessage;
class PerformanceTrackingData;
class Loggers;
class Helpers;
Y
youny626 已提交
496 497
template <typename T>
class Callback;
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
class LogDispatchCallback;
class PerformanceTrackingCallback;
class LoggerRegistrationCallback;
class LogDispatchData;
namespace base {
class Storage;
class RegisteredLoggers;
class PerformanceTracker;
class MessageBuilder;
class Writer;
class PErrorWriter;
class LogDispatcher;
class DefaultLogBuilder;
class DefaultLogDispatchCallback;
#if ELPP_ASYNC_LOGGING
class AsyncLogDispatchCallback;
class AsyncDispatchWorker;
Y
youny626 已提交
515
#endif  // ELPP_ASYNC_LOGGING
516 517 518 519 520 521 522 523 524 525 526 527 528
class DefaultPerformanceTrackingCallback;
}  // namespace base
}  // namespace el
/// @brief Easylogging++ entry namespace
namespace el {
/// @brief Namespace containing base/internal functionality used by Easylogging++
namespace base {
/// @brief Data types used by Easylogging++
namespace type {
#undef ELPP_LITERAL
#undef ELPP_STRLEN
#undef ELPP_COUT
#if defined(ELPP_UNICODE)
Y
youny626 已提交
529 530 531 532 533 534 535
#define ELPP_LITERAL(txt) L##txt
#define ELPP_STRLEN wcslen
#if defined ELPP_CUSTOM_COUT
#define ELPP_COUT ELPP_CUSTOM_COUT
#else
#define ELPP_COUT std::wcout
#endif  // defined ELPP_CUSTOM_COUT
536 537 538 539 540 541
typedef wchar_t char_t;
typedef std::wstring string_t;
typedef std::wstringstream stringstream_t;
typedef std::wfstream fstream_t;
typedef std::wostream ostream_t;
#else
Y
youny626 已提交
542 543 544 545 546 547 548
#define ELPP_LITERAL(txt) txt
#define ELPP_STRLEN strlen
#if defined ELPP_CUSTOM_COUT
#define ELPP_COUT ELPP_CUSTOM_COUT
#else
#define ELPP_COUT std::cout
#endif  // defined ELPP_CUSTOM_COUT
549 550 551 552 553 554 555
typedef char char_t;
typedef std::string string_t;
typedef std::stringstream stringstream_t;
typedef std::fstream fstream_t;
typedef std::ostream ostream_t;
#endif  // defined(ELPP_UNICODE)
#if defined(ELPP_CUSTOM_COUT_LINE)
Y
youny626 已提交
556
#define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine)
557
#else
Y
youny626 已提交
558 559
#define ELPP_COUT_LINE(logLine) logLine << std::flush
#endif  // defined(ELPP_CUSTOM_COUT_LINE)
560 561 562 563 564 565 566 567 568 569 570 571 572 573
typedef unsigned int EnumType;
typedef unsigned short VerboseLevel;
typedef unsigned long int LineNumber;
typedef std::shared_ptr<base::Storage> StoragePointer;
typedef std::shared_ptr<LogDispatchCallback> LogDispatchCallbackPtr;
typedef std::shared_ptr<PerformanceTrackingCallback> PerformanceTrackingCallbackPtr;
typedef std::shared_ptr<LoggerRegistrationCallback> LoggerRegistrationCallbackPtr;
typedef std::unique_ptr<el::base::PerformanceTracker> PerformanceTrackerPtr;
}  // namespace type
/// @brief Internal helper class that prevent copy constructor for class
///
/// @detail When using this class simply inherit it privately
class NoCopy {
 protected:
Y
youny626 已提交
574 575 576
    NoCopy(void) {
    }

577
 private:
Y
youny626 已提交
578 579 580
    NoCopy(const NoCopy&);
    NoCopy&
    operator=(const NoCopy&);
581 582 583 584 585 586 587
};
/// @brief Internal helper class that makes all default constructors private.
///
/// @detail This prevents initializing class making it static unless an explicit constructor is declared.
/// When using this class simply inherit it privately
class StaticClass {
 private:
Y
youny626 已提交
588 589 590 591
    StaticClass(void);
    StaticClass(const StaticClass&);
    StaticClass&
    operator=(const StaticClass&);
592 593 594 595 596 597 598
};
}  // namespace base
/// @brief Represents enumeration for severity level used to determine level of logging
///
/// @detail With Easylogging++, developers may disable or enable any level regardless of
/// what the severity is. Or they can choose to log using hierarchical logging flag
enum class Level : base::type::EnumType {
Y
youny626 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels
    Global = 1,
    /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs.
    Trace = 2,
    /// @brief Informational events most useful for developers to debug application
    Debug = 4,
    /// @brief Severe error information that will presumably abort application
    Fatal = 8,
    /// @brief Information representing errors in application but application will keep running
    Error = 16,
    /// @brief Useful when application has potentially harmful situtaions
    Warning = 32,
    /// @brief Information that can be highly useful and vary with verbose logging level.
    Verbose = 64,
    /// @brief Mainly useful to represent current progress of application
    Info = 128,
    /// @brief Represents unknown level
    Unknown = 1010
617
};
Y
youny626 已提交
618
}  // namespace el
619
namespace std {
Y
youny626 已提交
620 621
template <>
struct hash<el::Level> {
622
 public:
Y
youny626 已提交
623 624 625 626
    std::size_t
    operator()(const el::Level& l) const {
        return hash<el::base::type::EnumType>{}(static_cast<el::base::type::EnumType>(l));
    }
627
};
Y
youny626 已提交
628
}  // namespace std
629 630 631 632
namespace el {
/// @brief Static class that contains helper functions for el::Level
class LevelHelper : base::StaticClass {
 public:
Y
youny626 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
    /// @brief Represents minimum valid level. Useful when iterating through enum.
    static const base::type::EnumType kMinValid = static_cast<base::type::EnumType>(Level::Trace);
    /// @brief Represents maximum valid level. This is used internally and you should not need it.
    static const base::type::EnumType kMaxValid = static_cast<base::type::EnumType>(Level::Info);
    /// @brief Casts level to int, useful for iterating through enum.
    static base::type::EnumType
    castToInt(Level level) {
        return static_cast<base::type::EnumType>(level);
    }
    /// @brief Casts int(ushort) to level, useful for iterating through enum.
    static Level
    castFromInt(base::type::EnumType l) {
        return static_cast<Level>(l);
    }
    /// @brief Converts level to associated const char*
    /// @return Upper case string based level.
    static const char*
    convertToString(Level level);
    /// @brief Converts from levelStr to Level
    /// @param levelStr Upper case string based level.
    ///        Lower case is also valid but providing upper case is recommended.
    static Level
    convertFromString(const char* levelStr);
    /// @brief Applies specified function to each level starting from startIndex
    /// @param startIndex initial value to start the iteration from. This is passed as pointer and
    ///        is left-shifted so this can be used inside function (fn) to represent current level.
    /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through
    /// levels.
    static void
    forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn);
663 664 665 666
};
/// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect
/// of logging
enum class ConfigurationType : base::type::EnumType {
Y
youny626 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    /// @brief Determines whether or not corresponding level and logger of logging is enabled
    /// You may disable all logs by using el::Level::Global
    Enabled = 1,
    /// @brief Whether or not to write corresponding log to log file
    ToFile = 2,
    /// @brief Whether or not to write corresponding level and logger log to standard output.
    /// By standard output meaning termnal, command prompt etc
    ToStandardOutput = 4,
    /// @brief Determines format of logging corresponding level and logger.
    Format = 8,
    /// @brief Determines log file (full path) to write logs to for correponding level and logger
    Filename = 16,
    /// @brief Specifies precision of the subsecond part. It should be within range (1-6).
    SubsecondPrecision = 32,
    /// @brief Alias of SubsecondPrecision (for backward compatibility)
    MillisecondsWidth = SubsecondPrecision,
    /// @brief Determines whether or not performance tracking is enabled.
    ///
    /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger
    PerformanceTracking = 64,
    /// @brief Specifies log file max size.
    ///
    /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will
    /// be truncated and re-initiated.
    MaxLogFileSize = 128,
    /// @brief Specifies number of log entries to hold until we flush pending log data
    LogFlushThreshold = 256,
    /// @brief Represents unknown configuration
    Unknown = 1010
696 697 698 699
};
/// @brief Static class that contains helper functions for el::ConfigurationType
class ConfigurationTypeHelper : base::StaticClass {
 public:
Y
youny626 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    /// @brief Represents minimum valid configuration type. Useful when iterating through enum.
    static const base::type::EnumType kMinValid = static_cast<base::type::EnumType>(ConfigurationType::Enabled);
    /// @brief Represents maximum valid configuration type. This is used internally and you should not need it.
    static const base::type::EnumType kMaxValid = static_cast<base::type::EnumType>(ConfigurationType::MaxLogFileSize);
    /// @brief Casts configuration type to int, useful for iterating through enum.
    static base::type::EnumType
    castToInt(ConfigurationType configurationType) {
        return static_cast<base::type::EnumType>(configurationType);
    }
    /// @brief Casts int(ushort) to configurationt type, useful for iterating through enum.
    static ConfigurationType
    castFromInt(base::type::EnumType c) {
        return static_cast<ConfigurationType>(c);
    }
    /// @brief Converts configuration type to associated const char*
    /// @returns Upper case string based configuration type.
    static const char*
    convertToString(ConfigurationType configurationType);
    /// @brief Converts from configStr to ConfigurationType
    /// @param configStr Upper case string based configuration type.
    ///        Lower case is also valid but providing upper case is recommended.
    static ConfigurationType
    convertFromString(const char* configStr);
    /// @brief Applies specified function to each configuration type starting from startIndex
    /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted
    ///        so this can be used inside function (fn) to represent current configuration type.
    /// @param fn function to apply with each configuration type.
    ///        This bool represent whether or not to stop iterating through configurations.
    static inline void
    forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn);
730 731 732
};
/// @brief Flags used while writing logs. This flags are set by user
enum class LoggingFlag : base::type::EnumType {
Y
youny626 已提交
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    /// @brief Makes sure we have new line for each container log entry
    NewLineForContainer = 1,
    /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose
    /// logging is allowed via that module.
    AllowVerboseIfModuleNotSpecified = 2,
    /// @brief When handling crashes by default, detailed crash reason will be logged as well
    LogDetailedCrashReason = 4,
    /// @brief Allows to disable application abortion when logged using FATAL level
    DisableApplicationAbortOnFatalLog = 8,
    /// @brief Flushes log with every log-entry (performance sensative) - Disabled by default
    ImmediateFlush = 16,
    /// @brief Enables strict file rolling
    StrictLogFileSizeCheck = 32,
    /// @brief Make terminal output colorful for supported terminals
    ColoredTerminalOutput = 64,
    /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network")
    MultiLoggerSupport = 128,
    /// @brief Disables comparing performance tracker's checkpoints
    DisablePerformanceTrackingCheckpointComparison = 256,
    /// @brief Disable VModules
    DisableVModules = 512,
    /// @brief Disable VModules extensions
    DisableVModulesExtensions = 1024,
    /// @brief Enables hierarchical logging
    HierarchicalLogging = 2048,
    /// @brief Creates logger automatically when not available
    CreateLoggerAutomatically = 4096,
    /// @brief Adds spaces b/w logs that separated by left-shift operator
    AutoSpacing = 8192,
    /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only)
    FixedTimeFormat = 16384,
    // @brief Ignore SIGINT or crash
    IgnoreSigInt = 32768,
766 767 768 769
};
namespace base {
/// @brief Namespace containing constants used internally.
namespace consts {
Y
youny626 已提交
770 771 772 773 774
static const char kFormatSpecifierCharValue = 'v';
static const char kFormatSpecifierChar = '%';
static const unsigned int kMaxLogPerCounter = 100000;
static const unsigned int kMaxLogPerContainer = 100;
static const unsigned int kDefaultSubsecondPrecision = 3;
775 776

#ifdef ELPP_DEFAULT_LOGGER
Y
youny626 已提交
777
static const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER;
778
#else
Y
youny626 已提交
779
static const char* kDefaultLoggerId = "default";
780 781 782 783
#endif

#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
#ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER
Y
youny626 已提交
784
static const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER;
785
#else
Y
youny626 已提交
786 787
static const char* kPerformanceLoggerId = "performance";
#endif  // ELPP_DEFAULT_PERFORMANCE_LOGGER
788 789 790
#endif

#if defined(ELPP_SYSLOG)
Y
youny626 已提交
791
static const char* kSysLogLoggerId = "syslog";
792 793 794
#endif  // defined(ELPP_SYSLOG)

#if ELPP_OS_WINDOWS
Y
youny626 已提交
795
static const char* kFilePathSeperator = "\\";
796
#else
Y
youny626 已提交
797
static const char* kFilePathSeperator = "/";
798 799
#endif  // ELPP_OS_WINDOWS

Y
youny626 已提交
800 801 802
static const std::size_t kSourceFilenameMaxLength = 100;
static const std::size_t kSourceLineMaxLength = 10;
static const Level kPerformanceTrackerDefaultLevel = Level::Info;
803
const struct {
Y
youny626 已提交
804 805 806 807 808
    double value;
    const base::type::char_t* unit;
} kTimeFormats[] = {{1000.0f, ELPP_LITERAL("us")},    {1000.0f, ELPP_LITERAL("ms")},  {60.0f, ELPP_LITERAL("seconds")},
                    {60.0f, ELPP_LITERAL("minutes")}, {24.0f, ELPP_LITERAL("hours")}, {7.0f, ELPP_LITERAL("days")}};
static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]);
809
const struct {
Y
youny626 已提交
810 811 812 813
    int numb;
    const char* name;
    const char* brief;
    const char* detail;
814
} kCrashSignals[] = {
Y
youny626 已提交
815 816 817 818 819 820 821 822 823 824
    // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..)
    {SIGABRT, "SIGABRT", "Abnormal termination", "Program was abnormally terminated."},
    {SIGFPE, "SIGFPE", "Erroneous arithmetic operation",
     "Arithemetic operation issue such as division by zero or operation resulting in overflow."},
    {SIGILL, "SIGILL", "Illegal instruction",
     "Generally due to a corruption in the code or to an attempt to execute data."},
    {SIGSEGV, "SIGSEGV", "Invalid access to memory",
     "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory."},
    {SIGINT, "SIGINT", "Interactive attention signal",
     "Interruption generated (generally) by user or operating system."},
825
};
Y
youny626 已提交
826
static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]);
827 828 829 830
}  // namespace consts
}  // namespace base
typedef std::function<void(const char*, std::size_t, Level level)> PreRollOutCallback;
namespace base {
Y
youny626 已提交
831 832 833
static inline void
defaultPreRollOutCallback(const char*, std::size_t, Level level) {
}
834 835
/// @brief Enum to represent timestamp unit
enum class TimestampUnit : base::type::EnumType {
Y
youny626 已提交
836 837 838 839 840 841
    Microsecond = 0,
    Millisecond = 1,
    Second = 2,
    Minute = 3,
    Hour = 4,
    Day = 5
842 843 844
};
/// @brief Format flags used to determine specifiers that are active for performance improvements.
enum class FormatFlags : base::type::EnumType {
Y
youny626 已提交
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    DateTime = 1 << 1,
    LoggerId = 1 << 2,
    File = 1 << 3,
    Line = 1 << 4,
    Location = 1 << 5,
    Function = 1 << 6,
    User = 1 << 7,
    Host = 1 << 8,
    LogMessage = 1 << 9,
    VerboseLevel = 1 << 10,
    AppName = 1 << 11,
    ThreadId = 1 << 12,
    Level = 1 << 13,
    FileBase = 1 << 14,
    LevelShort = 1 << 15
860 861 862 863
};
/// @brief A subsecond precision class containing actual width and offset of the subsecond part
class SubsecondPrecision {
 public:
Y
youny626 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876
    SubsecondPrecision(void) {
        init(base::consts::kDefaultSubsecondPrecision);
    }
    explicit SubsecondPrecision(int width) {
        init(width);
    }
    bool
    operator==(const SubsecondPrecision& ssPrec) {
        return m_width == ssPrec.m_width && m_offset == ssPrec.m_offset;
    }
    int m_width;
    unsigned int m_offset;

877
 private:
Y
youny626 已提交
878 879
    void
    init(int width);
880 881 882 883 884 885 886
};
/// @brief Type alias of SubsecondPrecision
typedef SubsecondPrecision MillisecondsWidth;
/// @brief Namespace containing utility functions/static classes used internally
namespace utils {
/// @brief Deletes memory safely and points to null
template <typename T>
Y
youny626 已提交
887
static typename std::enable_if<std::is_pointer<T*>::value, void>::type
888
safeDelete(T*& pointer) {
Y
youny626 已提交
889 890 891 892
    if (pointer == nullptr)
        return;
    delete pointer;
    pointer = nullptr;
893
}
Y
youny626 已提交
894 895
/// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise
/// operation Use these function as <pre>flag = bitwise::Or<MyEnum>(MyEnum::val1, flag);</pre>
896 897
namespace bitwise {
template <typename Enum>
Y
youny626 已提交
898 899 900
static inline base::type::EnumType
And(Enum e, base::type::EnumType flag) {
    return static_cast<base::type::EnumType>(flag) & static_cast<base::type::EnumType>(e);
901 902
}
template <typename Enum>
Y
youny626 已提交
903 904 905
static inline base::type::EnumType
Not(Enum e, base::type::EnumType flag) {
    return static_cast<base::type::EnumType>(flag) & ~(static_cast<base::type::EnumType>(e));
906 907
}
template <typename Enum>
Y
youny626 已提交
908 909 910
static inline base::type::EnumType
Or(Enum e, base::type::EnumType flag) {
    return static_cast<base::type::EnumType>(flag) | static_cast<base::type::EnumType>(e);
911 912 913
}
}  // namespace bitwise
template <typename Enum>
Y
youny626 已提交
914 915 916
static inline void
addFlag(Enum e, base::type::EnumType* flag) {
    *flag = base::utils::bitwise::Or<Enum>(e, *flag);
917 918
}
template <typename Enum>
Y
youny626 已提交
919 920 921
static inline void
removeFlag(Enum e, base::type::EnumType* flag) {
    *flag = base::utils::bitwise::Not<Enum>(e, *flag);
922 923
}
template <typename Enum>
Y
youny626 已提交
924 925 926
static inline bool
hasFlag(Enum e, base::type::EnumType flag) {
    return base::utils::bitwise::And<Enum>(e, flag) > 0x0;
927 928 929 930
}
}  // namespace utils
namespace threading {
#if ELPP_THREADING_ENABLED
Y
youny626 已提交
931
#if !ELPP_USE_STD_THREADING
932 933 934 935
namespace internal {
/// @brief A mutex wrapper for compiler that dont yet support std::recursive_mutex
class Mutex : base::NoCopy {
 public:
Y
youny626 已提交
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    Mutex(void) {
#if ELPP_OS_UNIX
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&m_underlyingMutex, &attr);
        pthread_mutexattr_destroy(&attr);
#elif ELPP_OS_WINDOWS
        InitializeCriticalSection(&m_underlyingMutex);
#endif  // ELPP_OS_UNIX
    }

    virtual ~Mutex(void) {
#if ELPP_OS_UNIX
        pthread_mutex_destroy(&m_underlyingMutex);
#elif ELPP_OS_WINDOWS
        DeleteCriticalSection(&m_underlyingMutex);
#endif  // ELPP_OS_UNIX
    }

    inline void
    lock(void) {
#if ELPP_OS_UNIX
        pthread_mutex_lock(&m_underlyingMutex);
#elif ELPP_OS_WINDOWS
        EnterCriticalSection(&m_underlyingMutex);
#endif  // ELPP_OS_UNIX
    }

    inline bool
    try_lock(void) {
#if ELPP_OS_UNIX
        return (pthread_mutex_trylock(&m_underlyingMutex) == 0);
#elif ELPP_OS_WINDOWS
        return TryEnterCriticalSection(&m_underlyingMutex);
#endif  // ELPP_OS_UNIX
    }

    inline void
    unlock(void) {
#if ELPP_OS_UNIX
        pthread_mutex_unlock(&m_underlyingMutex);
#elif ELPP_OS_WINDOWS
        LeaveCriticalSection(&m_underlyingMutex);
#endif  // ELPP_OS_UNIX
    }
982 983

 private:
Y
youny626 已提交
984 985 986 987 988
#if ELPP_OS_UNIX
    pthread_mutex_t m_underlyingMutex;
#elif ELPP_OS_WINDOWS
    CRITICAL_SECTION m_underlyingMutex;
#endif  // ELPP_OS_UNIX
989 990 991 992 993
};
/// @brief Scoped lock for compiler that dont yet support std::lock_guard
template <typename M>
class ScopedLock : base::NoCopy {
 public:
Y
youny626 已提交
994 995 996 997 998 999 1000 1001 1002
    explicit ScopedLock(M& mutex) {
        m_mutex = &mutex;
        m_mutex->lock();
    }

    virtual ~ScopedLock(void) {
        m_mutex->unlock();
    }

1003
 private:
Y
youny626 已提交
1004 1005
    M* m_mutex;
    ScopedLock(void);
1006
};
Y
youny626 已提交
1007
}  // namespace internal
1008 1009
typedef base::threading::internal::Mutex Mutex;
typedef base::threading::internal::ScopedLock<base::threading::Mutex> ScopedLock;
Y
youny626 已提交
1010
#else
1011 1012
typedef std::recursive_mutex Mutex;
typedef std::lock_guard<base::threading::Mutex> ScopedLock;
Y
youny626 已提交
1013
#endif  // !ELPP_USE_STD_THREADING
1014 1015 1016 1017 1018
#else
namespace internal {
/// @brief Mutex wrapper used when multi-threading is disabled.
class NoMutex : base::NoCopy {
 public:
Y
youny626 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    NoMutex(void) {
    }
    inline void
    lock(void) {
    }
    inline bool
    try_lock(void) {
        return true;
    }
    inline void
    unlock(void) {
    }
1031 1032 1033 1034 1035
};
/// @brief Lock guard wrapper used when multi-threading is disabled.
template <typename Mutex>
class NoScopedLock : base::NoCopy {
 public:
Y
youny626 已提交
1036 1037 1038 1039 1040
    explicit NoScopedLock(Mutex&) {
    }
    virtual ~NoScopedLock(void) {
    }

1041
 private:
Y
youny626 已提交
1042
    NoScopedLock(void);
1043 1044 1045 1046 1047 1048 1049 1050
};
}  // namespace internal
typedef base::threading::internal::NoMutex Mutex;
typedef base::threading::internal::NoScopedLock<base::threading::Mutex> ScopedLock;
#endif  // ELPP_THREADING_ENABLED
/// @brief Base of thread safe class, this class is inheritable-only
class ThreadSafe {
 public:
Y
youny626 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    virtual inline void
    acquireLock(void) ELPP_FINAL {
        m_mutex.lock();
    }
    virtual inline void
    releaseLock(void) ELPP_FINAL {
        m_mutex.unlock();
    }
    virtual inline base::threading::Mutex&
    lock(void) ELPP_FINAL {
        return m_mutex;
    }

1064
 protected:
Y
youny626 已提交
1065 1066 1067 1068 1069
    ThreadSafe(void) {
    }
    virtual ~ThreadSafe(void) {
    }

1070
 private:
Y
youny626 已提交
1071
    base::threading::Mutex m_mutex;
1072 1073 1074
};

#if ELPP_THREADING_ENABLED
Y
youny626 已提交
1075
#if !ELPP_USE_STD_THREADING
1076
/// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned.
Y
youny626 已提交
1077 1078 1079 1080 1081 1082 1083
static std::string
getCurrentThreadId(void) {
    std::stringstream ss;
#if (ELPP_OS_WINDOWS)
    ss << GetCurrentThreadId();
#endif  // (ELPP_OS_WINDOWS)
    return ss.str();
1084
}
Y
youny626 已提交
1085
#else
1086
/// @brief Gets ID of currently running threading using std::this_thread::get_id()
Y
youny626 已提交
1087 1088 1089 1090 1091
static std::string
getCurrentThreadId(void) {
    std::stringstream ss;
    ss << std::this_thread::get_id();
    return ss.str();
1092
}
Y
youny626 已提交
1093
#endif  // !ELPP_USE_STD_THREADING
1094
#else
Y
youny626 已提交
1095 1096 1097
static inline std::string
getCurrentThreadId(void) {
    return std::string();
1098 1099 1100 1101 1102 1103
}
#endif  // ELPP_THREADING_ENABLED
}  // namespace threading
namespace utils {
class File : base::StaticClass {
 public:
Y
youny626 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
    /// @brief Creates new out file stream for specified filename.
    /// @return Pointer to newly created fstream or nullptr
    static base::type::fstream_t*
    newFileStream(const std::string& filename);

    /// @brief Gets size of file provided in stream
    static std::size_t
    getSizeOfFile(base::type::fstream_t* fs);

    /// @brief Determines whether or not provided path exist in current file system
    static bool
    pathExists(const char* path, bool considerFile = false);

    /// @brief Creates specified path on file system
    /// @param path Path to create.
    static bool
    createPath(const std::string& path);
    /// @brief Extracts path of filename with leading slash
    static std::string
    extractPathFromFilename(const std::string& fullPath, const char* seperator = base::consts::kFilePathSeperator);
    /// @brief builds stripped filename and puts it in buff
    static void
    buildStrippedFilename(const char* filename, char buff[],
                          std::size_t limit = base::consts::kSourceFilenameMaxLength);
    /// @brief builds base filename and puts it in buff
    static void
    buildBaseFilename(const std::string& fullPath, char buff[],
                      std::size_t limit = base::consts::kSourceFilenameMaxLength,
                      const char* seperator = base::consts::kFilePathSeperator);
1133 1134 1135 1136
};
/// @brief String utilities helper class used internally. You should not use it.
class Str : base::StaticClass {
 public:
Y
youny626 已提交
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    /// @brief Checks if character is digit. Dont use libc implementation of it to prevent locale issues.
    static inline bool
    isDigit(char c) {
        return c >= '0' && c <= '9';
    }

    /// @brief Matches wildcards, '*' and '?' only supported.
    static bool
    wildCardMatch(const char* str, const char* pattern);

    static std::string&
    ltrim(std::string& str);
    static std::string&
    rtrim(std::string& str);
    static std::string&
    trim(std::string& str);

    /// @brief Determines whether or not str starts with specified string
    /// @param str String to check
    /// @param start String to check against
    /// @return Returns true if starts with specified string, false otherwise
    static bool
    startsWith(const std::string& str, const std::string& start);

    /// @brief Determines whether or not str ends with specified string
    /// @param str String to check
    /// @param end String to check against
    /// @return Returns true if ends with specified string, false otherwise
    static bool
    endsWith(const std::string& str, const std::string& end);

    /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance.
    /// @param [in,out] str String to replace from
    /// @param replaceWhat Character to replace
    /// @param replaceWith Character to replace with
    /// @return Modified version of str
    static std::string&
    replaceAll(std::string& str, char replaceWhat, char replaceWith);

    /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place
    /// @param str String to replace from
    /// @param replaceWhat Character to replace
    /// @param replaceWith Character to replace with
    /// @return Modified (original) str
    static std::string&
    replaceAll(std::string& str, const std::string& replaceWhat, const std::string& replaceWith);

    static void
    replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
                           const base::type::string_t& replaceWith);
1187
#if defined(ELPP_UNICODE)
Y
youny626 已提交
1188 1189 1190
    static void
    replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
                           const std::string& replaceWith);
1191
#endif  // defined(ELPP_UNICODE)
Y
youny626 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    /// @brief Converts string to uppercase
    /// @param str String to convert
    /// @return Uppercase string
    static std::string&
    toUpper(std::string& str);

    /// @brief Compares cstring equality - uses strcmp
    static bool
    cStringEq(const char* s1, const char* s2);

    /// @brief Compares cstring equality (case-insensitive) - uses toupper(char)
    /// Dont use strcasecmp because of CRT (VC++)
    static bool
    cStringCaseEq(const char* s1, const char* s2);

    /// @brief Returns true if c exist in str
    static bool
    contains(const char* str, char c);

    static char*
    convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true);
    static char*
    addToBuff(const char* str, char* buf, const char* bufLim);
    static char*
    clearBuff(char buff[], std::size_t lim);

    /// @brief Converst wchar* to char*
    ///        NOTE: Need to free return value after use!
    static char*
    wcharPtrToCharPtr(const wchar_t* line);
1222 1223 1224 1225 1226
};
/// @brief Operating System helper static class used internally. You should not use it.
class OS : base::StaticClass {
 public:
#if ELPP_OS_WINDOWS
Y
youny626 已提交
1227 1228 1229 1230 1231 1232
    /// @brief Gets environment variables for Windows based OS.
    ///        We are not using <code>getenv(const char*)</code> because of CRT deprecation
    /// @param varname Variable name to get environment variable value for
    /// @return If variable exist the value of it otherwise nullptr
    static const char*
    getWindowsEnvironmentVariable(const char* varname);
1233 1234
#endif  // ELPP_OS_WINDOWS
#if ELPP_OS_ANDROID
Y
youny626 已提交
1235 1236 1237
    /// @brief Reads android property value
    static std::string
    getProperty(const char* prop);
1238

Y
youny626 已提交
1239 1240 1241
    /// @brief Reads android device name
    static std::string
    getDeviceName(void);
1242 1243
#endif  // ELPP_OS_ANDROID

Y
youny626 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
    /// @brief Runs command on terminal and returns the output.
    ///
    /// @detail This is applicable only on unix based systems, for all other OS, an empty string is returned.
    /// @param command Bash command
    /// @return Result of bash output or empty string if no result found.
    static const std::string
    getBashOutput(const char* command);

    /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++)
    /// @param variableName Environment variable name
    /// @param defaultVal If no environment variable or value found the value to return by default
    /// @param alternativeBashCommand If environment variable not found what would be alternative bash command
    ///        in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami'
    static std::string
    getEnvironmentVariable(const char* variableName, const char* defaultVal,
                           const char* alternativeBashCommand = nullptr);
    /// @brief Gets current username.
    static std::string
    currentUser(void);

    /// @brief Gets current host name or computer name.
    ///
    /// @detail For android systems this is device name with its manufacturer and model seperated by hyphen
    static std::string
    currentHost(void);
    /// @brief Whether or not terminal supports colors
    static bool
    termSupportsColor(void);
1272 1273 1274 1275
};
/// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str
class DateTime : base::StaticClass {
 public:
Y
youny626 已提交
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current
    /// microsecond.
    ///
    /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a seperate implementation is
    /// provided
    /// @param [in,out] tv Pointer that gets updated
    static void
    gettimeofday(struct timeval* tv);

    /// @brief Gets current date and time with a subsecond part.
    /// @param format User provided date/time format
    /// @param ssPrec A pointer to base::SubsecondPrecision from configuration (non-null)
    /// @returns string based date time in specified format.
    static std::string
    getDateTime(const char* format, const base::SubsecondPrecision* ssPrec);

    /// @brief Converts timeval (struct from ctime) to string using specified format and subsecond precision
    static std::string
    timevalToString(struct timeval tval, const char* format, const el::base::SubsecondPrecision* ssPrec);

    /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc
    static base::type::string_t
    formatTime(unsigned long long time, base::TimestampUnit timestampUnit);

    /// @brief Gets time difference in milli/micro second depending on timestampUnit
    static unsigned long long
    getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
                      base::TimestampUnit timestampUnit);

    static struct ::tm*
    buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo);
1307 1308

 private:
Y
youny626 已提交
1309 1310 1311
    static char*
    parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, std::size_t msec,
                const base::SubsecondPrecision* ssPrec);
1312 1313 1314 1315
};
/// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..)
class CommandLineArgs {
 public:
Y
youny626 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
    CommandLineArgs(void) {
        setArgs(0, static_cast<char**>(nullptr));
    }
    CommandLineArgs(int argc, const char** argv) {
        setArgs(argc, argv);
    }
    CommandLineArgs(int argc, char** argv) {
        setArgs(argc, argv);
    }
    virtual ~CommandLineArgs(void) {
    }
    /// @brief Sets arguments and parses them
    inline void
    setArgs(int argc, const char** argv) {
        setArgs(argc, const_cast<char**>(argv));
    }
    /// @brief Sets arguments and parses them
    void
    setArgs(int argc, char** argv);
    /// @brief Returns true if arguments contain paramKey with a value (seperated by '=')
    bool
    hasParamWithValue(const char* paramKey) const;
    /// @brief Returns value of arguments
    /// @see hasParamWithValue(const char*)
    const char*
    getParamValue(const char* paramKey) const;
    /// @brief Return true if arguments has a param (not having a value) i,e without '='
    bool
    hasParam(const char* paramKey) const;
    /// @brief Returns true if no params available. This exclude argv[0]
    bool
    empty(void) const;
    /// @brief Returns total number of arguments. This exclude argv[0]
    std::size_t
    size(void) const;
    friend base::type::ostream_t&
    operator<<(base::type::ostream_t& os, const CommandLineArgs& c);
1353 1354

 private:
Y
youny626 已提交
1355 1356 1357 1358
    int m_argc;
    char** m_argv;
    std::unordered_map<std::string, std::string> m_paramsWithValue;
    std::vector<std::string> m_params;
1359
};
Y
youny626 已提交
1360 1361
/// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr
/// type.
1362
///
Y
youny626 已提交
1363 1364 1365 1366
/// @detail Most of the functions are virtual final methods but anything implementing this abstract class should
/// implement unregisterAll() and deepCopy(const AbstractRegistry<T_Ptr, Container>&) and write registerNew() method
/// according to container and few more methods; get() to find element, unregister() to unregister single entry. Please
/// note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation.
1367 1368 1369
template <typename T_Ptr, typename Container>
class AbstractRegistry : public base::threading::ThreadSafe {
 public:
Y
youny626 已提交
1370 1371
    typedef typename Container::iterator iterator;
    typedef typename Container::const_iterator const_iterator;
1372

Y
youny626 已提交
1373 1374
    /// @brief Default constructor
    AbstractRegistry(void) {
1375 1376
    }

Y
youny626 已提交
1377 1378 1379 1380 1381 1382 1383
    /// @brief Move constructor that is useful for base classes
    AbstractRegistry(AbstractRegistry&& sr) {
        if (this == &sr) {
            return;
        }
        unregisterAll();
        m_list = std::move(sr.m_list);
1384 1385
    }

Y
youny626 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    bool
    operator==(const AbstractRegistry<T_Ptr, Container>& other) {
        if (size() != other.size()) {
            return false;
        }
        for (std::size_t i = 0; i < m_list.size(); ++i) {
            if (m_list.at(i) != other.m_list.at(i)) {
                return false;
            }
        }
1396 1397 1398
        return true;
    }

Y
youny626 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    bool
    operator!=(const AbstractRegistry<T_Ptr, Container>& other) {
        if (size() != other.size()) {
            return true;
        }
        for (std::size_t i = 0; i < m_list.size(); ++i) {
            if (m_list.at(i) != other.m_list.at(i)) {
                return true;
            }
        }
        return false;
1410 1411
    }

Y
youny626 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    /// @brief Assignment move operator
    AbstractRegistry&
    operator=(AbstractRegistry&& sr) {
        if (this == &sr) {
            return *this;
        }
        unregisterAll();
        m_list = std::move(sr.m_list);
        return *this;
    }
1422

Y
youny626 已提交
1423 1424
    virtual ~AbstractRegistry(void) {
    }
1425

Y
youny626 已提交
1426 1427 1428 1429 1430
    /// @return Iterator pointer from start of repository
    virtual inline iterator
    begin(void) ELPP_FINAL {
        return m_list.begin();
    }
1431

Y
youny626 已提交
1432 1433 1434 1435 1436
    /// @return Iterator pointer from end of repository
    virtual inline iterator
    end(void) ELPP_FINAL {
        return m_list.end();
    }
1437

Y
youny626 已提交
1438 1439 1440 1441 1442
    /// @return Constant iterator pointer from start of repository
    virtual inline const_iterator
    cbegin(void) const ELPP_FINAL {
        return m_list.cbegin();
    }
1443

Y
youny626 已提交
1444 1445 1446 1447 1448
    /// @return End of repository
    virtual inline const_iterator
    cend(void) const ELPP_FINAL {
        return m_list.cend();
    }
1449

Y
youny626 已提交
1450 1451 1452 1453 1454
    /// @return Whether or not repository is empty
    virtual inline bool
    empty(void) const ELPP_FINAL {
        return m_list.empty();
    }
1455

Y
youny626 已提交
1456 1457 1458 1459 1460
    /// @return Size of repository
    virtual inline std::size_t
    size(void) const ELPP_FINAL {
        return m_list.size();
    }
1461

Y
youny626 已提交
1462 1463 1464 1465 1466
    /// @brief Returns underlying container by reference
    virtual inline Container&
    list(void) ELPP_FINAL {
        return m_list;
    }
1467

Y
youny626 已提交
1468 1469 1470 1471 1472
    /// @brief Returns underlying container by constant reference.
    virtual inline const Container&
    list(void) const ELPP_FINAL {
        return m_list;
    }
1473

Y
youny626 已提交
1474 1475 1476
    /// @brief Unregisters all the pointers from current repository.
    virtual void
    unregisterAll(void) = 0;
1477 1478

 protected:
Y
youny626 已提交
1479 1480 1481 1482 1483 1484 1485
    virtual void
    deepCopy(const AbstractRegistry<T_Ptr, Container>&) = 0;
    void
    reinitDeepCopy(const AbstractRegistry<T_Ptr, Container>& sr) {
        unregisterAll();
        deepCopy(sr);
    }
1486 1487

 private:
Y
youny626 已提交
1488
    Container m_list;
1489 1490 1491 1492
};

/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version)
///
Y
youny626 已提交
1493 1494
/// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these
/// functions)
1495 1496 1497 1498 1499
///         of AbstractRegistry<T_Ptr, Container>. Any implementation of this class should be
///         explicitly (by using lock functions)
template <typename T_Ptr, typename T_Key = const char*>
class Registry : public AbstractRegistry<T_Ptr, std::unordered_map<T_Key, T_Ptr*>> {
 public:
Y
youny626 已提交
1500 1501
    typedef typename Registry<T_Ptr, T_Key>::iterator iterator;
    typedef typename Registry<T_Ptr, T_Key>::const_iterator const_iterator;
1502

Y
youny626 已提交
1503 1504
    Registry(void) {
    }
1505

Y
youny626 已提交
1506 1507 1508 1509 1510 1511
    /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor.
    Registry(const Registry& sr) : AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>() {
        if (this == &sr) {
            return;
        }
        this->reinitDeepCopy(sr);
1512 1513
    }

Y
youny626 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element
    /// @see unregisterAll()
    /// @see deepCopy(const AbstractRegistry&)
    Registry&
    operator=(const Registry& sr) {
        if (this == &sr) {
            return *this;
        }
        this->reinitDeepCopy(sr);
        return *this;
1524 1525
    }

Y
youny626 已提交
1526 1527 1528
    virtual ~Registry(void) {
        unregisterAll();
    }
1529 1530

 protected:
Y
youny626 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    virtual void
    unregisterAll(void) ELPP_FINAL {
        if (!this->empty()) {
            for (auto&& curr : this->list()) {
                base::utils::safeDelete(curr.second);
            }
            this->list().clear();
        }
    }

    /// @brief Registers new registry to repository.
    virtual void
    registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL {
        unregister(uniqKey);
        this->list().insert(std::make_pair(uniqKey, ptr));
    }

    /// @brief Unregisters single entry mapped to specified unique key
    void
    unregister(const T_Key& uniqKey) {
        T_Ptr* existing = get(uniqKey);
        if (existing != nullptr) {
            this->list().erase(uniqKey);
            base::utils::safeDelete(existing);
        }
    }

    /// @brief Gets pointer from repository. If none found, nullptr is returned.
    T_Ptr*
    get(const T_Key& uniqKey) {
        iterator it = this->list().find(uniqKey);
        return it == this->list().end() ? nullptr : it->second;
    }
1564 1565

 private:
Y
youny626 已提交
1566 1567 1568 1569 1570
    virtual void
    deepCopy(const AbstractRegistry<T_Ptr, std::unordered_map<T_Key, T_Ptr*>>& sr) ELPP_FINAL {
        for (const_iterator it = sr.cbegin(); it != sr.cend(); ++it) {
            registerNew(it->first, new T_Ptr(*it->second));
        }
1571 1572 1573 1574 1575
    }
};

/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version)
///
Y
youny626 已提交
1576 1577
/// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry<T_Ptr, Container>. Any implementation of this
/// class should be made thread-safe explicitly
1578 1579 1580
template <typename T_Ptr, typename Pred>
class RegistryWithPred : public AbstractRegistry<T_Ptr, std::vector<T_Ptr*>> {
 public:
Y
youny626 已提交
1581 1582
    typedef typename RegistryWithPred<T_Ptr, Pred>::iterator iterator;
    typedef typename RegistryWithPred<T_Ptr, Pred>::const_iterator const_iterator;
1583

Y
youny626 已提交
1584 1585
    RegistryWithPred(void) {
    }
1586

Y
youny626 已提交
1587 1588 1589
    virtual ~RegistryWithPred(void) {
        unregisterAll();
    }
1590

Y
youny626 已提交
1591 1592 1593 1594 1595 1596
    /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor.
    RegistryWithPred(const RegistryWithPred& sr) : AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>() {
        if (this == &sr) {
            return;
        }
        this->reinitDeepCopy(sr);
1597 1598
    }

Y
youny626 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element
    /// @see unregisterAll()
    /// @see deepCopy(const AbstractRegistry&)
    RegistryWithPred&
    operator=(const RegistryWithPred& sr) {
        if (this == &sr) {
            return *this;
        }
        this->reinitDeepCopy(sr);
        return *this;
1609 1610
    }

Y
youny626 已提交
1611 1612 1613 1614 1615 1616
    friend base::type::ostream_t&
    operator<<(base::type::ostream_t& os, const RegistryWithPred& sr) {
        for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) {
            os << ELPP_LITERAL("    ") << **it << ELPP_LITERAL("\n");
        }
        return os;
1617 1618 1619
    }

 protected:
Y
youny626 已提交
1620 1621 1622 1623 1624 1625 1626
    virtual void
    unregisterAll(void) ELPP_FINAL {
        if (!this->empty()) {
            for (auto&& curr : this->list()) {
                base::utils::safeDelete(curr);
            }
            this->list().clear();
1627 1628 1629
        }
    }

Y
youny626 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    virtual void
    unregister(T_Ptr*& ptr) ELPP_FINAL {
        if (ptr) {
            iterator iter = this->begin();
            for (; iter != this->end(); ++iter) {
                if (ptr == *iter) {
                    break;
                }
            }
            if (iter != this->end() && *iter != nullptr) {
                this->list().erase(iter);
                base::utils::safeDelete(*iter);
            }
        }
    }
1645

Y
youny626 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
    virtual inline void
    registerNew(T_Ptr* ptr) ELPP_FINAL {
        this->list().push_back(ptr);
    }

    /// @brief Gets pointer from repository with speicifed arguments. Arguments are passed to predicate
    /// in order to validate pointer.
    template <typename T, typename T2>
    T_Ptr*
    get(const T& arg1, const T2 arg2) {
        iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2));
        if (iter != this->list().end() && *iter != nullptr) {
            return *iter;
        }
        return nullptr;
1661 1662 1663
    }

 private:
Y
youny626 已提交
1664 1665 1666 1667 1668
    virtual void
    deepCopy(const AbstractRegistry<T_Ptr, std::vector<T_Ptr*>>& sr) {
        for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) {
            registerNew(new T_Ptr(**it));
        }
1669 1670 1671 1672
    }
};
class Utils {
 public:
Y
youny626 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
    template <typename T, typename TPtr>
    static bool
    installCallback(const std::string& id, std::unordered_map<std::string, TPtr>* mapT) {
        if (mapT->find(id) == mapT->end()) {
            mapT->insert(std::make_pair(id, TPtr(new T())));
            return true;
        }
        return false;
    }

    template <typename T, typename TPtr>
    static void
    uninstallCallback(const std::string& id, std::unordered_map<std::string, TPtr>* mapT) {
        if (mapT->find(id) != mapT->end()) {
            mapT->erase(id);
        }
    }

    template <typename T, typename TPtr>
    static T*
    callback(const std::string& id, std::unordered_map<std::string, TPtr>* mapT) {
        typename std::unordered_map<std::string, TPtr>::iterator iter = mapT->find(id);
        if (iter != mapT->end()) {
            return static_cast<T*>(iter->second.get());
        }
        return nullptr;
    }
1700 1701
};
}  // namespace utils
Y
youny626 已提交
1702
}  // namespace base
1703 1704 1705 1706 1707
/// @brief Base of Easylogging++ friendly class
///
/// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const`
class Loggable {
 public:
Y
youny626 已提交
1708 1709 1710 1711 1712
    virtual ~Loggable(void) {
    }
    virtual void
    log(el::base::type::ostream_t&) const = 0;

1713
 private:
Y
youny626 已提交
1714 1715 1716 1717 1718
    friend inline el::base::type::ostream_t&
    operator<<(el::base::type::ostream_t& os, const Loggable& loggable) {
        loggable.log(os);
        return os;
    }
1719 1720 1721 1722 1723
};
namespace base {
/// @brief Represents log format containing flags and date format. This is used internally to start initial log
class LogFormat : public Loggable {
 public:
Y
youny626 已提交
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
    LogFormat(void);
    LogFormat(Level level, const base::type::string_t& format);
    LogFormat(const LogFormat& logFormat);
    LogFormat(LogFormat&& logFormat);
    LogFormat&
    operator=(const LogFormat& logFormat);
    virtual ~LogFormat(void) {
    }
    bool
    operator==(const LogFormat& other);
1734

Y
youny626 已提交
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    /// @brief Updates format to be used while logging.
    /// @param userFormat User provided format
    void
    parseFromFormat(const base::type::string_t& userFormat);

    inline Level
    level(void) const {
        return m_level;
    }

    inline const base::type::string_t&
    userFormat(void) const {
        return m_userFormat;
    }

    inline const base::type::string_t&
    format(void) const {
        return m_format;
    }

    inline const std::string&
    dateTimeFormat(void) const {
        return m_dateTimeFormat;
    }
1759

Y
youny626 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768
    inline base::type::EnumType
    flags(void) const {
        return m_flags;
    }

    inline bool
    hasFlag(base::FormatFlags flag) const {
        return base::utils::hasFlag(flag, m_flags);
    }
1769

Y
youny626 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
    virtual void
    log(el::base::type::ostream_t& os) const {
        os << m_format;
    }

 protected:
    /// @brief Updates date time format if available in currFormat.
    /// @param index Index where %datetime, %date or %time was found
    /// @param [in,out] currFormat current format that is being used to format
    virtual void
    updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL;

    /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format
    /// and m_level
    virtual void
    updateFormatSpec(void) ELPP_FINAL;

    inline void
    addFlag(base::FormatFlags flag) {
        base::utils::addFlag(flag, &m_flags);
    }
1791 1792

 private:
Y
youny626 已提交
1793 1794 1795 1796 1797 1798 1799 1800
    Level m_level;
    base::type::string_t m_userFormat;
    base::type::string_t m_format;
    std::string m_dateTimeFormat;
    base::type::EnumType m_flags;
    std::string m_currentUser;
    std::string m_currentHost;
    friend class el::Logger;  // To resolve loggerId format specifier easily
1801 1802 1803 1804 1805 1806 1807 1808 1809
};
}  // namespace base
/// @brief Resolving function for format specifier
typedef std::function<std::string(const LogMessage*)> FormatSpecifierValueResolver;
/// @brief User-provided custom format specifier
/// @see el::Helpers::installCustomFormatSpecifier
/// @see FormatSpecifierValueResolver
class CustomFormatSpecifier {
 public:
Y
youny626 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver)
        : m_formatSpecifier(formatSpecifier), m_resolver(resolver) {
    }
    inline const char*
    formatSpecifier(void) const {
        return m_formatSpecifier;
    }
    inline const FormatSpecifierValueResolver&
    resolver(void) const {
        return m_resolver;
    }
    inline bool
    operator==(const char* formatSpecifier) {
        return strcmp(m_formatSpecifier, formatSpecifier) == 0;
    }
1825 1826

 private:
Y
youny626 已提交
1827 1828
    const char* m_formatSpecifier;
    FormatSpecifierValueResolver m_resolver;
1829 1830 1831
};
/// @brief Represents single configuration that has representing level, configuration type and a string based value.
///
Y
youny626 已提交
1832 1833
/// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside
/// quotes and will be parsed later.
1834 1835 1836 1837 1838 1839 1840
///
/// Consider some examples below:
///   * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true");
///   * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048");
///   * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log");
class Configuration : public Loggable {
 public:
Y
youny626 已提交
1841 1842 1843
    Configuration(const Configuration& c);
    Configuration&
    operator=(const Configuration& c);
1844

Y
youny626 已提交
1845 1846
    virtual ~Configuration(void) {
    }
1847

Y
youny626 已提交
1848 1849
    /// @brief Full constructor used to sets value of configuration
    Configuration(Level level, ConfigurationType configurationType, const std::string& value);
1850

Y
youny626 已提交
1851 1852 1853 1854 1855
    /// @brief Gets level of current configuration
    inline Level
    level(void) const {
        return m_level;
    }
1856

Y
youny626 已提交
1857 1858 1859 1860 1861
    /// @brief Gets configuration type of current configuration
    inline ConfigurationType
    configurationType(void) const {
        return m_configurationType;
    }
1862

Y
youny626 已提交
1863 1864 1865 1866 1867
    /// @brief Gets string based configuration value
    inline const std::string&
    value(void) const {
        return m_value;
    }
1868

Y
youny626 已提交
1869 1870 1871 1872 1873 1874 1875 1876
    /// @brief Set string based configuration value
    /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any
    /// integral values
    ///        use them in quotes. They will be parsed when configuring
    inline void
    setValue(const std::string& value) {
        m_value = value;
    }
1877

Y
youny626 已提交
1878 1879
    virtual void
    log(el::base::type::ostream_t& os) const;
1880

Y
youny626 已提交
1881 1882 1883 1884
    /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
    class Predicate {
     public:
        Predicate(Level level, ConfigurationType configurationType);
1885

Y
youny626 已提交
1886 1887
        bool
        operator()(const Configuration* conf) const;
1888

Y
youny626 已提交
1889 1890 1891 1892
     private:
        Level m_level;
        ConfigurationType m_configurationType;
    };
1893 1894

 private:
Y
youny626 已提交
1895 1896 1897
    Level m_level;
    ConfigurationType m_configurationType;
    std::string m_value;
1898 1899 1900 1901 1902 1903 1904
};

/// @brief Thread-safe Configuration repository
///
/// @detail This repository represents configurations for all the levels and configuration type mapped to a value.
class Configurations : public base::utils::RegistryWithPred<Configuration, Configuration::Predicate> {
 public:
Y
youny626 已提交
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
    /// @brief Default constructor with empty repository
    Configurations(void);

    /// @brief Constructor used to set configurations using configuration file.
    /// @param configurationFile Full path to configuration file
    /// @param useDefaultsForRemaining Lets you set the remaining configurations to default.
    /// @param base If provided, this configuration will be based off existing repository that this argument is pointing
    /// to.
    /// @see parseFromFile(const std::string&, Configurations* base)
    /// @see setRemainingToDefault()
    Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true,
                   Configurations* base = nullptr);

    virtual ~Configurations(void) {
    }

1921 1922 1923 1924
    /// @brief Parses configuration from file.
    /// @param configurationFile Full path to configuration file
    /// @param base Configurations to base new configuration repository off. This value is used when you want to use
    ///        existing Configurations to base all the values and then set rest of configuration via configuration file.
Y
youny626 已提交
1925 1926
    /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure
    /// you
1927
    ///         do not proceed without successful parse.
Y
youny626 已提交
1928 1929
    bool
    parseFromFile(const std::string& configurationFile, Configurations* base = nullptr);
1930 1931 1932 1933

    /// @brief Parse configurations from configuration string.
    ///
    /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary
Y
youny626 已提交
1934
    /// new line characters are provided.
1935 1936
    /// @param base Configurations to base new configuration repository off. This value is used when you want to use
    ///        existing Configurations to base all the values and then set rest of configuration via configuration text.
Y
youny626 已提交
1937 1938 1939 1940 1941
    /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure
    /// you
    ///         do not proceed without successful parse.
    bool
    parseFromText(const std::string& configurationsString, Configurations* base = nullptr);
1942

Y
youny626 已提交
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
    /// @brief Sets configuration based-off an existing configurations.
    /// @param base Pointer to existing configurations.
    void
    setFromBase(Configurations* base);

    /// @brief Determines whether or not specified configuration type exists in the repository.
    ///
    /// @detail Returns as soon as first level is found.
    /// @param configurationType Type of configuration to check existence for.
    bool
    hasConfiguration(ConfigurationType configurationType);

    /// @brief Determines whether or not specified configuration type exists for specified level
    /// @param level Level to check
    /// @param configurationType Type of configuration to check existence for.
    bool
    hasConfiguration(Level level, ConfigurationType configurationType);

    /// @brief Sets value of configuration for specified level.
    ///
    /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types
    /// ConfigurationType::SubsecondPrecision and ConfigurationType::PerformanceTracking will be ignored if not set for
    /// Level::Global because these configurations are not dependant on level.
    /// @param level Level to set configuration for (el::Level).
    /// @param configurationType Type of configuration (el::ConfigurationType)
    /// @param value A string based value. Regardless of what the data type of configuration is, it will always be
    /// string from users' point of view. This is then parsed later to be used internally.
    /// @see Configuration::setValue(const std::string& value)
    /// @see el::Level
    /// @see el::ConfigurationType
    void
    set(Level level, ConfigurationType configurationType, const std::string& value);

    /// @brief Sets single configuration based on other single configuration.
    /// @see set(Level level, ConfigurationType configurationType, const std::string& value)
    void
    set(Configuration* conf);

    inline Configuration*
    get(Level level, ConfigurationType configurationType) {
        base::threading::ScopedLock scopedLock(lock());
        return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType);
    }

    /// @brief Sets configuration for all levels.
    /// @param configurationType Type of configuration
    /// @param value String based value
    /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value)
    inline void
    setGlobally(ConfigurationType configurationType, const std::string& value) {
        setGlobally(configurationType, value, false);
    }

    /// @brief Clears repository so that all the configurations are unset
    inline void
    clear(void) {
        base::threading::ScopedLock scopedLock(lock());
        unregisterAll();
    }

    /// @brief Gets configuration file used in parsing this configurations.
    ///
    /// @detail If this repository was set manually or by text this returns empty string.
    inline const std::string&
    configurationFile(void) const {
        return m_configurationFile;
    }

    /// @brief Sets configurations to "factory based" configurations.
    void
    setToDefault(void);

    /// @brief Lets you set the remaining configurations to default.
    ///
    /// @detail By remaining, it means that the level/type a configuration does not exist for.
    /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file
    /// that sets configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set
    /// to default i.e, true. If you dont do this explicitly (either by calling this function or by using second param
    /// in Constructor and try to access a value, an error is thrown
    void
    setRemainingToDefault(void);

    /// @brief Parser used internally to parse configurations from file or text.
    ///
    /// @detail This class makes use of base::utils::Str.
    /// You should not need this unless you are working on some tool for Easylogging++
    class Parser : base::StaticClass {
     public:
        /// @brief Parses configuration from file.
        /// @param configurationFile Full path to configuration file
        /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
        /// @param base Configurations to base new configuration repository off. This value is used when you want to use
        ///        existing Configurations to base all the values and then set rest of configuration via configuration
        ///        file.
        /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make
        /// sure you
        ///         do not proceed without successful parse.
        static bool
        parseFromFile(const std::string& configurationFile, Configurations* sender, Configurations* base = nullptr);

        /// @brief Parse configurations from configuration string.
        ///
        /// @detail This configuration string has same syntax as configuration file contents. Make sure all the
        /// necessary new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you
        /// do not proceed without successful parse (This is recommended)
        /// @param configurationsString the configuration in plain text format
        /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
        /// @param base Configurations to base new configuration repository off. This value is used when you want to use
        ///        existing Configurations to base all the values and then set rest of configuration via configuration
        ///        text.
        /// @return True if successfully parsed, false otherwise.
        static bool
        parseFromText(const std::string& configurationsString, Configurations* sender, Configurations* base = nullptr);

     private:
        friend class el::Loggers;
        static void
        ignoreComments(std::string* line);
        static bool
        isLevel(const std::string& line);
        static bool
        isComment(const std::string& line);
        static inline bool
        isConfig(const std::string& line);
        static bool
        parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel,
                  Configurations* conf);
    };
2071 2072

 private:
Y
youny626 已提交
2073 2074 2075
    std::string m_configurationFile;
    bool m_isFromFile;
    friend class el::Loggers;
2076

Y
youny626 已提交
2077 2078 2079
    /// @brief Unsafely sets configuration if does not already exist
    void
    unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value);
2080

Y
youny626 已提交
2081 2082 2083
    /// @brief Thread unsafe set
    void
    unsafeSet(Level level, ConfigurationType configurationType, const std::string& value);
2084

Y
youny626 已提交
2085 2086 2087 2088
    /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true
    /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
    void
    setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
2089

Y
youny626 已提交
2090 2091 2092 2093
    /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true
    /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
    void
    unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
2094 2095 2096 2097 2098 2099 2100
};

namespace base {
typedef std::shared_ptr<base::type::fstream_t> FileStreamPtr;
typedef std::unordered_map<std::string, FileStreamPtr> LogStreamsReferenceMap;
/// @brief Configurations with data types.
///
Y
youny626 已提交
2101 2102
/// @detail el::Configurations have string based values. This is whats used internally in order to read correct
/// configurations. This is to perform faster while writing logs using correct configurations.
2103 2104 2105 2106
///
/// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class)
class TypedConfigurations : public base::threading::ThreadSafe {
 public:
Y
youny626 已提交
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
    /// @brief Constructor to initialize (construct) the object off el::Configurations
    /// @param configurations Configurations pointer/reference to base this typed configurations off.
    /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference()
    TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference);

    TypedConfigurations(const TypedConfigurations& other);

    virtual ~TypedConfigurations(void) {
    }

    const Configurations*
    configurations(void) const {
        return m_configurations;
    }

    bool
    enabled(Level level);
    bool
    toFile(Level level);
    const std::string&
    filename(Level level);
    bool
    toStandardOutput(Level level);
    const base::LogFormat&
    logFormat(Level level);
    const base::SubsecondPrecision&
    subsecondPrecision(Level level = Level::Global);
    const base::MillisecondsWidth&
    millisecondsWidth(Level level = Level::Global);
    bool
    performanceTracking(Level level = Level::Global);
    base::type::fstream_t*
    fileStream(Level level);
    std::size_t
    maxLogFileSize(Level level);
    std::size_t
    logFlushThreshold(Level level);
2144 2145

 private:
Y
youny626 已提交
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
    Configurations* m_configurations;
    std::unordered_map<Level, bool> m_enabledMap;
    std::unordered_map<Level, bool> m_toFileMap;
    std::unordered_map<Level, std::string> m_filenameMap;
    std::unordered_map<Level, bool> m_toStandardOutputMap;
    std::unordered_map<Level, base::LogFormat> m_logFormatMap;
    std::unordered_map<Level, base::SubsecondPrecision> m_subsecondPrecisionMap;
    std::unordered_map<Level, bool> m_performanceTrackingMap;
    std::unordered_map<Level, base::FileStreamPtr> m_fileStreamMap;
    std::unordered_map<Level, std::size_t> m_maxLogFileSizeMap;
    std::unordered_map<Level, std::size_t> m_logFlushThresholdMap;
    base::LogStreamsReferenceMap* m_logStreamsReference;

    friend class el::Helpers;
    friend class el::base::MessageBuilder;
    friend class el::base::Writer;
    friend class el::base::DefaultLogDispatchCallback;
    friend class el::base::LogDispatcher;

    template <typename Conf_T>
    inline Conf_T
    getConfigByVal(Level level, const std::unordered_map<Level, Conf_T>* confMap, const char* confName) {
        base::threading::ScopedLock scopedLock(lock());
        return unsafeGetConfigByVal(level, confMap, confName);  // This is not unsafe anymore - mutex locked in scope
    }

    template <typename Conf_T>
    inline Conf_T&
    getConfigByRef(Level level, std::unordered_map<Level, Conf_T>* confMap, const char* confName) {
        base::threading::ScopedLock scopedLock(lock());
        return unsafeGetConfigByRef(level, confMap, confName);  // This is not unsafe anymore - mutex locked in scope
2177 2178
    }

Y
youny626 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
    template <typename Conf_T>
    Conf_T
    unsafeGetConfigByVal(Level level, const std::unordered_map<Level, Conf_T>* confMap, const char* confName) {
        ELPP_UNUSED(confName);
        typename std::unordered_map<Level, Conf_T>::const_iterator it = confMap->find(level);
        if (it == confMap->end()) {
            try {
                return confMap->at(Level::Global);
            } catch (...) {
                ELPP_INTERNAL_ERROR("Unable to get configuration ["
                                        << confName << "] for level [" << LevelHelper::convertToString(level) << "]"
                                        << std::endl
                                        << "Please ensure you have properly configured logger.",
                                    false);
                return Conf_T();
            }
        }
        return it->second;
    }

    template <typename Conf_T>
    Conf_T&
    unsafeGetConfigByRef(Level level, std::unordered_map<Level, Conf_T>* confMap, const char* confName) {
        ELPP_UNUSED(confName);
        typename std::unordered_map<Level, Conf_T>::iterator it = confMap->find(level);
        if (it == confMap->end()) {
            try {
                return confMap->at(Level::Global);
            } catch (...) {
                ELPP_INTERNAL_ERROR("Unable to get configuration ["
                                        << confName << "] for level [" << LevelHelper::convertToString(level) << "]"
                                        << std::endl
                                        << "Please ensure you have properly configured logger.",
                                    false);
            }
        }
        return it->second;
    }
2217

Y
youny626 已提交
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
    template <typename Conf_T>
    void
    setValue(Level level, const Conf_T& value, std::unordered_map<Level, Conf_T>* confMap,
             bool includeGlobalLevel = true) {
        // If map is empty and we are allowed to add into generic level (Level::Global), do it!
        if (confMap->empty() && includeGlobalLevel) {
            confMap->insert(std::make_pair(Level::Global, value));
            return;
        }
        // If same value exist in generic level already, dont add it to explicit level
        typename std::unordered_map<Level, Conf_T>::iterator it = confMap->find(Level::Global);
        if (it != confMap->end() && it->second == value) {
            return;
        }
        // Now make sure we dont double up values if we really need to add it to explicit level
        it = confMap->find(level);
        if (it == confMap->end()) {
            // Value not found for level, add new
            confMap->insert(std::make_pair(level, value));
        } else {
            // Value found, just update value
            confMap->at(level) = value;
        }
    }

    void
    build(Configurations* configurations);
    unsigned long
    getULong(std::string confVal);
    std::string
    resolveFilename(const std::string& filename);
    void
    insertFile(Level level, const std::string& fullFilename);
    bool
    unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback);

    inline bool
    validateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) {
        base::threading::ScopedLock scopedLock(lock());
        return unsafeValidateFileRolling(level, preRollOutCallback);
    }
2259 2260 2261 2262
};
/// @brief Class that keeps record of current line hit for occasional logging
class HitCounter {
 public:
Y
youny626 已提交
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
    HitCounter(void) : m_filename(""), m_lineNumber(0), m_hitCounts(0) {
    }

    HitCounter(const char* filename, base::type::LineNumber lineNumber)
        : m_filename(filename), m_lineNumber(lineNumber), m_hitCounts(0) {
    }

    HitCounter(const HitCounter& hitCounter)
        : m_filename(hitCounter.m_filename),
          m_lineNumber(hitCounter.m_lineNumber),
          m_hitCounts(hitCounter.m_hitCounts) {
    }

    HitCounter&
    operator=(const HitCounter& hitCounter) {
        if (&hitCounter != this) {
            m_filename = hitCounter.m_filename;
            m_lineNumber = hitCounter.m_lineNumber;
            m_hitCounts = hitCounter.m_hitCounts;
        }
        return *this;
    }

    virtual ~HitCounter(void) {
    }

    /// @brief Resets location of current hit counter
    inline void
    resetLocation(const char* filename, base::type::LineNumber lineNumber) {
        m_filename = filename;
        m_lineNumber = lineNumber;
    }

    /// @brief Validates hit counts and resets it if necessary
    inline void
    validateHitCounts(std::size_t n) {
        if (m_hitCounts >= base::consts::kMaxLogPerCounter) {
            m_hitCounts = (n >= 1 ? base::consts::kMaxLogPerCounter % n : 0);
        }
        ++m_hitCounts;
    }

    inline const char*
    filename(void) const {
        return m_filename;
    }

    inline base::type::LineNumber
    lineNumber(void) const {
        return m_lineNumber;
    }

    inline std::size_t
    hitCounts(void) const {
        return m_hitCounts;
    }

    inline void
    increment(void) {
        ++m_hitCounts;
    }

    class Predicate {
     public:
        Predicate(const char* filename, base::type::LineNumber lineNumber)
            : m_filename(filename), m_lineNumber(lineNumber) {
        }
        inline bool
        operator()(const HitCounter* counter) {
            return ((counter != nullptr) && (strcmp(counter->m_filename, m_filename) == 0) &&
                    (counter->m_lineNumber == m_lineNumber));
        }

     private:
        const char* m_filename;
        base::type::LineNumber m_lineNumber;
    };
2340 2341

 private:
Y
youny626 已提交
2342 2343 2344
    const char* m_filename;
    base::type::LineNumber m_lineNumber;
    std::size_t m_hitCounts;
2345 2346 2347 2348
};
/// @brief Repository for hit counters used across the application
class RegisteredHitCounters : public base::utils::RegistryWithPred<base::HitCounter, base::HitCounter::Predicate> {
 public:
Y
youny626 已提交
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
    /// @brief Validates counter for every N, i.e, registers new if does not exist otherwise updates original one
    /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
    bool
    validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n);

    /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one
    /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
    bool
    validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n);

    /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one
    /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned
    bool
    validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n);

    /// @brief Gets hit counter registered at specified position
    inline const base::HitCounter*
    getCounter(const char* filename, base::type::LineNumber lineNumber) {
        base::threading::ScopedLock scopedLock(lock());
        return get(filename, lineNumber);
    }
2370 2371
};
/// @brief Action to be taken for dispatching
Y
youny626 已提交
2372
enum class DispatchAction : base::type::EnumType { None = 1, NormalLog = 2, SysLog = 4 };
2373 2374 2375 2376
}  // namespace base
template <typename T>
class Callback : protected base::threading::ThreadSafe {
 public:
Y
youny626 已提交
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
    Callback(void) : m_enabled(true) {
    }
    inline bool
    enabled(void) const {
        return m_enabled;
    }
    inline void
    setEnabled(bool enabled) {
        base::threading::ScopedLock scopedLock(lock());
        m_enabled = enabled;
    }

2389
 protected:
Y
youny626 已提交
2390 2391 2392
    virtual void
    handle(const T* handlePtr) = 0;

2393
 private:
Y
youny626 已提交
2394
    bool m_enabled;
2395 2396 2397
};
class LogDispatchData {
 public:
Y
youny626 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
    LogDispatchData() : m_logMessage(nullptr), m_dispatchAction(base::DispatchAction::None) {
    }
    inline const LogMessage*
    logMessage(void) const {
        return m_logMessage;
    }
    inline base::DispatchAction
    dispatchAction(void) const {
        return m_dispatchAction;
    }
    inline void
    setLogMessage(LogMessage* logMessage) {
        m_logMessage = logMessage;
    }
    inline void
    setDispatchAction(base::DispatchAction dispatchAction) {
        m_dispatchAction = dispatchAction;
    }
2416

Y
youny626 已提交
2417 2418 2419 2420
 private:
    LogMessage* m_logMessage;
    base::DispatchAction m_dispatchAction;
    friend class base::LogDispatcher;
2421 2422 2423
};
class LogDispatchCallback : public Callback<LogDispatchData> {
 protected:
Y
youny626 已提交
2424 2425 2426 2427 2428
    virtual void
    handle(const LogDispatchData* data);
    base::threading::Mutex&
    fileHandle(const LogDispatchData* data);

2429
 private:
Y
youny626 已提交
2430 2431 2432
    friend class base::LogDispatcher;
    std::unordered_map<std::string, std::unique_ptr<base::threading::Mutex>> m_fileLocks;
    base::threading::Mutex m_fileLocksMapLock;
2433 2434 2435
};
class PerformanceTrackingCallback : public Callback<PerformanceTrackingData> {
 private:
Y
youny626 已提交
2436
    friend class base::PerformanceTracker;
2437 2438 2439
};
class LoggerRegistrationCallback : public Callback<Logger> {
 private:
Y
youny626 已提交
2440
    friend class base::RegisteredLoggers;
2441 2442 2443
};
class LogBuilder : base::NoCopy {
 public:
Y
youny626 已提交
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
    LogBuilder() : m_termSupportsColor(base::utils::OS::termSupportsColor()) {
    }
    virtual ~LogBuilder(void) {
        ELPP_INTERNAL_INFO(3, "Destroying log builder...")
    }
    virtual base::type::string_t
    build(const LogMessage* logMessage, bool appendNewLine) const = 0;
    void
    convertToColoredOutput(base::type::string_t* logLine, Level level);

2454
 private:
Y
youny626 已提交
2455 2456
    bool m_termSupportsColor;
    friend class el::base::DefaultLogDispatchCallback;
2457 2458 2459 2460 2461 2462 2463
};
typedef std::shared_ptr<LogBuilder> LogBuilderPtr;
/// @brief Represents a logger holding ID and configurations we need to write logs
///
/// @detail This class does not write logs itself instead its used by writer to read configuations from.
class Logger : public base::threading::ThreadSafe, public Loggable {
 public:
Y
youny626 已提交
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
    Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference);
    Logger(const std::string& id, const Configurations& configurations,
           base::LogStreamsReferenceMap* logStreamsReference);
    Logger(const Logger& logger);
    Logger&
    operator=(const Logger& logger);

    virtual ~Logger(void) {
        base::utils::safeDelete(m_typedConfigurations);
    }
2474

Y
youny626 已提交
2475 2476 2477 2478
    virtual inline void
    log(el::base::type::ostream_t& os) const {
        os << m_id.c_str();
    }
2479

Y
youny626 已提交
2480 2481 2482
    /// @brief Configures the logger using specified configurations.
    void
    configure(const Configurations& configurations);
2483

Y
youny626 已提交
2484 2485 2486
    /// @brief Reconfigures logger using existing configurations
    void
    reconfigure(void);
2487

Y
youny626 已提交
2488 2489 2490 2491
    inline const std::string&
    id(void) const {
        return m_id;
    }
2492

Y
youny626 已提交
2493 2494 2495 2496
    inline const std::string&
    parentApplicationName(void) const {
        return m_parentApplicationName;
    }
2497

Y
youny626 已提交
2498 2499 2500 2501
    inline void
    setParentApplicationName(const std::string& parentApplicationName) {
        m_parentApplicationName = parentApplicationName;
    }
2502

Y
youny626 已提交
2503 2504 2505 2506
    inline Configurations*
    configurations(void) {
        return &m_configurations;
    }
2507

Y
youny626 已提交
2508 2509 2510 2511
    inline base::TypedConfigurations*
    typedConfigurations(void) {
        return m_typedConfigurations;
    }
2512

Y
youny626 已提交
2513 2514
    static bool
    isValidId(const std::string& id);
2515

Y
youny626 已提交
2516 2517 2518
    /// @brief Flushes logger to sync all log files for all levels
    void
    flush(void);
2519

Y
youny626 已提交
2520 2521
    void
    flush(Level level, base::type::fstream_t* fs);
2522

Y
youny626 已提交
2523 2524 2525 2526
    inline bool
    isFlushNeeded(Level level) {
        return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level);
    }
2527

Y
youny626 已提交
2528 2529 2530 2531
    inline LogBuilder*
    logBuilder(void) const {
        return m_logBuilder.get();
    }
2532

Y
youny626 已提交
2533 2534 2535 2536
    inline void
    setLogBuilder(const LogBuilderPtr& logBuilder) {
        m_logBuilder = logBuilder;
    }
2537

Y
youny626 已提交
2538 2539 2540 2541
    inline bool
    enabled(Level level) const {
        return m_typedConfigurations->enabled(level);
    }
2542 2543

#if ELPP_VARIADIC_TEMPLATES_SUPPORTED
Y
youny626 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
#define LOGGER_LEVEL_WRITERS_SIGNATURES(FUNCTION_NAME)                \
    template <typename T, typename... Args>                           \
    inline void FUNCTION_NAME(const char*, const T&, const Args&...); \
    template <typename T>                                             \
    inline void FUNCTION_NAME(const T&);

    template <typename T, typename... Args>
    inline void
    verbose(int, const char*, const T&, const Args&...);

    template <typename T>
    inline void
    verbose(int, const T&);

    LOGGER_LEVEL_WRITERS_SIGNATURES(info)
    LOGGER_LEVEL_WRITERS_SIGNATURES(debug)
    LOGGER_LEVEL_WRITERS_SIGNATURES(warn)
    LOGGER_LEVEL_WRITERS_SIGNATURES(error)
    LOGGER_LEVEL_WRITERS_SIGNATURES(fatal)
    LOGGER_LEVEL_WRITERS_SIGNATURES(trace)
#undef LOGGER_LEVEL_WRITERS_SIGNATURES
#endif  // ELPP_VARIADIC_TEMPLATES_SUPPORTED
2566
 private:
Y
youny626 已提交
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
    std::string m_id;
    base::TypedConfigurations* m_typedConfigurations;
    base::type::stringstream_t m_stream;
    std::string m_parentApplicationName;
    bool m_isConfigured;
    Configurations m_configurations;
    std::unordered_map<Level, unsigned int> m_unflushedCount;
    base::LogStreamsReferenceMap* m_logStreamsReference;
    LogBuilderPtr m_logBuilder;

    friend class el::LogMessage;
    friend class el::Loggers;
    friend class el::Helpers;
    friend class el::base::RegisteredLoggers;
    friend class el::base::DefaultLogDispatchCallback;
    friend class el::base::MessageBuilder;
    friend class el::base::Writer;
    friend class el::base::PErrorWriter;
    friend class el::base::Storage;
    friend class el::base::PerformanceTracker;
    friend class el::base::LogDispatcher;

    Logger(void);
2590 2591

#if ELPP_VARIADIC_TEMPLATES_SUPPORTED
Y
youny626 已提交
2592 2593 2594
    template <typename T, typename... Args>
    void
    log_(Level, int, const char*, const T&, const Args&...);
2595

Y
youny626 已提交
2596 2597 2598
    template <typename T>
    inline void
    log_(Level, int, const T&);
2599

Y
youny626 已提交
2600 2601 2602
    template <typename T, typename... Args>
    void
    log(Level, const char*, const T&, const Args&...);
2603

Y
youny626 已提交
2604 2605 2606 2607
    template <typename T>
    inline void
    log(Level, const T&);
#endif  // ELPP_VARIADIC_TEMPLATES_SUPPORTED
2608

Y
youny626 已提交
2609 2610
    void
    initUnflushedCount(void);
2611

Y
youny626 已提交
2612 2613 2614 2615
    inline base::type::stringstream_t&
    stream(void) {
        return m_stream;
    }
2616

Y
youny626 已提交
2617 2618
    void
    resolveLoggerFormatSpec(void) const;
2619 2620 2621 2622 2623
};
namespace base {
/// @brief Loggers repository
class RegisteredLoggers : public base::utils::Registry<Logger, std::string> {
 public:
Y
youny626 已提交
2624
    explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder);
2625

Y
youny626 已提交
2626 2627 2628
    virtual ~RegisteredLoggers(void) {
        unsafeFlushAll();
    }
2629

Y
youny626 已提交
2630 2631 2632 2633 2634
    inline void
    setDefaultConfigurations(const Configurations& configurations) {
        base::threading::ScopedLock scopedLock(lock());
        m_defaultConfigurations.setFromBase(const_cast<Configurations*>(&configurations));
    }
2635

Y
youny626 已提交
2636 2637 2638 2639
    inline Configurations*
    defaultConfigurations(void) {
        return &m_defaultConfigurations;
    }
2640

Y
youny626 已提交
2641 2642
    Logger*
    get(const std::string& id, bool forceCreation = true);
2643

Y
youny626 已提交
2644 2645 2646 2647 2648 2649
    template <typename T>
    inline bool
    installLoggerRegistrationCallback(const std::string& id) {
        return base::utils::Utils::installCallback<T, base::type::LoggerRegistrationCallbackPtr>(
            id, &m_loggerRegistrationCallbacks);
    }
2650

Y
youny626 已提交
2651 2652 2653 2654 2655 2656
    template <typename T>
    inline void
    uninstallLoggerRegistrationCallback(const std::string& id) {
        base::utils::Utils::uninstallCallback<T, base::type::LoggerRegistrationCallbackPtr>(
            id, &m_loggerRegistrationCallbacks);
    }
2657

Y
youny626 已提交
2658 2659 2660 2661 2662 2663
    template <typename T>
    inline T*
    loggerRegistrationCallback(const std::string& id) {
        return base::utils::Utils::callback<T, base::type::LoggerRegistrationCallbackPtr>(
            id, &m_loggerRegistrationCallbacks);
    }
2664

Y
youny626 已提交
2665 2666
    bool
    remove(const std::string& id);
2667

Y
youny626 已提交
2668 2669 2670 2671
    inline bool
    has(const std::string& id) {
        return get(id, false) != nullptr;
    }
2672

Y
youny626 已提交
2673 2674 2675 2676 2677
    inline void
    unregister(Logger*& logger) {
        base::threading::ScopedLock scopedLock(lock());
        base::utils::Registry<Logger, std::string>::unregister(logger->id());
    }
2678

Y
youny626 已提交
2679 2680 2681 2682
    inline base::LogStreamsReferenceMap*
    logStreamsReference(void) {
        return &m_logStreamsReference;
    }
2683

Y
youny626 已提交
2684 2685 2686 2687 2688
    inline void
    flushAll(void) {
        base::threading::ScopedLock scopedLock(lock());
        unsafeFlushAll();
    }
2689

Y
youny626 已提交
2690 2691 2692 2693 2694
    inline void
    setDefaultLogBuilder(LogBuilderPtr& logBuilderPtr) {
        base::threading::ScopedLock scopedLock(lock());
        m_defaultLogBuilder = logBuilderPtr;
    }
2695 2696

 private:
Y
youny626 已提交
2697 2698 2699 2700 2701 2702 2703 2704
    LogBuilderPtr m_defaultLogBuilder;
    Configurations m_defaultConfigurations;
    base::LogStreamsReferenceMap m_logStreamsReference;
    std::unordered_map<std::string, base::type::LoggerRegistrationCallbackPtr> m_loggerRegistrationCallbacks;
    friend class el::base::Storage;

    void
    unsafeFlushAll(void);
2705 2706 2707 2708
};
/// @brief Represents registries for verbose logging
class VRegistry : base::NoCopy, public base::threading::ThreadSafe {
 public:
Y
youny626 已提交
2709
    explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags);
2710

Y
youny626 已提交
2711 2712 2713
    /// @brief Sets verbose level. Accepted range is 0-9
    void
    setLevel(base::type::VerboseLevel level);
2714

Y
youny626 已提交
2715 2716 2717 2718
    inline base::type::VerboseLevel
    level(void) const {
        return m_level;
    }
2719

Y
youny626 已提交
2720 2721 2722 2723 2724
    inline void
    clearModules(void) {
        base::threading::ScopedLock scopedLock(lock());
        m_modules.clear();
    }
2725

Y
youny626 已提交
2726 2727
    void
    setModules(const char* modules);
2728

Y
youny626 已提交
2729 2730
    bool
    allowed(base::type::VerboseLevel vlevel, const char* file);
2731

Y
youny626 已提交
2732 2733 2734 2735
    inline const std::unordered_map<std::string, base::type::VerboseLevel>&
    modules(void) const {
        return m_modules;
    }
2736

Y
youny626 已提交
2737 2738
    void
    setFromArgs(const base::utils::CommandLineArgs* commandLineArgs);
2739

Y
youny626 已提交
2740 2741 2742 2743 2744
    /// @brief Whether or not vModules enabled
    inline bool
    vModulesEnabled(void) {
        return !base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags);
    }
2745 2746

 private:
Y
youny626 已提交
2747 2748 2749
    base::type::VerboseLevel m_level;
    base::type::EnumType* m_pFlags;
    std::unordered_map<std::string, base::type::VerboseLevel> m_modules;
2750 2751 2752 2753
};
}  // namespace base
class LogMessage {
 public:
Y
youny626 已提交
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
    LogMessage(Level level, const std::string& file, base::type::LineNumber line, const std::string& func,
               base::type::VerboseLevel verboseLevel, Logger* logger)
        : m_level(level),
          m_file(file),
          m_line(line),
          m_func(func),
          m_verboseLevel(verboseLevel),
          m_logger(logger),
          m_message(logger->stream().str()) {
    }
    inline Level
    level(void) const {
        return m_level;
    }
    inline const std::string&
    file(void) const {
        return m_file;
    }
    inline base::type::LineNumber
    line(void) const {
        return m_line;
    }
    inline const std::string&
    func(void) const {
        return m_func;
    }
    inline base::type::VerboseLevel
    verboseLevel(void) const {
        return m_verboseLevel;
    }
    inline Logger*
    logger(void) const {
        return m_logger;
    }
    inline const base::type::string_t&
    message(void) const {
        return m_message;
    }

2793
 private:
Y
youny626 已提交
2794 2795 2796 2797 2798 2799 2800
    Level m_level;
    std::string m_file;
    base::type::LineNumber m_line;
    std::string m_func;
    base::type::VerboseLevel m_verboseLevel;
    Logger* m_logger;
    base::type::string_t m_message;
2801 2802 2803 2804 2805
};
namespace base {
#if ELPP_ASYNC_LOGGING
class AsyncLogItem {
 public:
Y
youny626 已提交
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
    explicit AsyncLogItem(const LogMessage& logMessage, const LogDispatchData& data,
                          const base::type::string_t& logLine)
        : m_logMessage(logMessage), m_dispatchData(data), m_logLine(logLine) {
    }
    virtual ~AsyncLogItem() {
    }
    inline LogMessage*
    logMessage(void) {
        return &m_logMessage;
    }
    inline LogDispatchData*
    data(void) {
        return &m_dispatchData;
    }
    inline base::type::string_t
    logLine(void) {
        return m_logLine;
    }

2825
 private:
Y
youny626 已提交
2826 2827 2828
    LogMessage m_logMessage;
    LogDispatchData m_dispatchData;
    base::type::string_t m_logLine;
2829 2830 2831
};
class AsyncLogQueue : public base::threading::ThreadSafe {
 public:
Y
youny626 已提交
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
    virtual ~AsyncLogQueue() {
        ELPP_INTERNAL_INFO(6, "~AsyncLogQueue");
    }

    inline AsyncLogItem
    next(void) {
        base::threading::ScopedLock scopedLock(lock());
        AsyncLogItem result = m_queue.front();
        m_queue.pop();
        return result;
    }

    inline void
    push(const AsyncLogItem& item) {
        base::threading::ScopedLock scopedLock(lock());
        m_queue.push(item);
    }
    inline void
    pop(void) {
        base::threading::ScopedLock scopedLock(lock());
        m_queue.pop();
    }
    inline AsyncLogItem
    front(void) {
        base::threading::ScopedLock scopedLock(lock());
        return m_queue.front();
    }
    inline bool
    empty(void) {
        base::threading::ScopedLock scopedLock(lock());
        return m_queue.empty();
    }

2865
 private:
Y
youny626 已提交
2866
    std::queue<AsyncLogItem> m_queue;
2867 2868 2869
};
class IWorker {
 public:
Y
youny626 已提交
2870 2871 2872 2873
    virtual ~IWorker() {
    }
    virtual void
    start() = 0;
2874
};
Y
youny626 已提交
2875
#endif  // ELPP_ASYNC_LOGGING
2876 2877 2878 2879
/// @brief Easylogging++ management storage
class Storage : base::NoCopy, public base::threading::ThreadSafe {
 public:
#if ELPP_ASYNC_LOGGING
Y
youny626 已提交
2880
    Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker);
2881
#else
Y
youny626 已提交
2882
    explicit Storage(const LogBuilderPtr& defaultLogBuilder);
2883 2884
#endif  // ELPP_ASYNC_LOGGING

Y
youny626 已提交
2885
    virtual ~Storage(void);
2886

Y
youny626 已提交
2887 2888 2889 2890
    inline bool
    validateEveryNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t occasion) {
        return hitCounters()->validateEveryN(filename, lineNumber, occasion);
    }
2891

Y
youny626 已提交
2892 2893 2894 2895
    inline bool
    validateAfterNCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
        return hitCounters()->validateAfterN(filename, lineNumber, n);
    }
2896

Y
youny626 已提交
2897 2898 2899 2900
    inline bool
    validateNTimesCounter(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
        return hitCounters()->validateNTimes(filename, lineNumber, n);
    }
2901

Y
youny626 已提交
2902 2903 2904 2905
    inline base::RegisteredHitCounters*
    hitCounters(void) const {
        return m_registeredHitCounters;
    }
2906

Y
youny626 已提交
2907 2908 2909 2910
    inline base::RegisteredLoggers*
    registeredLoggers(void) const {
        return m_registeredLoggers;
    }
2911

Y
youny626 已提交
2912 2913 2914 2915
    inline base::VRegistry*
    vRegistry(void) const {
        return m_vRegistry;
    }
2916 2917

#if ELPP_ASYNC_LOGGING
Y
youny626 已提交
2918 2919 2920 2921
    inline base::AsyncLogQueue*
    asyncLogQueue(void) const {
        return m_asyncLogQueue;
    }
2922 2923
#endif  // ELPP_ASYNC_LOGGING

Y
youny626 已提交
2924 2925 2926 2927
    inline const base::utils::CommandLineArgs*
    commandLineArgs(void) const {
        return &m_commandLineArgs;
    }
2928

Y
youny626 已提交
2929 2930 2931 2932
    inline void
    addFlag(LoggingFlag flag) {
        base::utils::addFlag(flag, &m_flags);
    }
2933

Y
youny626 已提交
2934 2935 2936 2937
    inline void
    removeFlag(LoggingFlag flag) {
        base::utils::removeFlag(flag, &m_flags);
    }
2938

Y
youny626 已提交
2939 2940 2941 2942
    inline bool
    hasFlag(LoggingFlag flag) const {
        return base::utils::hasFlag(flag, m_flags);
    }
2943

Y
youny626 已提交
2944 2945 2946 2947
    inline base::type::EnumType
    flags(void) const {
        return m_flags;
    }
2948

Y
youny626 已提交
2949 2950 2951 2952
    inline void
    setFlags(base::type::EnumType flags) {
        m_flags = flags;
    }
2953

Y
youny626 已提交
2954 2955 2956 2957
    inline void
    setPreRollOutCallback(const PreRollOutCallback& callback) {
        m_preRollOutCallback = callback;
    }
2958

Y
youny626 已提交
2959 2960 2961 2962
    inline void
    unsetPreRollOutCallback(void) {
        m_preRollOutCallback = base::defaultPreRollOutCallback;
    }
2963

Y
youny626 已提交
2964 2965 2966 2967
    inline PreRollOutCallback&
    preRollOutCallback(void) {
        return m_preRollOutCallback;
    }
2968

Y
youny626 已提交
2969 2970 2971 2972 2973 2974
    bool
    hasCustomFormatSpecifier(const char* formatSpecifier);
    void
    installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier);
    bool
    uninstallCustomFormatSpecifier(const char* formatSpecifier);
2975

Y
youny626 已提交
2976 2977 2978 2979
    const std::vector<CustomFormatSpecifier>*
    customFormatSpecifiers(void) const {
        return &m_customFormatSpecifiers;
    }
2980

Y
youny626 已提交
2981 2982 2983 2984
    base::threading::Mutex&
    customFormatSpecifiersLock() {
        return m_customFormatSpecifiersLock;
    }
2985

Y
youny626 已提交
2986 2987 2988 2989
    inline void
    setLoggingLevel(Level level) {
        m_loggingLevel = level;
    }
2990

Y
youny626 已提交
2991 2992 2993 2994 2995
    template <typename T>
    inline bool
    installLogDispatchCallback(const std::string& id) {
        return base::utils::Utils::installCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
    }
2996

Y
youny626 已提交
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
    template <typename T>
    inline void
    uninstallLogDispatchCallback(const std::string& id) {
        base::utils::Utils::uninstallCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
    }
    template <typename T>
    inline T*
    logDispatchCallback(const std::string& id) {
        return base::utils::Utils::callback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
    }
3007 3008

#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
Y
youny626 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
    template <typename T>
    inline bool
    installPerformanceTrackingCallback(const std::string& id) {
        return base::utils::Utils::installCallback<T, base::type::PerformanceTrackingCallbackPtr>(
            id, &m_performanceTrackingCallbacks);
    }

    template <typename T>
    inline void
    uninstallPerformanceTrackingCallback(const std::string& id) {
        base::utils::Utils::uninstallCallback<T, base::type::PerformanceTrackingCallbackPtr>(
            id, &m_performanceTrackingCallbacks);
    }

    template <typename T>
    inline T*
    performanceTrackingCallback(const std::string& id) {
        return base::utils::Utils::callback<T, base::type::PerformanceTrackingCallbackPtr>(
            id, &m_performanceTrackingCallbacks);
    }
#endif  // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)

    /// @brief Sets thread name for current thread. Requires std::thread
    inline void
    setThreadName(const std::string& name) {
        if (name.empty())
            return;
        base::threading::ScopedLock scopedLock(m_threadNamesLock);
        m_threadNames[base::threading::getCurrentThreadId()] = name;
    }

    inline std::string
    getThreadName(const std::string& threadId) {
        base::threading::ScopedLock scopedLock(m_threadNamesLock);
        std::unordered_map<std::string, std::string>::const_iterator it = m_threadNames.find(threadId);
        if (it == m_threadNames.end()) {
            return threadId;
        }
        return it->second;
    }

3050
 private:
Y
youny626 已提交
3051 3052 3053 3054
    base::RegisteredHitCounters* m_registeredHitCounters;
    base::RegisteredLoggers* m_registeredLoggers;
    base::type::EnumType m_flags;
    base::VRegistry* m_vRegistry;
3055
#if ELPP_ASYNC_LOGGING
Y
youny626 已提交
3056 3057
    base::AsyncLogQueue* m_asyncLogQueue;
    base::IWorker* m_asyncDispatchWorker;
3058
#endif  // ELPP_ASYNC_LOGGING
Y
youny626 已提交
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
    base::utils::CommandLineArgs m_commandLineArgs;
    PreRollOutCallback m_preRollOutCallback;
    std::unordered_map<std::string, base::type::LogDispatchCallbackPtr> m_logDispatchCallbacks;
    std::unordered_map<std::string, base::type::PerformanceTrackingCallbackPtr> m_performanceTrackingCallbacks;
    std::unordered_map<std::string, std::string> m_threadNames;
    std::vector<CustomFormatSpecifier> m_customFormatSpecifiers;
    base::threading::Mutex m_customFormatSpecifiersLock;
    base::threading::Mutex m_threadNamesLock;
    Level m_loggingLevel;

    friend class el::Helpers;
    friend class el::base::DefaultLogDispatchCallback;
    friend class el::LogBuilder;
    friend class el::base::MessageBuilder;
    friend class el::base::Writer;
    friend class el::base::PerformanceTracker;
    friend class el::base::LogDispatcher;

    void
    setApplicationArguments(int argc, char** argv);

    inline void
    setApplicationArguments(int argc, const char** argv) {
        setApplicationArguments(argc, const_cast<char**>(argv));
    }
3084 3085 3086 3087 3088
};
extern ELPP_EXPORT base::type::StoragePointer elStorage;
#define ELPP el::base::elStorage
class DefaultLogDispatchCallback : public LogDispatchCallback {
 protected:
Y
youny626 已提交
3089 3090 3091
    void
    handle(const LogDispatchData* data);

3092
 private:
Y
youny626 已提交
3093 3094 3095
    const LogDispatchData* m_data;
    void
    dispatch(base::type::string_t&& logLine);
3096 3097 3098 3099
};
#if ELPP_ASYNC_LOGGING
class AsyncLogDispatchCallback : public LogDispatchCallback {
 protected:
Y
youny626 已提交
3100 3101
    void
    handle(const LogDispatchData* data);
3102 3103 3104
};
class AsyncDispatchWorker : public base::IWorker, public base::threading::ThreadSafe {
 public:
Y
youny626 已提交
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
    AsyncDispatchWorker();
    virtual ~AsyncDispatchWorker();

    bool
    clean(void);
    void
    emptyQueue(void);
    virtual void
    start(void);
    void
    handle(AsyncLogItem* logItem);
    void
    run(void);

    void
    setContinueRunning(bool value) {
        base::threading::ScopedLock scopedLock(m_continueRunningLock);
        m_continueRunning = value;
    }

    bool
    continueRunning(void) const {
        return m_continueRunning;
    }

3130
 private:
Y
youny626 已提交
3131 3132 3133
    std::condition_variable cv;
    bool m_continueRunning;
    base::threading::Mutex m_continueRunningLock;
3134 3135 3136 3137 3138 3139
};
#endif  // ELPP_ASYNC_LOGGING
}  // namespace base
namespace base {
class DefaultLogBuilder : public LogBuilder {
 public:
Y
youny626 已提交
3140 3141
    base::type::string_t
    build(const LogMessage* logMessage, bool appendNewLine) const;
3142 3143 3144 3145
};
/// @brief Dispatches log messages
class LogDispatcher : base::NoCopy {
 public:
Y
youny626 已提交
3146 3147 3148
    LogDispatcher(bool proceed, LogMessage* logMessage, base::DispatchAction dispatchAction)
        : m_proceed(proceed), m_logMessage(logMessage), m_dispatchAction(std::move(dispatchAction)) {
    }
3149

Y
youny626 已提交
3150 3151
    void
    dispatch(void);
3152 3153

 private:
Y
youny626 已提交
3154 3155 3156
    bool m_proceed;
    LogMessage* m_logMessage;
    base::DispatchAction m_dispatchAction;
3157 3158 3159 3160
};
#if defined(ELPP_STL_LOGGING)
/// @brief Workarounds to write some STL logs
///
Y
youny626 已提交
3161 3162 3163 3164
/// @detail There is workaround needed to loop through some stl containers. In order to do that, we need iterable
/// containers of same type and provide iterator interface and pass it on to writeIterator(). Remember, this is passed
/// by value in constructor so that we dont change original containers. This operation is as expensive as
/// Big-O(std::min(class_.size(), base::consts::kMaxLogPerContainer))
3165 3166 3167 3168 3169
namespace workarounds {
/// @brief Abstract IterableContainer template that provides interface for iterable classes of type T
template <typename T, typename Container>
class IterableContainer {
 public:
Y
youny626 已提交
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
    typedef typename Container::iterator iterator;
    typedef typename Container::const_iterator const_iterator;
    IterableContainer(void) {
    }
    virtual ~IterableContainer(void) {
    }
    iterator
    begin(void) {
        return getContainer().begin();
    }
    iterator
    end(void) {
        return getContainer().end();
    }

3185
 private:
Y
youny626 已提交
3186 3187
    virtual Container&
    getContainer(void) = 0;
3188 3189
};
/// @brief Implements IterableContainer and provides iterable std::priority_queue class
Y
youny626 已提交
3190 3191
template <typename T, typename Container = std::vector<T>,
          typename Comparator = std::less<typename Container::value_type>>
3192
class IterablePriorityQueue : public IterableContainer<T, Container>,
Y
youny626 已提交
3193
                              public std::priority_queue<T, Container, Comparator> {
3194
 public:
Y
youny626 已提交
3195 3196 3197 3198 3199 3200
    IterablePriorityQueue(std::priority_queue<T, Container, Comparator> queue_) {
        std::size_t count_ = 0;
        while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) {
            this->push(queue_.top());
            queue_.pop();
        }
3201
    }
Y
youny626 已提交
3202

3203
 private:
Y
youny626 已提交
3204 3205 3206 3207
    inline Container&
    getContainer(void) {
        return this->c;
    }
3208 3209
};
/// @brief Implements IterableContainer and provides iterable std::queue class
Y
youny626 已提交
3210
template <typename T, typename Container = std::deque<T>>
3211 3212
class IterableQueue : public IterableContainer<T, Container>, public std::queue<T, Container> {
 public:
Y
youny626 已提交
3213 3214 3215 3216 3217 3218
    IterableQueue(std::queue<T, Container> queue_) {
        std::size_t count_ = 0;
        while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) {
            this->push(queue_.front());
            queue_.pop();
        }
3219
    }
Y
youny626 已提交
3220

3221
 private:
Y
youny626 已提交
3222 3223 3224 3225
    inline Container&
    getContainer(void) {
        return this->c;
    }
3226 3227
};
/// @brief Implements IterableContainer and provides iterable std::stack class
Y
youny626 已提交
3228
template <typename T, typename Container = std::deque<T>>
3229 3230
class IterableStack : public IterableContainer<T, Container>, public std::stack<T, Container> {
 public:
Y
youny626 已提交
3231 3232 3233 3234 3235 3236
    IterableStack(std::stack<T, Container> stack_) {
        std::size_t count_ = 0;
        while (++count_ < base::consts::kMaxLogPerContainer && !stack_.empty()) {
            this->push(stack_.top());
            stack_.pop();
        }
3237
    }
Y
youny626 已提交
3238

3239
 private:
Y
youny626 已提交
3240 3241 3242 3243
    inline Container&
    getContainer(void) {
        return this->c;
    }
3244 3245 3246 3247 3248 3249
};
}  // namespace workarounds
#endif  // defined(ELPP_STL_LOGGING)
// Log message builder
class MessageBuilder {
 public:
Y
youny626 已提交
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    MessageBuilder(void) : m_logger(nullptr), m_containerLogSeperator(ELPP_LITERAL("")) {
    }
    void
    initialize(Logger* logger);

#define ELPP_SIMPLE_LOG(LOG_TYPE)                      \
    MessageBuilder& operator<<(LOG_TYPE msg) {         \
        m_logger->stream() << msg;                     \
        if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { \
            m_logger->stream() << " ";                 \
        }                                              \
        return *this;                                  \
    }
3263

Y
youny626 已提交
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
    inline MessageBuilder&
    operator<<(const std::string& msg) {
        return operator<<(msg.c_str());
    }
    ELPP_SIMPLE_LOG(char)
    ELPP_SIMPLE_LOG(bool)
    ELPP_SIMPLE_LOG(signed short)
    ELPP_SIMPLE_LOG(unsigned short)
    ELPP_SIMPLE_LOG(signed int)
    ELPP_SIMPLE_LOG(unsigned int)
    ELPP_SIMPLE_LOG(signed long)
    ELPP_SIMPLE_LOG(unsigned long)
    ELPP_SIMPLE_LOG(float)
    ELPP_SIMPLE_LOG(double)
    ELPP_SIMPLE_LOG(char*)
    ELPP_SIMPLE_LOG(const char*)
    ELPP_SIMPLE_LOG(const void*)
    ELPP_SIMPLE_LOG(long double)
    inline MessageBuilder&
    operator<<(const std::wstring& msg) {
        return operator<<(msg.c_str());
    }
    MessageBuilder&
    operator<<(const wchar_t* msg);
    // ostream manipulators
    inline MessageBuilder&
    operator<<(std::ostream& (*OStreamMani)(std::ostream&)) {
        m_logger->stream() << OStreamMani;
        return *this;
    }
#define ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(temp)                                               \
    template <typename T>                                                                       \
    inline MessageBuilder& operator<<(const temp<T>& template_inst) {                           \
        return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
    }
#define ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(temp)                                               \
    template <typename T1, typename T2>                                                         \
    inline MessageBuilder& operator<<(const temp<T1, T2>& template_inst) {                      \
        return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
    }
#define ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(temp)                                             \
    template <typename T1, typename T2, typename T3>                                            \
    inline MessageBuilder& operator<<(const temp<T1, T2, T3>& template_inst) {                  \
        return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
    }
#define ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(temp)                                              \
    template <typename T1, typename T2, typename T3, typename T4>                               \
    inline MessageBuilder& operator<<(const temp<T1, T2, T3, T4>& template_inst) {              \
        return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
    }
#define ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(temp)                                              \
    template <typename T1, typename T2, typename T3, typename T4, typename T5>                  \
    inline MessageBuilder& operator<<(const temp<T1, T2, T3, T4, T5>& template_inst) {          \
        return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \
    }
3319 3320

#if defined(ELPP_STL_LOGGING)
Y
youny626 已提交
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::vector)
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::list)
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::deque)
    ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::set)
    ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::multiset)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::map)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::multimap)
    template <class T, class Container>
    inline MessageBuilder&
    operator<<(const std::queue<T, Container>& queue_) {
        base::workarounds::IterableQueue<T, Container> iterableQueue_ =
            static_cast<base::workarounds::IterableQueue<T, Container>>(queue_);
        return writeIterator(iterableQueue_.begin(), iterableQueue_.end(), iterableQueue_.size());
    }
    template <class T, class Container>
    inline MessageBuilder&
    operator<<(const std::stack<T, Container>& stack_) {
        base::workarounds::IterableStack<T, Container> iterableStack_ =
            static_cast<base::workarounds::IterableStack<T, Container>>(stack_);
        return writeIterator(iterableStack_.begin(), iterableStack_.end(), iterableStack_.size());
    }
    template <class T, class Container, class Comparator>
    inline MessageBuilder&
    operator<<(const std::priority_queue<T, Container, Comparator>& priorityQueue_) {
        base::workarounds::IterablePriorityQueue<T, Container, Comparator> iterablePriorityQueue_ =
            static_cast<base::workarounds::IterablePriorityQueue<T, Container, Comparator>>(priorityQueue_);
        return writeIterator(iterablePriorityQueue_.begin(), iterablePriorityQueue_.end(),
                             iterablePriorityQueue_.size());
    }
    template <class First, class Second>
    MessageBuilder&
    operator<<(const std::pair<First, Second>& pair_) {
        m_logger->stream() << ELPP_LITERAL("(");
        operator<<(static_cast<First>(pair_.first));
        m_logger->stream() << ELPP_LITERAL(", ");
        operator<<(static_cast<Second>(pair_.second));
        m_logger->stream() << ELPP_LITERAL(")");
        return *this;
    }
    template <std::size_t Size>
    MessageBuilder&
    operator<<(const std::bitset<Size>& bitset_) {
        m_logger->stream() << ELPP_LITERAL("[");
        operator<<(bitset_.to_string());
        m_logger->stream() << ELPP_LITERAL("]");
        return *this;
    }
#if defined(ELPP_LOG_STD_ARRAY)
    template <class T, std::size_t Size>
    inline MessageBuilder&
    operator<<(const std::array<T, Size>& array) {
        return writeIterator(array.begin(), array.end(), array.size());
    }
#endif  // defined(ELPP_LOG_STD_ARRAY)
#if defined(ELPP_LOG_UNORDERED_MAP)
    ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_map)
    ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_multimap)
#endif  // defined(ELPP_LOG_UNORDERED_MAP)
#if defined(ELPP_LOG_UNORDERED_SET)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_set)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_multiset)
#endif  // defined(ELPP_LOG_UNORDERED_SET)
3383 3384
#endif  // defined(ELPP_STL_LOGGING)
#if defined(ELPP_QT_LOGGING)
Y
youny626 已提交
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
    inline MessageBuilder&
    operator<<(const QString& msg) {
#if defined(ELPP_UNICODE)
        m_logger->stream() << msg.toStdWString();
#else
        m_logger->stream() << msg.toStdString();
#endif  // defined(ELPP_UNICODE)
        return *this;
    }
    inline MessageBuilder&
    operator<<(const QByteArray& msg) {
        return operator<<(QString(msg));
    }
    inline MessageBuilder&
    operator<<(const QStringRef& msg) {
        return operator<<(msg.toString());
    }
    inline MessageBuilder&
    operator<<(qint64 msg) {
#if defined(ELPP_UNICODE)
        m_logger->stream() << QString::number(msg).toStdWString();
#else
        m_logger->stream() << QString::number(msg).toStdString();
#endif  // defined(ELPP_UNICODE)
        return *this;
    }
    inline MessageBuilder&
    operator<<(quint64 msg) {
#if defined(ELPP_UNICODE)
        m_logger->stream() << QString::number(msg).toStdWString();
#else
        m_logger->stream() << QString::number(msg).toStdString();
#endif  // defined(ELPP_UNICODE)
        return *this;
    }
    inline MessageBuilder&
    operator<<(QChar msg) {
        m_logger->stream() << msg.toLatin1();
        return *this;
    }
    inline MessageBuilder&
    operator<<(const QLatin1String& msg) {
        m_logger->stream() << msg.latin1();
        return *this;
    }
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QList)
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QVector)
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QQueue)
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QSet)
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QLinkedList)
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QStack)
    template <typename First, typename Second>
    MessageBuilder&
    operator<<(const QPair<First, Second>& pair_) {
        m_logger->stream() << ELPP_LITERAL("(");
        operator<<(static_cast<First>(pair_.first));
        m_logger->stream() << ELPP_LITERAL(", ");
        operator<<(static_cast<Second>(pair_.second));
        m_logger->stream() << ELPP_LITERAL(")");
        return *this;
    }
    template <typename K, typename V>
    MessageBuilder&
    operator<<(const QMap<K, V>& map_) {
        m_logger->stream() << ELPP_LITERAL("[");
        QList<K> keys = map_.keys();
        typename QList<K>::const_iterator begin = keys.begin();
        typename QList<K>::const_iterator end = keys.end();
        int max_ = static_cast<int>(base::consts::kMaxLogPerContainer);  // to prevent warning
        for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) {
            m_logger->stream() << ELPP_LITERAL("(");
            operator<<(static_cast<K>(*begin));
            m_logger->stream() << ELPP_LITERAL(", ");
            operator<<(static_cast<V>(map_.value(*begin)));
            m_logger->stream() << ELPP_LITERAL(")");
            m_logger->stream() << ((index_ < keys.size() - 1) ? m_containerLogSeperator : ELPP_LITERAL(""));
        }
        if (begin != end) {
            m_logger->stream() << ELPP_LITERAL("...");
        }
        m_logger->stream() << ELPP_LITERAL("]");
        return *this;
    }
    template <typename K, typename V>
    inline MessageBuilder&
    operator<<(const QMultiMap<K, V>& map_) {
        operator<<(static_cast<QMap<K, V>>(map_));
        return *this;
    }
    template <typename K, typename V>
    MessageBuilder&
    operator<<(const QHash<K, V>& hash_) {
        m_logger->stream() << ELPP_LITERAL("[");
        QList<K> keys = hash_.keys();
        typename QList<K>::const_iterator begin = keys.begin();
        typename QList<K>::const_iterator end = keys.end();
        int max_ = static_cast<int>(base::consts::kMaxLogPerContainer);  // prevent type warning
        for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) {
            m_logger->stream() << ELPP_LITERAL("(");
            operator<<(static_cast<K>(*begin));
            m_logger->stream() << ELPP_LITERAL(", ");
            operator<<(static_cast<V>(hash_.value(*begin)));
            m_logger->stream() << ELPP_LITERAL(")");
            m_logger->stream() << ((index_ < keys.size() - 1) ? m_containerLogSeperator : ELPP_LITERAL(""));
        }
        if (begin != end) {
            m_logger->stream() << ELPP_LITERAL("...");
        }
        m_logger->stream() << ELPP_LITERAL("]");
        return *this;
    }
    template <typename K, typename V>
    inline MessageBuilder&
    operator<<(const QMultiHash<K, V>& multiHash_) {
        operator<<(static_cast<QHash<K, V>>(multiHash_));
        return *this;
    }
3502 3503
#endif  // defined(ELPP_QT_LOGGING)
#if defined(ELPP_BOOST_LOGGING)
Y
youny626 已提交
3504 3505 3506 3507 3508 3509 3510 3511
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::vector)
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::stable_vector)
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::list)
    ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::deque)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::map)
    ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::flat_map)
    ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::set)
    ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::flat_set)
3512 3513
#endif  // defined(ELPP_BOOST_LOGGING)

Y
youny626 已提交
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539
    /// @brief Macro used internally that can be used externally to make containers easylogging++ friendly
    ///
    /// @detail This macro expands to write an ostream& operator<< for container. This container is expected to
    ///         have begin() and end() methods that return respective iterators
    /// @param ContainerType Type of container e.g, MyList from WX_DECLARE_LIST(int, MyList); in wxwidgets
    /// @param SizeMethod Method used to get size of container.
    /// @param ElementInstance Instance of element to be fed out. Insance name is "elem". See WXELPP_ENABLED macro
    ///        for an example usage
#define MAKE_CONTAINERELPP_FRIENDLY(ContainerType, SizeMethod, ElementInstance)                                \
    el::base::type::ostream_t& operator<<(el::base::type::ostream_t& ss, const ContainerType& container) {     \
        const el::base::type::char_t* sep =                                                                    \
            ELPP->hasFlag(el::LoggingFlag::NewLineForContainer) ? ELPP_LITERAL("\n    ") : ELPP_LITERAL(", "); \
        ContainerType::const_iterator elem = container.begin();                                                \
        ContainerType::const_iterator endElem = container.end();                                               \
        std::size_t size_ = container.SizeMethod;                                                              \
        ss << ELPP_LITERAL("[");                                                                               \
        for (std::size_t i = 0; elem != endElem && i < el::base::consts::kMaxLogPerContainer; ++i, ++elem) {   \
            ss << ElementInstance;                                                                             \
            ss << ((i < size_ - 1) ? sep : ELPP_LITERAL(""));                                                  \
        }                                                                                                      \
        if (elem != endElem) {                                                                                 \
            ss << ELPP_LITERAL("...");                                                                         \
        }                                                                                                      \
        ss << ELPP_LITERAL("]");                                                                               \
        return ss;                                                                                             \
    }
3540
#if defined(ELPP_WXWIDGETS_LOGGING)
Y
youny626 已提交
3541 3542 3543 3544
    ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(wxVector)
#define ELPP_WX_PTR_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), *(*elem))
#define ELPP_WX_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), (*elem))
#define ELPP_WX_HASH_MAP_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), \
3545 3546
ELPP_LITERAL("(") << elem->first << ELPP_LITERAL(", ") << elem->second << ELPP_LITERAL(")")
#else
Y
youny626 已提交
3547 3548 3549
#define ELPP_WX_PTR_ENABLED(ContainerType)
#define ELPP_WX_ENABLED(ContainerType)
#define ELPP_WX_HASH_MAP_ENABLED(ContainerType)
3550
#endif  // defined(ELPP_WXWIDGETS_LOGGING)
Y
youny626 已提交
3551 3552 3553
    // Other classes
    template <class Class>
    ELPP_SIMPLE_LOG(const Class&)
3554 3555 3556 3557 3558 3559
#undef ELPP_SIMPLE_LOG
#undef ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG
#undef ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG
#undef ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG
#undef ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG
#undef ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG
Y
youny626 已提交
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
    private : Logger* m_logger;
    const base::type::char_t* m_containerLogSeperator;

    template <class Iterator>
    MessageBuilder&
    writeIterator(Iterator begin_, Iterator end_, std::size_t size_) {
        m_logger->stream() << ELPP_LITERAL("[");
        for (std::size_t i = 0; begin_ != end_ && i < base::consts::kMaxLogPerContainer; ++i, ++begin_) {
            operator<<(*begin_);
            m_logger->stream() << ((i < size_ - 1) ? m_containerLogSeperator : ELPP_LITERAL(""));
        }
        if (begin_ != end_) {
            m_logger->stream() << ELPP_LITERAL("...");
        }
        m_logger->stream() << ELPP_LITERAL("]");
        if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {
            m_logger->stream() << " ";
        }
        return *this;
3579 3580 3581 3582 3583
    }
};
/// @brief Writes nothing - Used when certain log is disabled
class NullWriter : base::NoCopy {
 public:
Y
youny626 已提交
3584 3585
    NullWriter(void) {
    }
3586

Y
youny626 已提交
3587 3588 3589 3590 3591
    // Null manipulator
    inline NullWriter&
    operator<<(std::ostream& (*)(std::ostream&)) {
        return *this;
    }
3592

Y
youny626 已提交
3593 3594 3595 3596 3597
    template <typename T>
    inline NullWriter&
    operator<<(const T&) {
        return *this;
    }
3598

Y
youny626 已提交
3599 3600 3601
    inline operator bool() {
        return true;
    }
3602 3603 3604 3605
};
/// @brief Main entry point of each logging
class Writer : base::NoCopy {
 public:
Y
youny626 已提交
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618
    Writer(Level level, const char* file, base::type::LineNumber line, const char* func,
           base::DispatchAction dispatchAction = base::DispatchAction::NormalLog,
           base::type::VerboseLevel verboseLevel = 0)
        : m_msg(nullptr),
          m_level(level),
          m_file(file),
          m_line(line),
          m_func(func),
          m_verboseLevel(verboseLevel),
          m_logger(nullptr),
          m_proceed(false),
          m_dispatchAction(dispatchAction) {
    }
3619

Y
youny626 已提交
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
    Writer(LogMessage* msg, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog)
        : m_msg(msg),
          m_level(msg != nullptr ? msg->level() : Level::Unknown),
          m_line(0),
          m_logger(nullptr),
          m_proceed(false),
          m_dispatchAction(dispatchAction) {
    }

    virtual ~Writer(void) {
        processDispatch();
3631 3632
    }

Y
youny626 已提交
3633 3634 3635
    template <typename T>
    inline Writer&
    operator<<(const T& log) {
3636
#if ELPP_LOGGING_ENABLED
Y
youny626 已提交
3637 3638 3639 3640 3641
        if (m_proceed) {
            m_messageBuilder << log;
        }
#endif  // ELPP_LOGGING_ENABLED
        return *this;
3642
    }
Y
youny626 已提交
3643 3644 3645 3646 3647 3648 3649

    inline Writer&
    operator<<(std::ostream& (*log)(std::ostream&)) {
#if ELPP_LOGGING_ENABLED
        if (m_proceed) {
            m_messageBuilder << log;
        }
3650
#endif  // ELPP_LOGGING_ENABLED
Y
youny626 已提交
3651 3652 3653 3654 3655 3656
        return *this;
    }

    inline operator bool() {
        return true;
    }
3657

Y
youny626 已提交
3658 3659 3660 3661
    Writer&
    construct(Logger* logger, bool needLock = true);
    Writer&
    construct(int count, const char* loggerIds, ...);
3662 3663

 protected:
Y
youny626 已提交
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682
    LogMessage* m_msg;
    Level m_level;
    const char* m_file;
    const base::type::LineNumber m_line;
    const char* m_func;
    base::type::VerboseLevel m_verboseLevel;
    Logger* m_logger;
    bool m_proceed;
    base::MessageBuilder m_messageBuilder;
    base::DispatchAction m_dispatchAction;
    std::vector<std::string> m_loggerIds;
    friend class el::Helpers;

    void
    initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true);
    void
    processDispatch();
    void
    triggerDispatch(void);
3683 3684 3685
};
class PErrorWriter : public base::Writer {
 public:
Y
youny626 已提交
3686 3687 3688 3689 3690
    PErrorWriter(Level level, const char* file, base::type::LineNumber line, const char* func,
                 base::DispatchAction dispatchAction = base::DispatchAction::NormalLog,
                 base::type::VerboseLevel verboseLevel = 0)
        : base::Writer(level, file, line, func, dispatchAction, verboseLevel) {
    }
3691

Y
youny626 已提交
3692
    virtual ~PErrorWriter(void);
3693 3694 3695 3696 3697
};
}  // namespace base
// Logging from Logger class. Why this is here? Because we have Storage and Writer class available
#if ELPP_VARIADIC_TEMPLATES_SUPPORTED
template <typename T, typename... Args>
Y
youny626 已提交
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
void
Logger::log_(Level level, int vlevel, const char* s, const T& value, const Args&... args) {
    base::MessageBuilder b;
    b.initialize(this);
    while (*s) {
        if (*s == base::consts::kFormatSpecifierChar) {
            if (*(s + 1) == base::consts::kFormatSpecifierChar) {
                ++s;
            } else {
                if (*(s + 1) == base::consts::kFormatSpecifierCharValue) {
                    ++s;
                    b << value;
                    log_(level, vlevel, ++s, args...);
                    return;
                }
            }
3714
        }
Y
youny626 已提交
3715
        b << *s++;
3716
    }
Y
youny626 已提交
3717
    ELPP_INTERNAL_ERROR("Too many arguments provided. Unable to handle. Please provide more format specifiers", false);
3718 3719
}
template <typename T>
Y
youny626 已提交
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
void
Logger::log_(Level level, int vlevel, const T& log) {
    if (level == Level::Verbose) {
        if (ELPP->vRegistry()->allowed(vlevel, __FILE__)) {
            base::Writer(Level::Verbose, "FILE", 0, "FUNCTION", base::DispatchAction::NormalLog, vlevel)
                    .construct(this, false)
                << log;
        } else {
            stream().str(ELPP_LITERAL(""));
            releaseLock();
        }
3731
    } else {
Y
youny626 已提交
3732
        base::Writer(level, "FILE", 0, "FUNCTION").construct(this, false) << log;
3733 3734 3735
    }
}
template <typename T, typename... Args>
Y
youny626 已提交
3736 3737 3738 3739
inline void
Logger::log(Level level, const char* s, const T& value, const Args&... args) {
    acquireLock();  // released in Writer!
    log_(level, 0, s, value, args...);
3740 3741
}
template <typename T>
Y
youny626 已提交
3742 3743 3744 3745
inline void
Logger::log(Level level, const T& log) {
    acquireLock();  // released in Writer!
    log_(level, 0, log);
3746
}
Y
youny626 已提交
3747
#if ELPP_VERBOSE_LOG
3748
template <typename T, typename... Args>
Y
youny626 已提交
3749 3750 3751 3752
inline void
Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) {
    acquireLock();  // released in Writer!
    log_(el::Level::Verbose, vlevel, s, value, args...);
3753 3754
}
template <typename T>
Y
youny626 已提交
3755 3756 3757 3758
inline void
Logger::verbose(int vlevel, const T& log) {
    acquireLock();  // released in Writer!
    log_(el::Level::Verbose, vlevel, log);
3759
}
Y
youny626 已提交
3760
#else
3761
template <typename T, typename... Args>
Y
youny626 已提交
3762 3763 3764
inline void
Logger::verbose(int, const char*, const T&, const Args&...) {
    return;
3765 3766
}
template <typename T>
Y
youny626 已提交
3767 3768 3769
inline void
Logger::verbose(int, const T&) {
    return;
3770
}
Y
youny626 已提交
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789
#endif  // ELPP_VERBOSE_LOG
#define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)                                      \
    template <typename T, typename... Args>                                                 \
    inline void Logger::FUNCTION_NAME(const char* s, const T& value, const Args&... args) { \
        log(LOG_LEVEL, s, value, args...);                                                  \
    }                                                                                       \
    template <typename T>                                                                   \
    inline void Logger::FUNCTION_NAME(const T& value) {                                     \
        log(LOG_LEVEL, value);                                                              \
    }
#define LOGGER_LEVEL_WRITERS_DISABLED(FUNCTION_NAME, LOG_LEVEL)                \
    template <typename T, typename... Args>                                    \
    inline void Logger::FUNCTION_NAME(const char*, const T&, const Args&...) { \
        return;                                                                \
    }                                                                          \
    template <typename T>                                                      \
    inline void Logger::FUNCTION_NAME(const T&) {                              \
        return;                                                                \
    }
3790

Y
youny626 已提交
3791
#if ELPP_INFO_LOG
3792
LOGGER_LEVEL_WRITERS(info, Level::Info)
Y
youny626 已提交
3793
#else
3794
LOGGER_LEVEL_WRITERS_DISABLED(info, Level::Info)
Y
youny626 已提交
3795 3796
#endif  // ELPP_INFO_LOG
#if ELPP_DEBUG_LOG
3797
LOGGER_LEVEL_WRITERS(debug, Level::Debug)
Y
youny626 已提交
3798
#else
3799
LOGGER_LEVEL_WRITERS_DISABLED(debug, Level::Debug)
Y
youny626 已提交
3800 3801
#endif  // ELPP_DEBUG_LOG
#if ELPP_WARNING_LOG
3802
LOGGER_LEVEL_WRITERS(warn, Level::Warning)
Y
youny626 已提交
3803
#else
3804
LOGGER_LEVEL_WRITERS_DISABLED(warn, Level::Warning)
Y
youny626 已提交
3805 3806
#endif  // ELPP_WARNING_LOG
#if ELPP_ERROR_LOG
3807
LOGGER_LEVEL_WRITERS(error, Level::Error)
Y
youny626 已提交
3808
#else
3809
LOGGER_LEVEL_WRITERS_DISABLED(error, Level::Error)
Y
youny626 已提交
3810 3811
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
3812
LOGGER_LEVEL_WRITERS(fatal, Level::Fatal)
Y
youny626 已提交
3813
#else
3814
LOGGER_LEVEL_WRITERS_DISABLED(fatal, Level::Fatal)
Y
youny626 已提交
3815 3816
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
3817
LOGGER_LEVEL_WRITERS(trace, Level::Trace)
Y
youny626 已提交
3818
#else
3819
LOGGER_LEVEL_WRITERS_DISABLED(trace, Level::Trace)
Y
youny626 已提交
3820 3821 3822 3823
#endif  // ELPP_TRACE_LOG
#undef LOGGER_LEVEL_WRITERS
#undef LOGGER_LEVEL_WRITERS_DISABLED
#endif  // ELPP_VARIADIC_TEMPLATES_SUPPORTED
3824
#if ELPP_COMPILER_MSVC
Y
youny626 已提交
3825 3826 3827 3828 3829 3830 3831
#define ELPP_VARIADIC_FUNC_MSVC(variadicFunction, variadicArgs) variadicFunction variadicArgs
#define ELPP_VARIADIC_FUNC_MSVC_RUN(variadicFunction, ...) ELPP_VARIADIC_FUNC_MSVC(variadicFunction, (__VA_ARGS__))
#define el_getVALength(...) \
    ELPP_VARIADIC_FUNC_MSVC_RUN(el_resolveVALength, 0, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#else
#if ELPP_COMPILER_CLANG
#define el_getVALength(...) el_resolveVALength(0, __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
3832
#else
Y
youny626 已提交
3833 3834 3835
#define el_getVALength(...) el_resolveVALength(0, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#endif  // ELPP_COMPILER_CLANG
#endif  // ELPP_COMPILER_MSVC
3836 3837
#define el_resolveVALength(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define ELPP_WRITE_LOG(writer, level, dispatchAction, ...) \
Y
youny626 已提交
3838 3839 3840 3841
    writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
#define ELPP_WRITE_LOG_IF(writer, condition, level, dispatchAction, ...) \
    if (condition)                                                       \
    writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
3842
#define ELPP_WRITE_LOG_EVERY_N(writer, occasion, level, dispatchAction, ...) \
Y
youny626 已提交
3843 3844 3845 3846 3847 3848 3849 3850 3851
    ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion) &&             \
        writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction)         \
            .construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
#define ELPP_WRITE_LOG_AFTER_N(writer, n, level, dispatchAction, ...)                                                  \
    ELPP->validateAfterNCounter(__FILE__, __LINE__, n) && writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction) \
                                                              .construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
#define ELPP_WRITE_LOG_N_TIMES(writer, n, level, dispatchAction, ...)                                                  \
    ELPP->validateNTimesCounter(__FILE__, __LINE__, n) && writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction) \
                                                              .construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
3852 3853 3854
#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
class PerformanceTrackingData {
 public:
Y
youny626 已提交
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
    enum class DataType : base::type::EnumType { Checkpoint = 1, Complete = 2 };
    // Do not use constructor, will run into multiple definition error, use init(PerformanceTracker*)
    explicit PerformanceTrackingData(DataType dataType)
        : m_performanceTracker(nullptr),
          m_dataType(dataType),
          m_firstCheckpoint(false),
          m_file(""),
          m_line(0),
          m_func("") {
    }
    inline const std::string*
    blockName(void) const;
    inline const struct timeval*
    startTime(void) const;
    inline const struct timeval*
    endTime(void) const;
    inline const struct timeval*
    lastCheckpointTime(void) const;
    inline const base::PerformanceTracker*
    performanceTracker(void) const {
        return m_performanceTracker;
    }
    inline PerformanceTrackingData::DataType
    dataType(void) const {
        return m_dataType;
    }
    inline bool
    firstCheckpoint(void) const {
        return m_firstCheckpoint;
    }
    inline std::string
    checkpointId(void) const {
        return m_checkpointId;
    }
    inline const char*
    file(void) const {
        return m_file;
    }
    inline base::type::LineNumber
    line(void) const {
        return m_line;
    }
    inline const char*
    func(void) const {
        return m_func;
    }
    inline const base::type::string_t*
    formattedTimeTaken() const {
        return &m_formattedTimeTaken;
    }
    inline const std::string&
    loggerId(void) const;

3908
 private:
Y
youny626 已提交
3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
    base::PerformanceTracker* m_performanceTracker;
    base::type::string_t m_formattedTimeTaken;
    PerformanceTrackingData::DataType m_dataType;
    bool m_firstCheckpoint;
    std::string m_checkpointId;
    const char* m_file;
    base::type::LineNumber m_line;
    const char* m_func;
    inline void
    init(base::PerformanceTracker* performanceTracker, bool firstCheckpoint = false) {
        m_performanceTracker = performanceTracker;
        m_firstCheckpoint = firstCheckpoint;
    }

    friend class el::base::PerformanceTracker;
3924 3925 3926 3927 3928 3929
};
namespace base {
/// @brief Represents performanceTracker block of code that conditionally adds performance status to log
///        either when goes outside the scope of when checkpoint() is called
class PerformanceTracker : public base::threading::ThreadSafe, public Loggable {
 public:
Y
youny626 已提交
3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
    PerformanceTracker(const std::string& blockName,
                       base::TimestampUnit timestampUnit = base::TimestampUnit::Millisecond,
                       const std::string& loggerId = std::string(el::base::consts::kPerformanceLoggerId),
                       bool scopedLog = true, Level level = base::consts::kPerformanceTrackerDefaultLevel);
    /// @brief Copy constructor
    PerformanceTracker(const PerformanceTracker& t)
        : m_blockName(t.m_blockName),
          m_timestampUnit(t.m_timestampUnit),
          m_loggerId(t.m_loggerId),
          m_scopedLog(t.m_scopedLog),
          m_level(t.m_level),
          m_hasChecked(t.m_hasChecked),
          m_lastCheckpointId(t.m_lastCheckpointId),
          m_enabled(t.m_enabled),
          m_startTime(t.m_startTime),
          m_endTime(t.m_endTime),
          m_lastCheckpointTime(t.m_lastCheckpointTime) {
    }
    virtual ~PerformanceTracker(void);
    /// @brief A checkpoint for current performanceTracker block.
    void
    checkpoint(const std::string& id = std::string(), const char* file = __FILE__,
               base::type::LineNumber line = __LINE__, const char* func = "");
    inline Level
    level(void) const {
        return m_level;
    }

3958
 private:
Y
youny626 已提交
3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
    std::string m_blockName;
    base::TimestampUnit m_timestampUnit;
    std::string m_loggerId;
    bool m_scopedLog;
    Level m_level;
    bool m_hasChecked;
    std::string m_lastCheckpointId;
    bool m_enabled;
    struct timeval m_startTime, m_endTime, m_lastCheckpointTime;

    PerformanceTracker(void);

    friend class el::PerformanceTrackingData;
    friend class base::DefaultPerformanceTrackingCallback;

    const inline base::type::string_t
    getFormattedTimeTaken() const {
        return getFormattedTimeTaken(m_startTime);
    }

    const base::type::string_t
    getFormattedTimeTaken(struct timeval startTime) const;

    virtual inline void
    log(el::base::type::ostream_t& os) const {
        os << getFormattedTimeTaken();
    }
3986 3987 3988
};
class DefaultPerformanceTrackingCallback : public PerformanceTrackingCallback {
 protected:
Y
youny626 已提交
3989 3990 3991 3992 3993 3994 3995
    void
    handle(const PerformanceTrackingData* data) {
        m_data = data;
        base::type::stringstream_t ss;
        if (m_data->dataType() == PerformanceTrackingData::DataType::Complete) {
            ss << ELPP_LITERAL("Executed [") << m_data->blockName()->c_str() << ELPP_LITERAL("] in [")
               << *m_data->formattedTimeTaken() << ELPP_LITERAL("]");
3996
        } else {
Y
youny626 已提交
3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
            ss << ELPP_LITERAL("Performance checkpoint");
            if (!m_data->checkpointId().empty()) {
                ss << ELPP_LITERAL(" [") << m_data->checkpointId().c_str() << ELPP_LITERAL("]");
            }
            ss << ELPP_LITERAL(" for block [") << m_data->blockName()->c_str() << ELPP_LITERAL("] : [")
               << *m_data->performanceTracker();
            if (!ELPP->hasFlag(LoggingFlag::DisablePerformanceTrackingCheckpointComparison) &&
                m_data->performanceTracker()->m_hasChecked) {
                ss << ELPP_LITERAL(" ([") << *m_data->formattedTimeTaken() << ELPP_LITERAL("] from ");
                if (m_data->performanceTracker()->m_lastCheckpointId.empty()) {
                    ss << ELPP_LITERAL("last checkpoint");
                } else {
                    ss << ELPP_LITERAL("checkpoint '") << m_data->performanceTracker()->m_lastCheckpointId.c_str()
                       << ELPP_LITERAL("'");
                }
                ss << ELPP_LITERAL(")]");
            } else {
                ss << ELPP_LITERAL("]");
            }
4016
        }
Y
youny626 已提交
4017 4018 4019 4020 4021
        el::base::Writer(m_data->performanceTracker()->level(), m_data->file(), m_data->line(), m_data->func())
                .construct(1, m_data->loggerId().c_str())
            << ss.str();
    }

4022
 private:
Y
youny626 已提交
4023
    const PerformanceTrackingData* m_data;
4024 4025
};
}  // namespace base
Y
youny626 已提交
4026 4027 4028
inline const std::string*
PerformanceTrackingData::blockName() const {
    return const_cast<const std::string*>(&m_performanceTracker->m_blockName);
4029
}
Y
youny626 已提交
4030 4031 4032
inline const struct timeval*
PerformanceTrackingData::startTime() const {
    return const_cast<const struct timeval*>(&m_performanceTracker->m_startTime);
4033
}
Y
youny626 已提交
4034 4035 4036
inline const struct timeval*
PerformanceTrackingData::endTime() const {
    return const_cast<const struct timeval*>(&m_performanceTracker->m_endTime);
4037
}
Y
youny626 已提交
4038 4039 4040
inline const struct timeval*
PerformanceTrackingData::lastCheckpointTime() const {
    return const_cast<const struct timeval*>(&m_performanceTracker->m_lastCheckpointTime);
4041
}
Y
youny626 已提交
4042 4043 4044
inline const std::string&
PerformanceTrackingData::loggerId(void) const {
    return m_performanceTracker->m_loggerId;
4045
}
Y
youny626 已提交
4046
#endif  // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
4047 4048 4049 4050 4051 4052
namespace base {
/// @brief Contains some internal debugging tools like crash handler and stack tracer
namespace debug {
#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
class StackTrace : base::NoCopy {
 public:
Y
youny626 已提交
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
    static const unsigned int kMaxStack = 64;
    static const unsigned int kStackStart = 2;  // We want to skip c'tor and StackTrace::generateNew()
    class StackTraceEntry {
     public:
        StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, const std::string& hex,
                        const std::string& addr);
        StackTraceEntry(std::size_t index, const std::string& loc) : m_index(index), m_location(loc) {
        }
        std::size_t m_index;
        std::string m_location;
        std::string m_demangled;
        std::string m_hex;
        std::string m_addr;
        friend std::ostream&
        operator<<(std::ostream& ss, const StackTraceEntry& si);

     private:
        StackTraceEntry(void);
    };

    StackTrace(void) {
        generateNew();
    }

    virtual ~StackTrace(void) {
    }

    inline std::vector<StackTraceEntry>&
    getLatestStack(void) {
        return m_stack;
    }

    friend std::ostream&
    operator<<(std::ostream& os, const StackTrace& st);
4087 4088

 private:
Y
youny626 已提交
4089
    std::vector<StackTraceEntry> m_stack;
4090

Y
youny626 已提交
4091 4092
    void
    generateNew(void);
4093 4094 4095 4096
};
/// @brief Handles unexpected crashes
class CrashHandler : base::NoCopy {
 public:
Y
youny626 已提交
4097
    typedef void (*Handler)(int);
4098

Y
youny626 已提交
4099 4100 4101 4102 4103 4104
    explicit CrashHandler(bool useDefault);
    explicit CrashHandler(const Handler& cHandler) {
        setHandler(cHandler);
    }
    void
    setHandler(const Handler& cHandler);
4105 4106

 private:
Y
youny626 已提交
4107
    Handler m_handler;
4108 4109 4110 4111
};
#else
class CrashHandler {
 public:
Y
youny626 已提交
4112 4113
    explicit CrashHandler(bool) {
    }
4114
};
Y
youny626 已提交
4115
#endif  // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
4116 4117 4118
}  // namespace debug
}  // namespace base
extern base::debug::CrashHandler elCrashHandler;
Y
youny626 已提交
4119 4120 4121
#define MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance)                      \
    el::base::type::ostream_t& operator<<(el::base::type::ostream_t& OutputStreamInstance, \
                                          const ClassType& ClassInstance)
4122 4123 4124
/// @brief Initializes syslog with process ID, options and facility. calls closelog() on d'tor
class SysLogInitializer {
 public:
Y
youny626 已提交
4125
    SysLogInitializer(const char* processIdent, int options = 0, int facility = 0) {
4126
#if defined(ELPP_SYSLOG)
Y
youny626 已提交
4127
        openlog(processIdent, options, facility);
4128
#else
Y
youny626 已提交
4129 4130 4131
        ELPP_UNUSED(processIdent);
        ELPP_UNUSED(options);
        ELPP_UNUSED(facility);
4132
#endif  // defined(ELPP_SYSLOG)
Y
youny626 已提交
4133 4134
    }
    virtual ~SysLogInitializer(void) {
4135
#if defined(ELPP_SYSLOG)
Y
youny626 已提交
4136
        closelog();
4137
#endif  // defined(ELPP_SYSLOG)
Y
youny626 已提交
4138
    }
4139 4140 4141 4142 4143
};
#define ELPP_INITIALIZE_SYSLOG(id, opt, fac) el::SysLogInitializer elSyslogInit(id, opt, fac)
/// @brief Static helpers for developers
class Helpers : base::StaticClass {
 public:
Y
youny626 已提交
4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172
    /// @brief Shares logging repository (base::Storage)
    static inline void
    setStorage(base::type::StoragePointer storage) {
        ELPP = storage;
    }
    /// @return Main storage repository
    static inline base::type::StoragePointer
    storage() {
        return ELPP;
    }
    /// @brief Sets application arguments and figures out whats active for logging and whats not.
    static inline void
    setArgs(int argc, char** argv) {
        ELPP->setApplicationArguments(argc, argv);
    }
    /// @copydoc setArgs(int argc, char** argv)
    static inline void
    setArgs(int argc, const char** argv) {
        ELPP->setApplicationArguments(argc, const_cast<char**>(argv));
    }
    /// @brief Sets thread name for current thread. Requires std::thread
    static inline void
    setThreadName(const std::string& name) {
        ELPP->setThreadName(name);
    }
    static inline std::string
    getThreadName() {
        return ELPP->getThreadName(base::threading::getCurrentThreadId());
    }
4173
#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
Y
youny626 已提交
4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
    /// @brief Overrides default crash handler and installs custom handler.
    /// @param crashHandler A functor with no return type that takes single int argument.
    ///        Handler is a typedef with specification: void (*Handler)(int)
    static inline void
    setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) {
        el::elCrashHandler.setHandler(crashHandler);
    }
    /// @brief Abort due to crash with signal in parameter
    /// @param sig Crash signal
    static void
    crashAbort(int sig, const char* sourceFile = "", unsigned int long line = 0);
    /// @brief Logs reason of crash as per sig
    /// @param sig Crash signal
    /// @param stackTraceIfAvailable Includes stack trace if available
    /// @param level Logging level
    /// @param logger Logger to use for logging
    static void
    logCrashReason(int sig, bool stackTraceIfAvailable = false, Level level = Level::Fatal,
                   const char* logger = base::consts::kDefaultLoggerId);
#endif  // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
    /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out
    ///        (can be useful for backing up)
    static inline void
    installPreRollOutCallback(const PreRollOutCallback& callback) {
        ELPP->setPreRollOutCallback(callback);
    }
    /// @brief Uninstalls pre rollout callback
    static inline void
    uninstallPreRollOutCallback(void) {
        ELPP->unsetPreRollOutCallback();
    }
    /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched
    template <typename T>
    static inline bool
    installLogDispatchCallback(const std::string& id) {
        return ELPP->installLogDispatchCallback<T>(id);
    }
    /// @brief Uninstalls log dispatch callback
    template <typename T>
    static inline void
    uninstallLogDispatchCallback(const std::string& id) {
        ELPP->uninstallLogDispatchCallback<T>(id);
    }
    template <typename T>
    static inline T*
    logDispatchCallback(const std::string& id) {
        return ELPP->logDispatchCallback<T>(id);
    }
4222
#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
Y
youny626 已提交
4223 4224 4225 4226 4227 4228
    /// @brief Installs post performance tracking callback, this callback is triggered when performance tracking is
    /// finished
    template <typename T>
    static inline bool
    installPerformanceTrackingCallback(const std::string& id) {
        return ELPP->installPerformanceTrackingCallback<T>(id);
4229
    }
Y
youny626 已提交
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254
    /// @brief Uninstalls post performance tracking handler
    template <typename T>
    static inline void
    uninstallPerformanceTrackingCallback(const std::string& id) {
        ELPP->uninstallPerformanceTrackingCallback<T>(id);
    }
    template <typename T>
    static inline T*
    performanceTrackingCallback(const std::string& id) {
        return ELPP->performanceTrackingCallback<T>(id);
    }
#endif  // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
    /// @brief Converts template to std::string - useful for loggable classes to log containers within
    /// log(std::ostream&) const
    template <typename T>
    static std::string
    convertTemplateToStdString(const T& templ) {
        el::Logger* logger = ELPP->registeredLoggers()->get(el::base::consts::kDefaultLoggerId);
        if (logger == nullptr) {
            return std::string();
        }
        base::MessageBuilder b;
        b.initialize(logger);
        logger->acquireLock();
        b << templ;
4255
#if defined(ELPP_UNICODE)
Y
youny626 已提交
4256
        std::string s = std::string(logger->stream().str().begin(), logger->stream().str().end());
4257
#else
Y
youny626 已提交
4258
        std::string s = logger->stream().str();
4259
#endif  // defined(ELPP_UNICODE)
Y
youny626 已提交
4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295
        logger->stream().str(ELPP_LITERAL(""));
        logger->releaseLock();
        return s;
    }
    /// @brief Returns command line arguments (pointer) provided to easylogging++
    static inline const el::base::utils::CommandLineArgs*
    commandLineArgs(void) {
        return ELPP->commandLineArgs();
    }
    /// @brief Reserve space for custom format specifiers for performance
    /// @see std::vector::reserve
    static inline void
    reserveCustomFormatSpecifiers(std::size_t size) {
        ELPP->m_customFormatSpecifiers.reserve(size);
    }
    /// @brief Installs user defined format specifier and handler
    static inline void
    installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
        ELPP->installCustomFormatSpecifier(customFormatSpecifier);
    }
    /// @brief Uninstalls user defined format specifier and handler
    static inline bool
    uninstallCustomFormatSpecifier(const char* formatSpecifier) {
        return ELPP->uninstallCustomFormatSpecifier(formatSpecifier);
    }
    /// @brief Returns true if custom format specifier is installed
    static inline bool
    hasCustomFormatSpecifier(const char* formatSpecifier) {
        return ELPP->hasCustomFormatSpecifier(formatSpecifier);
    }
    static inline void
    validateFileRolling(Logger* logger, Level level) {
        if (ELPP == nullptr || logger == nullptr)
            return;
        logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback());
    }
4296 4297 4298 4299
};
/// @brief Static helpers to deal with loggers and their configurations
class Loggers : base::StaticClass {
 public:
Y
youny626 已提交
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436
    /// @brief Gets existing or registers new logger
    static Logger*
    getLogger(const std::string& identity, bool registerIfNotAvailable = true);
    /// @brief Changes default log builder for future loggers
    static void
    setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr);
    /// @brief Installs logger registration callback, this callback is triggered when new logger is registered
    template <typename T>
    static inline bool
    installLoggerRegistrationCallback(const std::string& id) {
        return ELPP->registeredLoggers()->installLoggerRegistrationCallback<T>(id);
    }
    /// @brief Uninstalls log dispatch callback
    template <typename T>
    static inline void
    uninstallLoggerRegistrationCallback(const std::string& id) {
        ELPP->registeredLoggers()->uninstallLoggerRegistrationCallback<T>(id);
    }
    template <typename T>
    static inline T*
    loggerRegistrationCallback(const std::string& id) {
        return ELPP->registeredLoggers()->loggerRegistrationCallback<T>(id);
    }
    /// @brief Unregisters logger - use it only when you know what you are doing, you may unregister
    ///        loggers initialized / used by third-party libs.
    static bool
    unregisterLogger(const std::string& identity);
    /// @brief Whether or not logger with id is registered
    static bool
    hasLogger(const std::string& identity);
    /// @brief Reconfigures specified logger with new configurations
    static Logger*
    reconfigureLogger(Logger* logger, const Configurations& configurations);
    /// @brief Reconfigures logger with new configurations after looking it up using identity
    static Logger*
    reconfigureLogger(const std::string& identity, const Configurations& configurations);
    /// @brief Reconfigures logger's single configuration
    static Logger*
    reconfigureLogger(const std::string& identity, ConfigurationType configurationType, const std::string& value);
    /// @brief Reconfigures all the existing loggers with new configurations
    static void
    reconfigureAllLoggers(const Configurations& configurations);
    /// @brief Reconfigures single configuration for all the loggers
    static inline void
    reconfigureAllLoggers(ConfigurationType configurationType, const std::string& value) {
        reconfigureAllLoggers(Level::Global, configurationType, value);
    }
    /// @brief Reconfigures single configuration for all the loggers for specified level
    static void
    reconfigureAllLoggers(Level level, ConfigurationType configurationType, const std::string& value);
    /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing)
    /// loggers
    static void
    setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers = false);
    /// @brief Returns current default
    static const Configurations*
    defaultConfigurations(void);
    /// @brief Returns log stream reference pointer if needed by user
    static const base::LogStreamsReferenceMap*
    logStreamsReference(void);
    /// @brief Default typed configuration based on existing defaultConf
    static base::TypedConfigurations
    defaultTypedConfigurations(void);
    /// @brief Populates all logger IDs in current repository.
    /// @param [out] targetList List of fill up.
    static std::vector<std::string>*
    populateAllLoggerIds(std::vector<std::string>* targetList);
    /// @brief Sets configurations from global configuration file.
    static void
    configureFromGlobal(const char* globalConfigurationFilePath);
    /// @brief Configures loggers using command line arg. Ensure you have already set command line args,
    /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger.
    ///         If true is returned that does not mean it has been configured successfully, it only means that it
    ///         has attempeted to configure logger using configuration file provided in argument
    static bool
    configureFromArg(const char* argKey);
    /// @brief Flushes all loggers for all levels - Be careful if you dont know how many loggers are registered
    static void
    flushAll(void);
    /// @brief Adds logging flag used internally.
    static inline void
    addFlag(LoggingFlag flag) {
        ELPP->addFlag(flag);
    }
    /// @brief Removes logging flag used internally.
    static inline void
    removeFlag(LoggingFlag flag) {
        ELPP->removeFlag(flag);
    }
    /// @brief Determines whether or not certain flag is active
    static inline bool
    hasFlag(LoggingFlag flag) {
        return ELPP->hasFlag(flag);
    }
    /// @brief Adds flag and removes it when scope goes out
    class ScopedAddFlag {
     public:
        ScopedAddFlag(LoggingFlag flag) : m_flag(flag) {
            Loggers::addFlag(m_flag);
        }
        ~ScopedAddFlag(void) {
            Loggers::removeFlag(m_flag);
        }

     private:
        LoggingFlag m_flag;
    };
    /// @brief Removes flag and add it when scope goes out
    class ScopedRemoveFlag {
     public:
        ScopedRemoveFlag(LoggingFlag flag) : m_flag(flag) {
            Loggers::removeFlag(m_flag);
        }
        ~ScopedRemoveFlag(void) {
            Loggers::addFlag(m_flag);
        }

     private:
        LoggingFlag m_flag;
    };
    /// @brief Sets hierarchy for logging. Needs to enable logging flag (HierarchicalLogging)
    static void
    setLoggingLevel(Level level) {
        ELPP->setLoggingLevel(level);
    }
    /// @brief Sets verbose level on the fly
    static void
    setVerboseLevel(base::type::VerboseLevel level);
    /// @brief Gets current verbose level
    static base::type::VerboseLevel
    verboseLevel(void);
    /// @brief Sets vmodules as specified (on the fly)
    static void
    setVModules(const char* modules);
    /// @brief Clears vmodules
    static void
    clearVModules(void);
4437 4438 4439
};
class VersionInfo : base::StaticClass {
 public:
Y
youny626 已提交
4440 4441 4442
    /// @brief Current version number
    static const std::string
    version(void);
4443

Y
youny626 已提交
4444 4445 4446
    /// @brief Release date of current version
    static const std::string
    releaseDate(void);
4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
};
}  // namespace el
#undef VLOG_IS_ON
/// @brief Determines whether verbose logging is on for specified level current file.
#define VLOG_IS_ON(verboseLevel) (ELPP->vRegistry()->allowed(verboseLevel, __FILE__))
#undef TIMED_BLOCK
#undef TIMED_SCOPE
#undef TIMED_SCOPE_IF
#undef TIMED_FUNC
#undef TIMED_FUNC_IF
#undef ELPP_MIN_UNIT
#if defined(ELPP_PERFORMANCE_MICROSECONDS)
Y
youny626 已提交
4459
#define ELPP_MIN_UNIT el::base::TimestampUnit::Microsecond
4460
#else
Y
youny626 已提交
4461
#define ELPP_MIN_UNIT el::base::TimestampUnit::Millisecond
4462 4463 4464 4465 4466 4467 4468 4469
#endif  // (defined(ELPP_PERFORMANCE_MICROSECONDS))
/// @brief Performance tracked scope. Performance gets written when goes out of scope using
///        'performance' logger.
///
/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint();
/// @see el::base::PerformanceTracker
/// @see el::base::PerformanceTracker::checkpoint
// Note: Do not surround this definition with null macro because of obj instance
Y
youny626 已提交
4470 4471 4472
#define TIMED_SCOPE_IF(obj, blockname, condition)                                                                    \
    el::base::type::PerformanceTrackerPtr obj(condition ? new el::base::PerformanceTracker(blockname, ELPP_MIN_UNIT) \
                                                        : nullptr)
4473
#define TIMED_SCOPE(obj, blockname) TIMED_SCOPE_IF(obj, blockname, true)
Y
youny626 已提交
4474 4475 4476 4477 4478 4479 4480
#define TIMED_BLOCK(obj, blockName)                                                                                   \
    for (struct {                                                                                                     \
             int i;                                                                                                   \
             el::base::type::PerformanceTrackerPtr timer;                                                             \
         } obj = {0,                                                                                                  \
                  el::base::type::PerformanceTrackerPtr(new el::base::PerformanceTracker(blockName, ELPP_MIN_UNIT))}; \
         obj.i < 1; ++obj.i)
4481 4482 4483 4484 4485 4486
/// @brief Performance tracked function. Performance gets written when goes out of scope using
///        'performance' logger.
///
/// @detail Please note in order to check the performance at a certain time you can use obj->checkpoint();
/// @see el::base::PerformanceTracker
/// @see el::base::PerformanceTracker::checkpoint
Y
youny626 已提交
4487
#define TIMED_FUNC_IF(obj, condition) TIMED_SCOPE_IF(obj, ELPP_FUNC, condition)
4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
#define TIMED_FUNC(obj) TIMED_SCOPE(obj, ELPP_FUNC)
#undef PERFORMANCE_CHECKPOINT
#undef PERFORMANCE_CHECKPOINT_WITH_ID
#define PERFORMANCE_CHECKPOINT(obj) obj->checkpoint(std::string(), __FILE__, __LINE__, ELPP_FUNC)
#define PERFORMANCE_CHECKPOINT_WITH_ID(obj, id) obj->checkpoint(id, __FILE__, __LINE__, ELPP_FUNC)
#undef ELPP_COUNTER
#undef ELPP_COUNTER_POS
/// @brief Gets hit counter for file/line
#define ELPP_COUNTER (ELPP->hitCounters()->getCounter(__FILE__, __LINE__))
/// @brief Gets hit counter position for file/line, -1 if not registered yet
#define ELPP_COUNTER_POS (ELPP_COUNTER == nullptr ? -1 : ELPP_COUNTER->hitCounts())
// Undef levels to support LOG(LEVEL)
#undef INFO
#undef WARNING
#undef DEBUG
#undef ERROR
#undef FATAL
#undef TRACE
#undef VERBOSE
// Undef existing
#undef CINFO
#undef CWARNING
#undef CDEBUG
#undef CFATAL
#undef CERROR
#undef CTRACE
#undef CVERBOSE
#undef CINFO_IF
#undef CWARNING_IF
#undef CDEBUG_IF
#undef CERROR_IF
#undef CFATAL_IF
#undef CTRACE_IF
#undef CVERBOSE_IF
#undef CINFO_EVERY_N
#undef CWARNING_EVERY_N
#undef CDEBUG_EVERY_N
#undef CERROR_EVERY_N
#undef CFATAL_EVERY_N
#undef CTRACE_EVERY_N
#undef CVERBOSE_EVERY_N
#undef CINFO_AFTER_N
#undef CWARNING_AFTER_N
#undef CDEBUG_AFTER_N
#undef CERROR_AFTER_N
#undef CFATAL_AFTER_N
#undef CTRACE_AFTER_N
#undef CVERBOSE_AFTER_N
#undef CINFO_N_TIMES
#undef CWARNING_N_TIMES
#undef CDEBUG_N_TIMES
#undef CERROR_N_TIMES
#undef CFATAL_N_TIMES
#undef CTRACE_N_TIMES
#undef CVERBOSE_N_TIMES
// Normal logs
#if ELPP_INFO_LOG
Y
youny626 已提交
4545
#define CINFO(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Info, dispatchAction, __VA_ARGS__)
4546
#else
Y
youny626 已提交
4547
#define CINFO(writer, dispatchAction, ...) el::base::NullWriter()
4548 4549
#endif  // ELPP_INFO_LOG
#if ELPP_WARNING_LOG
Y
youny626 已提交
4550
#define CWARNING(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Warning, dispatchAction, __VA_ARGS__)
4551
#else
Y
youny626 已提交
4552
#define CWARNING(writer, dispatchAction, ...) el::base::NullWriter()
4553 4554
#endif  // ELPP_WARNING_LOG
#if ELPP_DEBUG_LOG
Y
youny626 已提交
4555
#define CDEBUG(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Debug, dispatchAction, __VA_ARGS__)
4556
#else
Y
youny626 已提交
4557
#define CDEBUG(writer, dispatchAction, ...) el::base::NullWriter()
4558 4559
#endif  // ELPP_DEBUG_LOG
#if ELPP_ERROR_LOG
Y
youny626 已提交
4560
#define CERROR(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Error, dispatchAction, __VA_ARGS__)
4561
#else
Y
youny626 已提交
4562
#define CERROR(writer, dispatchAction, ...) el::base::NullWriter()
4563 4564
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
Y
youny626 已提交
4565
#define CFATAL(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Fatal, dispatchAction, __VA_ARGS__)
4566
#else
Y
youny626 已提交
4567
#define CFATAL(writer, dispatchAction, ...) el::base::NullWriter()
4568 4569
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
Y
youny626 已提交
4570
#define CTRACE(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Trace, dispatchAction, __VA_ARGS__)
4571
#else
Y
youny626 已提交
4572
#define CTRACE(writer, dispatchAction, ...) el::base::NullWriter()
4573 4574
#endif  // ELPP_TRACE_LOG
#if ELPP_VERBOSE_LOG
Y
youny626 已提交
4575 4576 4577 4578
#define CVERBOSE(writer, vlevel, dispatchAction, ...)                                 \
    if (VLOG_IS_ON(vlevel))                                                           \
    writer(el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel) \
        .construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
4579
#else
Y
youny626 已提交
4580
#define CVERBOSE(writer, vlevel, dispatchAction, ...) el::base::NullWriter()
4581 4582 4583
#endif  // ELPP_VERBOSE_LOG
// Conditional logs
#if ELPP_INFO_LOG
Y
youny626 已提交
4584 4585
#define CINFO_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Info, dispatchAction, __VA_ARGS__)
4586
#else
Y
youny626 已提交
4587
#define CINFO_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4588 4589
#endif  // ELPP_INFO_LOG
#if ELPP_WARNING_LOG
Y
youny626 已提交
4590 4591
#define CWARNING_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Warning, dispatchAction, __VA_ARGS__)
4592
#else
Y
youny626 已提交
4593
#define CWARNING_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4594 4595
#endif  // ELPP_WARNING_LOG
#if ELPP_DEBUG_LOG
Y
youny626 已提交
4596 4597
#define CDEBUG_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Debug, dispatchAction, __VA_ARGS__)
4598
#else
Y
youny626 已提交
4599
#define CDEBUG_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4600 4601
#endif  // ELPP_DEBUG_LOG
#if ELPP_ERROR_LOG
Y
youny626 已提交
4602 4603
#define CERROR_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Error, dispatchAction, __VA_ARGS__)
4604
#else
Y
youny626 已提交
4605
#define CERROR_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4606 4607
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
Y
youny626 已提交
4608 4609
#define CFATAL_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Fatal, dispatchAction, __VA_ARGS__)
4610
#else
Y
youny626 已提交
4611
#define CFATAL_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4612 4613
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
Y
youny626 已提交
4614 4615
#define CTRACE_IF(writer, condition_, dispatchAction, ...) \
    ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Trace, dispatchAction, __VA_ARGS__)
4616
#else
Y
youny626 已提交
4617
#define CTRACE_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter()
4618 4619
#endif  // ELPP_TRACE_LOG
#if ELPP_VERBOSE_LOG
Y
youny626 已提交
4620 4621 4622 4623
#define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...)                  \
    if (VLOG_IS_ON(vlevel) && (condition_))                                           \
    writer(el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel) \
        .construct(el_getVALength(__VA_ARGS__), __VA_ARGS__)
4624
#else
Y
youny626 已提交
4625
#define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) el::base::NullWriter()
4626 4627 4628
#endif  // ELPP_VERBOSE_LOG
// Occasional logs
#if ELPP_INFO_LOG
Y
youny626 已提交
4629 4630
#define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Info, dispatchAction, __VA_ARGS__)
4631
#else
Y
youny626 已提交
4632
#define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4633 4634
#endif  // ELPP_INFO_LOG
#if ELPP_WARNING_LOG
Y
youny626 已提交
4635 4636
#define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Warning, dispatchAction, __VA_ARGS__)
4637
#else
Y
youny626 已提交
4638
#define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4639 4640
#endif  // ELPP_WARNING_LOG
#if ELPP_DEBUG_LOG
Y
youny626 已提交
4641 4642
#define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Debug, dispatchAction, __VA_ARGS__)
4643
#else
Y
youny626 已提交
4644
#define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4645 4646
#endif  // ELPP_DEBUG_LOG
#if ELPP_ERROR_LOG
Y
youny626 已提交
4647 4648
#define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Error, dispatchAction, __VA_ARGS__)
4649
#else
Y
youny626 已提交
4650
#define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4651 4652
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
Y
youny626 已提交
4653 4654
#define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Fatal, dispatchAction, __VA_ARGS__)
4655
#else
Y
youny626 已提交
4656
#define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4657 4658
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
Y
youny626 已提交
4659 4660
#define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) \
    ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Trace, dispatchAction, __VA_ARGS__)
4661
#else
Y
youny626 已提交
4662
#define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter()
4663 4664
#endif  // ELPP_TRACE_LOG
#if ELPP_VERBOSE_LOG
Y
youny626 已提交
4665 4666
#define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) \
    CVERBOSE_IF(writer, ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion), vlevel, dispatchAction, __VA_ARGS__)
4667
#else
Y
youny626 已提交
4668
#define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) el::base::NullWriter()
4669 4670 4671
#endif  // ELPP_VERBOSE_LOG
// After N logs
#if ELPP_INFO_LOG
Y
youny626 已提交
4672 4673
#define CINFO_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__)
4674
#else
Y
youny626 已提交
4675
#define CINFO_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4676 4677
#endif  // ELPP_INFO_LOG
#if ELPP_WARNING_LOG
Y
youny626 已提交
4678 4679
#define CWARNING_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__)
4680
#else
Y
youny626 已提交
4681
#define CWARNING_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4682 4683
#endif  // ELPP_WARNING_LOG
#if ELPP_DEBUG_LOG
Y
youny626 已提交
4684 4685
#define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__)
4686
#else
Y
youny626 已提交
4687
#define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4688 4689
#endif  // ELPP_DEBUG_LOG
#if ELPP_ERROR_LOG
Y
youny626 已提交
4690 4691
#define CERROR_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__)
4692
#else
Y
youny626 已提交
4693
#define CERROR_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4694 4695
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
Y
youny626 已提交
4696 4697
#define CFATAL_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__)
4698
#else
Y
youny626 已提交
4699
#define CFATAL_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4700 4701
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
Y
youny626 已提交
4702 4703
#define CTRACE_AFTER_N(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__)
4704
#else
Y
youny626 已提交
4705
#define CTRACE_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter()
4706 4707
#endif  // ELPP_TRACE_LOG
#if ELPP_VERBOSE_LOG
Y
youny626 已提交
4708 4709
#define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) \
    CVERBOSE_IF(writer, ELPP->validateAfterNCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__)
4710
#else
Y
youny626 已提交
4711
#define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter()
4712 4713 4714
#endif  // ELPP_VERBOSE_LOG
// N Times logs
#if ELPP_INFO_LOG
Y
youny626 已提交
4715 4716
#define CINFO_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__)
4717
#else
Y
youny626 已提交
4718
#define CINFO_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4719 4720
#endif  // ELPP_INFO_LOG
#if ELPP_WARNING_LOG
Y
youny626 已提交
4721 4722
#define CWARNING_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__)
4723
#else
Y
youny626 已提交
4724
#define CWARNING_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4725 4726
#endif  // ELPP_WARNING_LOG
#if ELPP_DEBUG_LOG
Y
youny626 已提交
4727 4728
#define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__)
4729
#else
Y
youny626 已提交
4730
#define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4731 4732
#endif  // ELPP_DEBUG_LOG
#if ELPP_ERROR_LOG
Y
youny626 已提交
4733 4734
#define CERROR_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__)
4735
#else
Y
youny626 已提交
4736
#define CERROR_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4737 4738
#endif  // ELPP_ERROR_LOG
#if ELPP_FATAL_LOG
Y
youny626 已提交
4739 4740
#define CFATAL_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__)
4741
#else
Y
youny626 已提交
4742
#define CFATAL_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4743 4744
#endif  // ELPP_FATAL_LOG
#if ELPP_TRACE_LOG
Y
youny626 已提交
4745 4746
#define CTRACE_N_TIMES(writer, n, dispatchAction, ...) \
    ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__)
4747
#else
Y
youny626 已提交
4748
#define CTRACE_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter()
4749 4750
#endif  // ELPP_TRACE_LOG
#if ELPP_VERBOSE_LOG
Y
youny626 已提交
4751 4752
#define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) \
    CVERBOSE_IF(writer, ELPP->validateNTimesCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__)
4753
#else
Y
youny626 已提交
4754
#define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter()
4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772
#endif  // ELPP_VERBOSE_LOG
//
// Custom Loggers - Requires (level, dispatchAction, loggerId/s)
//
// undef existing
#undef CLOG
#undef CLOG_VERBOSE
#undef CVLOG
#undef CLOG_IF
#undef CLOG_VERBOSE_IF
#undef CVLOG_IF
#undef CLOG_EVERY_N
#undef CVLOG_EVERY_N
#undef CLOG_AFTER_N
#undef CVLOG_AFTER_N
#undef CLOG_N_TIMES
#undef CVLOG_N_TIMES
// Normal logs
Y
youny626 已提交
4773
#define CLOG(LEVEL, ...) C##LEVEL(el::base::Writer, el::base::DispatchAction::NormalLog, __VA_ARGS__)
4774 4775
#define CVLOG(vlevel, ...) CVERBOSE(el::base::Writer, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
// Conditional logs
Y
youny626 已提交
4776 4777 4778 4779
#define CLOG_IF(condition, LEVEL, ...) \
    C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CVLOG_IF(condition, vlevel, ...) \
    CVERBOSE_IF(el::base::Writer, condition, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
4780
// Hit counts based logs
Y
youny626 已提交
4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792
#define CLOG_EVERY_N(n, LEVEL, ...) \
    C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CVLOG_EVERY_N(n, vlevel, ...) \
    CVERBOSE_EVERY_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CLOG_AFTER_N(n, LEVEL, ...) \
    C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CVLOG_AFTER_N(n, vlevel, ...) \
    CVERBOSE_AFTER_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CLOG_N_TIMES(n, LEVEL, ...) \
    C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CVLOG_N_TIMES(n, vlevel, ...) \
    CVERBOSE_N_TIMES(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__)
4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808
//
// Default Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros
//
// undef existing
#undef LOG
#undef VLOG
#undef LOG_IF
#undef VLOG_IF
#undef LOG_EVERY_N
#undef VLOG_EVERY_N
#undef LOG_AFTER_N
#undef VLOG_AFTER_N
#undef LOG_N_TIMES
#undef VLOG_N_TIMES
#undef ELPP_CURR_FILE_LOGGER_ID
#if defined(ELPP_DEFAULT_LOGGER)
Y
youny626 已提交
4809
#define ELPP_CURR_FILE_LOGGER_ID ELPP_DEFAULT_LOGGER
4810
#else
Y
youny626 已提交
4811
#define ELPP_CURR_FILE_LOGGER_ID el::base::consts::kDefaultLoggerId
4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836
#endif
#undef ELPP_TRACE
#define ELPP_TRACE CLOG(TRACE, ELPP_CURR_FILE_LOGGER_ID)
// Normal logs
#define LOG(LEVEL) CLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define VLOG(vlevel) CVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID)
// Conditional logs
#define LOG_IF(condition, LEVEL) CLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define VLOG_IF(condition, vlevel) CVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID)
// Hit counts based logs
#define LOG_EVERY_N(n, LEVEL) CLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define VLOG_EVERY_N(n, vlevel) CVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
#define LOG_AFTER_N(n, LEVEL) CLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define VLOG_AFTER_N(n, vlevel) CVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
#define LOG_N_TIMES(n, LEVEL) CLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define VLOG_N_TIMES(n, vlevel) CVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
// Generic PLOG()
#undef CPLOG
#undef CPLOG_IF
#undef PLOG
#undef PLOG_IF
#undef DCPLOG
#undef DCPLOG_IF
#undef DPLOG
#undef DPLOG_IF
Y
youny626 已提交
4837 4838 4839 4840 4841 4842 4843 4844 4845
#define CPLOG(LEVEL, ...) C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define CPLOG_IF(condition, LEVEL, ...) \
    C##LEVEL##_IF(el::base::PErrorWriter, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define DCPLOG(LEVEL, ...) \
    if (ELPP_DEBUG_LOG)    \
    C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__)
#define DCPLOG_IF(condition, LEVEL, ...)                                                                        \
    C##LEVEL##_IF(el::base::PErrorWriter, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::NormalLog, \
                  __VA_ARGS__)
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871
#define PLOG(LEVEL) CPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define PLOG_IF(condition, LEVEL) CPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DPLOG(LEVEL) DCPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DPLOG_IF(condition, LEVEL) DCPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
// Generic SYSLOG()
#undef CSYSLOG
#undef CSYSLOG_IF
#undef CSYSLOG_EVERY_N
#undef CSYSLOG_AFTER_N
#undef CSYSLOG_N_TIMES
#undef SYSLOG
#undef SYSLOG_IF
#undef SYSLOG_EVERY_N
#undef SYSLOG_AFTER_N
#undef SYSLOG_N_TIMES
#undef DCSYSLOG
#undef DCSYSLOG_IF
#undef DCSYSLOG_EVERY_N
#undef DCSYSLOG_AFTER_N
#undef DCSYSLOG_N_TIMES
#undef DSYSLOG
#undef DSYSLOG_IF
#undef DSYSLOG_EVERY_N
#undef DSYSLOG_AFTER_N
#undef DSYSLOG_N_TIMES
#if defined(ELPP_SYSLOG)
Y
youny626 已提交
4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904
#define CSYSLOG(LEVEL, ...) C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define CSYSLOG_IF(condition, LEVEL, ...) \
    C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define CSYSLOG_EVERY_N(n, LEVEL, ...) \
    C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define CSYSLOG_AFTER_N(n, LEVEL, ...) \
    C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define CSYSLOG_N_TIMES(n, LEVEL, ...) \
    C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define SYSLOG(LEVEL) CSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId)
#define SYSLOG_IF(condition, LEVEL) CSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId)
#define SYSLOG_EVERY_N(n, LEVEL) CSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
#define SYSLOG_AFTER_N(n, LEVEL) CSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
#define SYSLOG_N_TIMES(n, LEVEL) CSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId)
#define DCSYSLOG(LEVEL, ...) \
    if (ELPP_DEBUG_LOG)      \
    C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define DCSYSLOG_IF(condition, LEVEL, ...) \
    C##LEVEL##_IF(el::base::Writer, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::SysLog, __VA_ARGS__)
#define DCSYSLOG_EVERY_N(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)                 \
    C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define DCSYSLOG_AFTER_N(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)                 \
    C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define DCSYSLOG_N_TIMES(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)                 \
    C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__)
#define DSYSLOG(LEVEL) DCSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId)
#define DSYSLOG_IF(condition, LEVEL) DCSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId)
#define DSYSLOG_EVERY_N(n, LEVEL) DCSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
#define DSYSLOG_AFTER_N(n, LEVEL) DCSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId)
#define DSYSLOG_N_TIMES(n, LEVEL) DCSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId)
4905
#else
Y
youny626 已提交
4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925
#define CSYSLOG(LEVEL, ...) el::base::NullWriter()
#define CSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter()
#define CSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter()
#define CSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter()
#define CSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter()
#define SYSLOG(LEVEL) el::base::NullWriter()
#define SYSLOG_IF(condition, LEVEL) el::base::NullWriter()
#define SYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter()
#define SYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter()
#define SYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter()
#define DCSYSLOG(LEVEL, ...) el::base::NullWriter()
#define DCSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter()
#define DCSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter()
#define DCSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter()
#define DCSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter()
#define DSYSLOG(LEVEL) el::base::NullWriter()
#define DSYSLOG_IF(condition, LEVEL) el::base::NullWriter()
#define DSYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter()
#define DSYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter()
#define DSYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter()
4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
#endif  // defined(ELPP_SYSLOG)
//
// Custom Debug Only Loggers - Requires (level, loggerId/s)
//
// undef existing
#undef DCLOG
#undef DCVLOG
#undef DCLOG_IF
#undef DCVLOG_IF
#undef DCLOG_EVERY_N
#undef DCVLOG_EVERY_N
#undef DCLOG_AFTER_N
#undef DCVLOG_AFTER_N
#undef DCLOG_N_TIMES
#undef DCVLOG_N_TIMES
// Normal logs
Y
youny626 已提交
4942 4943 4944 4945 4946 4947 4948 4949 4950
#define DCLOG(LEVEL, ...) \
    if (ELPP_DEBUG_LOG)   \
    CLOG(LEVEL, __VA_ARGS__)
#define DCLOG_VERBOSE(vlevel, ...) \
    if (ELPP_DEBUG_LOG)            \
    CLOG_VERBOSE(vlevel, __VA_ARGS__)
#define DCVLOG(vlevel, ...) \
    if (ELPP_DEBUG_LOG)     \
    CVLOG(vlevel, __VA_ARGS__)
4951
// Conditional logs
Y
youny626 已提交
4952 4953 4954 4955 4956 4957
#define DCLOG_IF(condition, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)                 \
    CLOG_IF(condition, LEVEL, __VA_ARGS__)
#define DCVLOG_IF(condition, vlevel, ...) \
    if (ELPP_DEBUG_LOG)                   \
    CVLOG_IF(condition, vlevel, __VA_ARGS__)
4958
// Hit counts based logs
Y
youny626 已提交
4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
#define DCLOG_EVERY_N(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)              \
    CLOG_EVERY_N(n, LEVEL, __VA_ARGS__)
#define DCVLOG_EVERY_N(n, vlevel, ...) \
    if (ELPP_DEBUG_LOG)                \
    CVLOG_EVERY_N(n, vlevel, __VA_ARGS__)
#define DCLOG_AFTER_N(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)              \
    CLOG_AFTER_N(n, LEVEL, __VA_ARGS__)
#define DCVLOG_AFTER_N(n, vlevel, ...) \
    if (ELPP_DEBUG_LOG)                \
    CVLOG_AFTER_N(n, vlevel, __VA_ARGS__)
#define DCLOG_N_TIMES(n, LEVEL, ...) \
    if (ELPP_DEBUG_LOG)              \
    CLOG_N_TIMES(n, LEVEL, __VA_ARGS__)
#define DCVLOG_N_TIMES(n, vlevel, ...) \
    if (ELPP_DEBUG_LOG)                \
    CVLOG_N_TIMES(n, vlevel, __VA_ARGS__)
4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004
//
// Default Debug Only Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros
//
#if !defined(ELPP_NO_DEBUG_MACROS)
// undef existing
#undef DLOG
#undef DVLOG
#undef DLOG_IF
#undef DVLOG_IF
#undef DLOG_EVERY_N
#undef DVLOG_EVERY_N
#undef DLOG_AFTER_N
#undef DVLOG_AFTER_N
#undef DLOG_N_TIMES
#undef DVLOG_N_TIMES
// Normal logs
#define DLOG(LEVEL) DCLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DVLOG(vlevel) DCVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID)
// Conditional logs
#define DLOG_IF(condition, LEVEL) DCLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DVLOG_IF(condition, vlevel) DCVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID)
// Hit counts based logs
#define DLOG_EVERY_N(n, LEVEL) DCLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DVLOG_EVERY_N(n, vlevel) DCVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
#define DLOG_AFTER_N(n, LEVEL) DCLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DVLOG_AFTER_N(n, vlevel) DCVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
#define DLOG_N_TIMES(n, LEVEL) DCLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID)
#define DVLOG_N_TIMES(n, vlevel) DCVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID)
Y
youny626 已提交
5005
#endif  // defined(ELPP_NO_DEBUG_MACROS)
5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
#if !defined(ELPP_NO_CHECK_MACROS)
// Check macros
#undef CCHECK
#undef CPCHECK
#undef CCHECK_EQ
#undef CCHECK_NE
#undef CCHECK_LT
#undef CCHECK_GT
#undef CCHECK_LE
#undef CCHECK_GE
#undef CCHECK_BOUNDS
#undef CCHECK_NOTNULL
#undef CCHECK_STRCASEEQ
#undef CCHECK_STRCASENE
#undef CHECK
#undef PCHECK
#undef CHECK_EQ
#undef CHECK_NE
#undef CHECK_LT
#undef CHECK_GT
#undef CHECK_LE
#undef CHECK_GE
#undef CHECK_BOUNDS
#undef CHECK_NOTNULL
#undef CHECK_STRCASEEQ
#undef CHECK_STRCASENE
#define CCHECK(condition, ...) CLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] "
#define CPCHECK(condition, ...) CPLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] "
#define CHECK(condition) CCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
#define PCHECK(condition) CPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
#define CCHECK_EQ(a, b, ...) CCHECK(a == b, __VA_ARGS__)
#define CCHECK_NE(a, b, ...) CCHECK(a != b, __VA_ARGS__)
#define CCHECK_LT(a, b, ...) CCHECK(a < b, __VA_ARGS__)
#define CCHECK_GT(a, b, ...) CCHECK(a > b, __VA_ARGS__)
#define CCHECK_LE(a, b, ...) CCHECK(a <= b, __VA_ARGS__)
#define CCHECK_GE(a, b, ...) CCHECK(a >= b, __VA_ARGS__)
#define CCHECK_BOUNDS(val, min, max, ...) CCHECK(val >= min && val <= max, __VA_ARGS__)
#define CHECK_EQ(a, b) CCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_NE(a, b) CCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_LT(a, b) CCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_GT(a, b) CCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_LE(a, b) CCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_GE(a, b) CCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_BOUNDS(val, min, max) CCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID)
#define CCHECK_NOTNULL(ptr, ...) CCHECK((ptr) != nullptr, __VA_ARGS__)
Y
youny626 已提交
5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062
#define CCHECK_STREQ(str1, str2, ...)                                         \
    CLOG_IF(!el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \
        << "Check failed: [" << #str1 << " == " << #str2 << "] "
#define CCHECK_STRNE(str1, str2, ...)                                        \
    CLOG_IF(el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \
        << "Check failed: [" << #str1 << " != " << #str2 << "] "
#define CCHECK_STRCASEEQ(str1, str2, ...)                                         \
    CLOG_IF(!el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \
        << "Check failed: [" << #str1 << " == " << #str2 << "] "
#define CCHECK_STRCASENE(str1, str2, ...)                                        \
    CLOG_IF(el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \
        << "Check failed: [" << #str1 << " != " << #str2 << "] "
5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
#define CHECK_NOTNULL(ptr) CCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_STREQ(str1, str2) CCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_STRNE(str1, str2) CCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_STRCASEEQ(str1, str2) CCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define CHECK_STRCASENE(str1, str2) CCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#undef DCCHECK
#undef DCCHECK_EQ
#undef DCCHECK_NE
#undef DCCHECK_LT
#undef DCCHECK_GT
#undef DCCHECK_LE
#undef DCCHECK_GE
#undef DCCHECK_BOUNDS
#undef DCCHECK_NOTNULL
#undef DCCHECK_STRCASEEQ
#undef DCCHECK_STRCASENE
#undef DCPCHECK
#undef DCHECK
#undef DCHECK_EQ
#undef DCHECK_NE
#undef DCHECK_LT
#undef DCHECK_GT
#undef DCHECK_LE
#undef DCHECK_GE
#undef DCHECK_BOUNDS_
#undef DCHECK_NOTNULL
#undef DCHECK_STRCASEEQ
#undef DCHECK_STRCASENE
#undef DPCHECK
Y
youny626 已提交
5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133
#define DCCHECK(condition, ...) \
    if (ELPP_DEBUG_LOG)         \
    CCHECK(condition, __VA_ARGS__)
#define DCCHECK_EQ(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_EQ(a, b, __VA_ARGS__)
#define DCCHECK_NE(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_NE(a, b, __VA_ARGS__)
#define DCCHECK_LT(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_LT(a, b, __VA_ARGS__)
#define DCCHECK_GT(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_GT(a, b, __VA_ARGS__)
#define DCCHECK_LE(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_LE(a, b, __VA_ARGS__)
#define DCCHECK_GE(a, b, ...) \
    if (ELPP_DEBUG_LOG)       \
    CCHECK_GE(a, b, __VA_ARGS__)
#define DCCHECK_BOUNDS(val, min, max, ...) \
    if (ELPP_DEBUG_LOG)                    \
    CCHECK_BOUNDS(val, min, max, __VA_ARGS__)
#define DCCHECK_NOTNULL(ptr, ...) \
    if (ELPP_DEBUG_LOG)           \
    CCHECK_NOTNULL((ptr), __VA_ARGS__)
#define DCCHECK_STREQ(str1, str2, ...) \
    if (ELPP_DEBUG_LOG)                \
    CCHECK_STREQ(str1, str2, __VA_ARGS__)
#define DCCHECK_STRNE(str1, str2, ...) \
    if (ELPP_DEBUG_LOG)                \
    CCHECK_STRNE(str1, str2, __VA_ARGS__)
#define DCCHECK_STRCASEEQ(str1, str2, ...) \
    if (ELPP_DEBUG_LOG)                    \
    CCHECK_STRCASEEQ(str1, str2, __VA_ARGS__)
#define DCCHECK_STRCASENE(str1, str2, ...) \
    if (ELPP_DEBUG_LOG)                    \
    CCHECK_STRCASENE(str1, str2, __VA_ARGS__)
#define DCPCHECK(condition, ...) \
    if (ELPP_DEBUG_LOG)          \
    CPCHECK(condition, __VA_ARGS__)
5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147
#define DCHECK(condition) DCCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_EQ(a, b) DCCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_NE(a, b) DCCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_LT(a, b) DCCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_GT(a, b) DCCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_LE(a, b) DCCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_GE(a, b) DCCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_BOUNDS(val, min, max) DCCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_NOTNULL(ptr) DCCHECK_NOTNULL((ptr), ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_STREQ(str1, str2) DCCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_STRNE(str1, str2) DCCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_STRCASEEQ(str1, str2) DCCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define DCHECK_STRCASENE(str1, str2) DCCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID)
#define DPCHECK(condition) DCPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID)
Y
youny626 已提交
5148
#endif  // defined(ELPP_NO_CHECK_MACROS)
5149
#if defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING)
Y
youny626 已提交
5150
#define ELPP_USE_DEF_CRASH_HANDLER false
5151
#else
Y
youny626 已提交
5152
#define ELPP_USE_DEF_CRASH_HANDLER true
5153 5154
#endif  // defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING)
#define ELPP_CRASH_HANDLER_INIT
Y
youny626 已提交
5155 5156 5157 5158 5159 5160 5161
#define ELPP_INIT_EASYLOGGINGPP(val)                                          \
    namespace el {                                                            \
    namespace base {                                                          \
    el::base::type::StoragePointer elStorage(val);                            \
    }                                                                         \
    el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \
    }
5162 5163

#if ELPP_ASYNC_LOGGING
Y
youny626 已提交
5164 5165 5166
#define INITIALIZE_EASYLOGGINGPP                                                                        \
    ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()), \
                                                  new el::base::AsyncDispatchWorker()))
5167
#else
Y
youny626 已提交
5168 5169
#define INITIALIZE_EASYLOGGINGPP \
    ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder())))
5170
#endif  // ELPP_ASYNC_LOGGING
Y
youny626 已提交
5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
#define INITIALIZE_NULL_EASYLOGGINGPP                                         \
    namespace el {                                                            \
    namespace base {                                                          \
    el::base::type::StoragePointer elStorage;                                 \
    }                                                                         \
    el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \
    }
#define SHARE_EASYLOGGINGPP(initializedStorage)                               \
    namespace el {                                                            \
    namespace base {                                                          \
    el::base::type::StoragePointer elStorage(initializedStorage);             \
    }                                                                         \
    el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER); \
    }
5185 5186

#if defined(ELPP_UNICODE)
Y
youny626 已提交
5187 5188 5189
#define START_EASYLOGGINGPP(argc, argv) \
    el::Helpers::setArgs(argc, argv);   \
    std::locale::global(std::locale(""))
5190
#else
Y
youny626 已提交
5191
#define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv)
5192
#endif  // defined(ELPP_UNICODE)
Y
youny626 已提交
5193
#endif  // EASYLOGGINGPP_H