Skip to content
Snippets Groups Projects
easylogging++.h 278 KiB
Newer Older
  • Learn to ignore specific revisions
  • Radim Vavřík's avatar
    Radim Vavřík committed
    1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 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 1133 1134 1135 1136 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 1187 1188 1189 1190 1191 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 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 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 1272 1273 1274 1275 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 1307 1308 1309 1310 1311 1312 1313 1314 1315 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 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 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 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 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 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 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
    namespace internal {
    /// @brief Mutex wrapper used when multi-threading is disabled.
    class NoMutex : base::NoCopy {
    public:
        NoMutex(void) {}
        inline void lock(void) {}
        inline bool try_lock(void) { return true; }
        inline void unlock(void) {}
    };
    /// @brief Lock guard wrapper used when multi-threading is disabled.
    template <typename Mutex>
    class NoScopedLock : base::NoCopy {
    public:
        explicit NoScopedLock(Mutex&) {
        }
        virtual ~NoScopedLock(void) {
        }
    private:
        NoScopedLock(void);
    };
    }  // namespace internal
    static inline std::string getCurrentThreadId(void) {
        return std::string();
    }
    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:
        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; }
    protected:
        ThreadSafe(void) {}
        virtual ~ThreadSafe(void) {}
    private:
        base::threading::Mutex m_mutex;
    };
    }  // namespace threading
    namespace utils {
    class File : base::StaticClass {
    public:
        /// @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) {
            base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), 
                base::type::fstream_t::out | base::type::fstream_t::app);
    #if defined(_ELPP_UNICODE)
            std::locale elppUnicodeLocale("");
            fs->imbue(elppUnicodeLocale);
    #endif  // defined(_ELPP_UNICODE)
            if (fs->is_open()) {
                fs->flush();
            } else {
                base::utils::safeDelete(fs);
                ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true);
            }
            return fs;
        }
    
        /// @brief Gets size of file provided in stream
        static std::size_t getSizeOfFile(base::type::fstream_t* fs) {
            if (fs == nullptr) {
                return 0;
            }
            std::streampos currPos = fs->tellg();
            fs->seekg(0, fs->end);
            std::size_t size = static_cast<std::size_t>(fs->tellg());
            fs->seekg(currPos);
            return size;
        }
    
        /// @brief Determines whether or not provided path exist in current file system
        static inline bool pathExists(const char* path, bool considerFile = false) {
            if (path == nullptr) {
                return false;
            }
    #if _ELPP_OS_UNIX
            _ELPP_UNUSED(considerFile);
            struct stat st;
            return (stat(path, &st) == 0);
    #elif _ELPP_OS_WINDOWS
            DWORD fileType = GetFileAttributesA(path);
            if (fileType == INVALID_FILE_ATTRIBUTES) {
                return false;
            }
            return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true);
    #endif  // _ELPP_OS_UNIX
        }
    
        /// @brief Creates specified path on file system
        /// @param path Path to create.
        static bool createPath(const std::string& path) {
            if (path.empty()) {
                return false;
            }
            if (base::utils::File::pathExists(path.c_str())) {
                return true;
            }
            int status = -1;
    
            char* currPath = const_cast<char*>(path.c_str());
            std::string builtPath = std::string();
    #if _ELPP_OS_UNIX
            if (path[0] == '/') {
                builtPath = "/";
            }
            currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0);
    #elif _ELPP_OS_WINDOWS
            // Use secure functions API
            char* nextTok_;
            currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_);
            _ELPP_UNUSED(nextTok_);
    #endif  // _ELPP_OS_UNIX
            while (currPath != nullptr) {
                builtPath.append(currPath);
                builtPath.append(base::consts::kFilePathSeperator);
    #if _ELPP_OS_UNIX
                status = mkdir(builtPath.c_str(), _ELPP_LOG_PERMS);
                currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0);
    #elif _ELPP_OS_WINDOWS
                status = _mkdir(builtPath.c_str());
                currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_);
    #endif  // _ELPP_OS_UNIX
            }
            if (status == -1) {
                ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true);
                return false;
            }
            return true;
        }
        /// @brief Extracts path of filename with leading slash
        static std::string extractPathFromFilename(const std::string& fullPath,
                const char* seperator = base::consts::kFilePathSeperator) {
            if ((fullPath == "") || (fullPath.find(seperator) == std::string::npos)) {
                return fullPath;
            }
            std::size_t lastSlashAt = fullPath.find_last_of(seperator);
            if (lastSlashAt == 0) {
                return std::string(seperator);
            }
            return fullPath.substr(0, lastSlashAt + 1);
        }
        /// @brief builds stripped filename and puts it in buff
        static void buildStrippedFilename(const char* filename, char buff[], 
                std::size_t limit = base::consts::kSourceFilenameMaxLength) {
            std::size_t sizeOfFilename = strlen(filename);
            if (sizeOfFilename >= limit) {
                filename += (sizeOfFilename - limit);
                if (filename[0] != '.' && filename[1] != '.') {  // prepend if not already
                    filename += 3;  // 3 = '..'
                    STRCAT(buff, "..", limit);
                }
            }
            STRCAT(buff, filename, limit);
        }
        /// @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) {
            const char *filename = fullPath.c_str();
            std::size_t lastSlashAt = fullPath.find_last_of(seperator);
            filename += lastSlashAt ? lastSlashAt+1 : 0;
            std::size_t sizeOfFilename = strlen(filename);
            if (sizeOfFilename >= limit) {
                filename += (sizeOfFilename - limit);
                if (filename[0] != '.' && filename[1] != '.') {  // prepend if not already
                    filename += 3;  // 3 = '..'
                    STRCAT(buff, "..", limit);
                }
            }
            STRCAT(buff, filename, limit);
        }
    };
    /// @brief String utilities helper class used internally. You should not use it.
    class Str : base::StaticClass {
    public:
        /// @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) {
            while (*pattern) {
                switch (*pattern) {
                case '?':
                    if (!*str)
                        return false;
                    ++str;
                    ++pattern;
                    break;
                case '*':
                    if (wildCardMatch(str, pattern + 1))
                        return true;
                    if (*str && wildCardMatch(str + 1, pattern))
                        return true;
                    return false;
                    break;
                default:
                    if (*str++ != *pattern++)
                        return false;
                    break;
                }
            }
            return !*str && !*pattern;
        }
    
        /// @brief Trims string from start
        /// @param [in,out] str String to trim
        static inline std::string& ltrim(std::string& str) {  // NOLINT
            str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not1(std::ptr_fun<int, int>(&std::isspace))));
            return str;
        }
    
        /// @brief Trim string from end
        /// @param [in,out] str String to trim
        static inline std::string& rtrim(std::string& str) {  // NOLINT
            str.erase(std::find_if(str.rbegin(), str.rend(), std::not1(std::ptr_fun<int, int>(&std::isspace))).base(), str.end());
            return str;
        }
    
        /// @brief Trims string from left and right
        /// @param [in,out] str String to trim
        static inline std::string& trim(std::string& str) {  // NOLINT
            return ltrim(rtrim(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 inline bool startsWith(const std::string& str, const std::string& start) {
            return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0);
        }
    
        /// @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 inline bool endsWith(const std::string& str, const std::string& end) {
            return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0);
        }
    
        /// @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 inline std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith) {  // NOLINT
            std::replace(str.begin(), str.end(), replaceWhat, replaceWith);
            return str;
        }
    
        /// @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 inline std::string& replaceAll(std::string& str, const std::string& replaceWhat, // NOLINT
                const std::string& replaceWith) {
            if (replaceWhat == replaceWith)
                return str;
            std::size_t foundAt = std::string::npos;
            while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) {
                str.replace(foundAt, replaceWhat.length(), replaceWith);
            }
            return str;
        }
    
        static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, // NOLINT
                const base::type::string_t& replaceWith) {
            std::size_t foundAt = base::type::string_t::npos;
            while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) {
                if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) {
                    str.erase(foundAt > 0 ? foundAt - 1 : 0, 1);
                    ++foundAt;
                } else {
                    str.replace(foundAt, replaceWhat.length(), replaceWith);
                    return;
                }
            }
        }
    #if defined(_ELPP_UNICODE)
        static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, // NOLINT
                const std::string& replaceWith) {
            replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end()));
        }
    #endif  // defined(_ELPP_UNICODE)
        /// @brief Converts string to uppercase
        /// @param str String to convert
        /// @return Uppercase string
        static inline std::string& toUpper(std::string& str) {  // NOLINT
            std::transform(str.begin(), str.end(), str.begin(), ::toupper);
            return str;
        }
    
        /// @brief Compares cstring equality - uses strcmp
        static inline bool cStringEq(const char* s1, const char* s2) {
            if (s1 == nullptr && s2 == nullptr) return true;
            if (s1 == nullptr || s2 == nullptr) return false;
            return strcmp(s1, s2) == 0;
        }
    
        /// @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) {
            if (s1 == nullptr && s2 == nullptr) return true;
            if (s1 == nullptr || s2 == nullptr) return false;
            if (strlen(s1) != strlen(s2)) return false;
            while (*s1 != '\0' && *s2 != '\0') {
                if (::toupper(*s1) != ::toupper(*s2)) return false;
                ++s1;
                ++s2;
            }
            return true;
        }
    
        /// @brief Returns true if c exist in str
        static inline bool contains(const char* str, char c) {
            for (; *str; ++str) {
                if (*str == c)
                    return true;
            }
            return false;
        }
    
        static inline char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true) {
            char localBuff[10] = "";
            char* p = localBuff + sizeof(localBuff) - 2;
            if (n > 0) {
                for (; n > 0 && p > localBuff && len > 0; n /= 10, --len)
                    *--p = static_cast<char>(n % 10 + '0');
            } else {
                *--p = '0';
                --len;
            }
            if (zeroPadded)
                while (p > localBuff && len-- > 0) *--p = static_cast<char>('0');
            return addToBuff(p, buf, bufLim);
        }
    
        static inline char* addToBuff(const char* str, char* buf, const char* bufLim) {
            while ((buf < bufLim) && ((*buf = *str++) != '\0'))
                ++buf;
            return buf;
        }
    
        static inline char* clearBuff(char buff[], std::size_t lim) {
            STRCPY(buff, "", lim);
            _ELPP_UNUSED(lim);  // For *nix we dont have anything using lim in above STRCPY macro
            return buff;
        }
    
        /// @brief Converst wchar* to char*
        ///        NOTE: Need to free return value after use!
        static char* wcharPtrToCharPtr(const wchar_t* line) {
            std::size_t len_ = wcslen(line) + 1;
            char* buff_ = static_cast<char*>(malloc(len_ + 1));
    #      if _ELPP_OS_UNIX || (_ELPP_OS_WINDOWS && !_ELPP_CRT_DBG_WARNINGS)
            std::wcstombs(buff_, line, len_);
    #      elif _ELPP_OS_WINDOWS
            std::size_t convCount_ = 0;
            mbstate_t mbState_;
            ::memset(static_cast<void*>(&mbState_), 0, sizeof(mbState_));
            wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_);
    #      endif  // _ELPP_OS_UNIX || (_ELPP_OS_WINDOWS && !_ELPP_CRT_DBG_WARNINGS)
           return buff_;
        }
    };
    /// @brief Operating System helper static class used internally. You should not use it.
    class OS : base::StaticClass {
    public:
    #if _ELPP_OS_WINDOWS
        /// @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) {
            const DWORD bufferLen = 50;
            static char buffer[bufferLen];
            if (GetEnvironmentVariableA(varname, buffer, bufferLen)) {
                return buffer;
            }
            return nullptr;
        }
    #endif  // _ELPP_OS_WINDOWS
    #if _ELPP_OS_ANDROID
        /// @brief Reads android property value
        static inline std::string getProperty(const char* prop) {
            char propVal[PROP_VALUE_MAX + 1];
            int ret = __system_property_get(prop, propVal);
            return ret == 0 ? std::string() : std::string(propVal);
        }
    
        /// @brief Reads android device name
        static std::string getDeviceName(void) {
            std::stringstream ss;
            std::string manufacturer = getProperty("ro.product.manufacturer");
            std::string model = getProperty("ro.product.model");
            if (manufacturer.empty() || model.empty()) {
                return std::string();
            }
            ss << manufacturer << "-" << model;
            return ss.str();
        }
    #endif  // _ELPP_OS_ANDROID
    
        /// @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) {
    #if (_ELPP_OS_UNIX && !_ELPP_OS_ANDROID && !_ELPP_CYGWIN)
            if (command == nullptr) {
                return std::string();
            }
            FILE* proc = nullptr;
            if ((proc = popen(command, "r")) == nullptr) {
                ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true);
                return std::string();
            }
            char hBuff[4096];
            if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) {
                pclose(proc);
                if (hBuff[strlen(hBuff) - 1] == '\n') {
                    hBuff[strlen(hBuff) - 1] = '\0';
                }
                return std::string(hBuff);
            }
            return std::string();
    #else
            _ELPP_UNUSED(command);
            return std::string();
    #endif  // (_ELPP_OS_UNIX && !_ELPP_OS_ANDROID && !_ELPP_CYGWIN)
        }
    
        /// @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) {
    #if _ELPP_OS_UNIX
            const char* val = getenv(variableName);
    #elif _ELPP_OS_WINDOWS
            const char* val = getWindowsEnvironmentVariable(variableName);
    #endif  // _ELPP_OS_UNIX
            if ((val == nullptr) || ((strcmp(val, "") == 0))) {
    #if _ELPP_OS_UNIX && defined(_ELPP_FORCE_ENV_VAR_FROM_BASH)
               // Try harder on unix-based systems
                std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand);
                if (valBash.empty()) {
                    return std::string(defaultVal);
                } else {
                    return valBash;
                }
    #elif _ELPP_OS_WINDOWS || _ELPP_OS_UNIX
                _ELPP_UNUSED(alternativeBashCommand);
                return std::string(defaultVal);
    #endif  // _ELPP_OS_UNIX && defined(_ELPP_FORCE_ENV_VAR_FROM_BASH)
            }
            return std::string(val);
        }
       /// @brief Gets current username.
        static inline std::string currentUser(void) {
    #if _ELPP_OS_UNIX && !_ELPP_OS_ANDROID
            return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami");
    #elif _ELPP_OS_WINDOWS
            return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser);
    #elif _ELPP_OS_ANDROID
            _ELPP_UNUSED(base::consts::kUnknownUser);
            return std::string("android");
    #else
            return std::string();
    #endif  // _ELPP_OS_UNIX && !_ELPP_OS_ANDROID
        }
    
        /// @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 inline std::string currentHost(void) {
    #if _ELPP_OS_UNIX && !_ELPP_OS_ANDROID
            return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname");
    #elif _ELPP_OS_WINDOWS
            return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost);
    #elif _ELPP_OS_ANDROID
            _ELPP_UNUSED(base::consts::kUnknownHost);
            return getDeviceName();
    #else
            return std::string();
    #endif  // _ELPP_OS_UNIX && !_ELPP_OS_ANDROID
        }
        /// @brief Whether or not terminal supports colors
        static inline bool termSupportsColor(void) {
            std::string term = getEnvironmentVariable("TERM", "");
            return term == "xterm" || term == "xterm-color" || term == "xterm-256color" ||
                                  term == "screen" || term == "linux" || term == "cygwin";
        }
    };
    extern std::string s_currentUser;
    extern std::string s_currentHost;
    extern bool s_termSupportsColor;
    #define _ELPP_INITI_BASIC_DECLR \
        namespace el {\
            namespace base {\
                namespace utils {\
                    std::string s_currentUser = el::base::utils::OS::currentUser(); \
                    std::string s_currentHost = el::base::utils::OS::currentHost(); \
                    bool s_termSupportsColor = el::base::utils::OS::termSupportsColor(); \
                }\
            }\
       }
    /// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str
    class DateTime : base::StaticClass {
    public:
        /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current millisecond.
        ///
        /// @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) {
    #if _ELPP_OS_WINDOWS
            if (tv != nullptr) {
    #   if _ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
                const unsigned __int64 delta_ = 11644473600000000Ui64;
    #   else
                const unsigned __int64 delta_ = 11644473600000000ULL;
    #   endif  // _ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS)
                const double secOffSet = 0.000001;
                const unsigned long usecOffSet = 1000000;  // NOLINT
                FILETIME fileTime;
                GetSystemTimeAsFileTime(&fileTime);
                unsigned __int64 present = 0;
                present |= fileTime.dwHighDateTime;
                present = present << 32;
                present |= fileTime.dwLowDateTime;
                present /= 10;  // mic-sec
               // Subtract the difference
                present -= delta_;
                tv->tv_sec = static_cast<long>(present * secOffSet);  // NOLINT
                tv->tv_usec = static_cast<long>(present % usecOffSet);  // NOLINT
            }
    #else
            ::gettimeofday(tv, nullptr);
    #endif  // _ELPP_OS_WINDOWS
        }
    
        /// @brief Gets current date and time with milliseconds.
        /// @param format User provided date/time format
        /// @param msWidth A pointer to base::MillisecondsWidth from configuration (non-null)
        /// @returns string based date time in specified format.
        static inline std::string getDateTime(const char* format, const base::MillisecondsWidth* msWidth) {
            struct timeval currTime;
            gettimeofday(&currTime);
            struct ::tm timeInfo;
            buildTimeInfo(&currTime, &timeInfo);
            const int kBuffSize = 30;
            char buff_[kBuffSize] = "";
            parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast<std::size_t>(currTime.tv_usec / msWidth->m_offset), msWidth);
            return std::string(buff_);
        }
    
        /// @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) {  // NOLINT
            double result = static_cast<double>(time);
            base::type::EnumType start = static_cast<base::type::EnumType>(timestampUnit);
            const base::type::char_t* unit = base::consts::kTimeFormats[start].unit;
            for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) {
                if (result <= base::consts::kTimeFormats[i].value) {
                    break;
                }
                result /= base::consts::kTimeFormats[i].value;
                unit = base::consts::kTimeFormats[i + 1].unit;
            }
            base::type::stringstream_t ss;
            ss << result << " " << unit;
            return ss.str();
        }
    
        /// @brief Gets time difference in milli/micro second depending on timestampUnit
        static inline unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, base::TimestampUnit timestampUnit) {  // NOLINT
            if (timestampUnit == base::TimestampUnit::Microsecond) {
                return static_cast<unsigned long long>(static_cast<unsigned long long>(1000000 * endTime.tv_sec + endTime.tv_usec) -  // NOLINT
                        static_cast<unsigned long long>(1000000 * startTime.tv_sec + startTime.tv_usec));  // NOLINT
            } else {
                return static_cast<unsigned long long>((((endTime.tv_sec - startTime.tv_sec) * 1000000) + (endTime.tv_usec - startTime.tv_usec)) / 1000);  // NOLINT
            }
        }
    
    private:
        static inline struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) {
    #if _ELPP_OS_UNIX
            time_t rawTime = currTime->tv_sec;
            ::localtime_r(&rawTime, timeInfo);
            return timeInfo;
    #else
    #   if _ELPP_COMPILER_MSVC
            _ELPP_UNUSED(currTime);
            time_t t;
            _time64(&t);
            localtime_s(timeInfo, &t);
            return timeInfo;
    #   else
            // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method
            time_t rawTime = currTime->tv_sec;  // NOLINT
            struct tm* tmInf = localtime(&rawTime);  // NOLINT
            *timeInfo = *tmInf;
            return timeInfo;
    #   endif  // _ELPP_COMPILER_MSVC
    #endif  // _ELPP_OS_UNIX
        }
        static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
                std::size_t msec, const base::MillisecondsWidth* msWidth) {
            const char* bufLim = buf + bufSz;
            for (; *format; ++format) {
                if (*format == base::consts::kFormatSpecifierChar) {
                    switch (*++format) {
                    case base::consts::kFormatSpecifierChar:  // Escape
                        break;
                    case '\0':  // End
                        --format;
                        break;
                    case 'd':  // Day
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim);
                        continue;
                    case 'a':  // Day of week (short)
                        buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim);
                        continue;
                    case 'A':  // Day of week (long)
                        buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim);
                        continue;
                    case 'M':  // month
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim);
                        continue;
                    case 'b':  // month (short)
                        buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim);
                        continue;
                    case 'B':  // month (long)
                        buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim);
                        continue;
                    case 'y':  // year (two digits)
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim);
                        continue;
                    case 'Y':  // year (four digits)
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim);
                        continue;
                    case 'h':  // hour (12-hour)
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim);
                        continue;
                    case 'H':  // hour (24-hour)
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim);
                        continue;
                    case 'm':  // minute
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim);
                        continue;
                    case 's':  // second
                        buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim);
                        continue;
                    case 'z':  // milliseconds
                    case 'g':
                        buf = base::utils::Str::convertAndAddToBuff(msec, msWidth->m_width, buf, bufLim);
                        continue;
                    case 'F':  // AM/PM
                        buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim);
                        continue;
                    default:
                        continue;
                    }
                }
                if (buf == bufLim) break;
                *buf++ = *format;
            }
            return buf;
        }
    };
    /// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or _START_EASYLOGGINGPP(..)
    class CommandLineArgs {
    public:
        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
        inline void setArgs(int argc, char** argv) {
            m_params.clear();
            m_paramsWithValue.clear();
            if (argc == 0 || argv == nullptr) {
                return;
            }
            m_argc = argc;
            m_argv = argv;
            for (int i = 1; i < m_argc; ++i) {
                const char* v = (strstr(m_argv[i], "="));
                if (v != nullptr && strlen(v) > 0) {
                    std::string key = std::string(m_argv[i]);
                    key = key.substr(0, key.find_first_of('='));
                    if (hasParamWithValue(key.c_str())) {
                        ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value [" 
                            << getParamValue(key.c_str()) << "]");
                    } else {
                        m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1)));
                    }
                }
                if (v == nullptr) {
                    if (hasParam(m_argv[i])) {
                        ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists");
                    } else {
                        m_params.push_back(std::string(m_argv[i]));
                    }
                }
            }
        }
        /// @brief Returns true if arguments contain paramKey with a value (seperated by '=')
        inline bool hasParamWithValue(const char* paramKey) const {
            return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end();
        }
        /// @brief Returns value of arguments
        /// @see hasParamWithValue(const char*)
        inline const char* getParamValue(const char* paramKey) const {
            return m_paramsWithValue.find(std::string(paramKey))->second.c_str();
        }
        /// @brief Return true if arguments has a param (not having a value) i,e without '='
        inline bool hasParam(const char* paramKey) const {
            return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end();
        }
        /// @brief Returns true if no params available. This exclude argv[0]
        inline bool empty(void) const {
            return m_params.empty() && m_paramsWithValue.empty();
        }
        /// @brief Returns total number of arguments. This exclude argv[0]
        inline std::size_t size(void) const {
            return m_params.size() + m_paramsWithValue.size();
        }
        inline friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) {
            for (int i = 1; i < c.m_argc; ++i) {
                os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]");
                if (i < c.m_argc - 1) {
                    os << ELPP_LITERAL(" ");
                }
            }
            return os;
        }
    
    private:
        int m_argc;
        char** m_argv;
        std::map<std::string, std::string> m_paramsWithValue;
        std::vector<std::string> m_params;
    };
    /// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type.
    ///
    /// @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.
    template <typename T_Ptr, typename Container>
    class AbstractRegistry : public base::threading::ThreadSafe {
    public:
        typedef typename Container::iterator iterator;
        typedef typename Container::const_iterator const_iterator;
    
        /// @brief Default constructor
        AbstractRegistry(void) {}
    
        /// @brief Move constructor that is useful for base classes
        AbstractRegistry(AbstractRegistry&& sr) {
            if (this == &sr) {
                return;
            }
            unregisterAll();
            m_list = std::move(sr.m_list);
        }
    
        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;
                }
            }
            return true;
        }
    
        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;
        }
    
        /// @brief Assignment move operator
        AbstractRegistry& operator=(AbstractRegistry&& sr) {
            if (this == &sr) {
                return *this;
            }
            unregisterAll();
            m_list = std::move(sr.m_list);
            return *this;
        }
    
        virtual ~AbstractRegistry(void) {
        }
    
        /// @return Iterator pointer from start of repository
        virtual inline iterator begin(void) ELPP_FINAL {
            return m_list.begin();
        }
    
        /// @return Iterator pointer from end of repository
        virtual inline iterator end(void) ELPP_FINAL {
            return m_list.end();
        }
    
    
        /// @return Constant iterator pointer from start of repository
        virtual inline const_iterator cbegin(void) const ELPP_FINAL {
            return m_list.cbegin();
        }
    
        /// @return End of repository
        virtual inline const_iterator cend(void) const ELPP_FINAL {
            return m_list.cend();
        }
    
        /// @return Whether or not repository is empty
        virtual inline bool empty(void) const ELPP_FINAL {
            return m_list.empty();
        }
    
        /// @return Size of repository
        virtual inline std::size_t size(void) const ELPP_FINAL {
            return m_list.size();
        }
    
        /// @brief Returns underlying container by reference
        virtual inline Container& list(void) ELPP_FINAL {
            return m_list;
        }
    
        /// @brief Returns underlying container by constant reference.
        virtual inline const Container& list(void) const ELPP_FINAL {
            return m_list;
        }
    
        /// @brief Unregisters all the pointers from current repository.
        virtual void unregisterAll(void) = 0;
    
    protected:
        virtual void deepCopy(const AbstractRegistry<T_Ptr, Container>&) = 0;
        void reinitDeepCopy(const AbstractRegistry<T_Ptr, Container>& sr) {
            unregisterAll();
            deepCopy(sr);
        }
    
    private:
        Container m_list;
    };
    
    /// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version)
    ///
    /// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these functions)
    ///         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::map<T_Key, T_Ptr*>> {
    public:
        typedef typename Registry<T_Ptr, T_Key>::iterator iterator;
        typedef typename Registry<T_Ptr, T_Key>::const_iterator const_iterator;
    
        Registry(void) {}
    
        /// @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);
        }
    
        /// @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;
        }
    
        virtual ~Registry(void) {
            unregisterAll();
        }
    
    protected:
        virtual inline 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 inline 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
        inline void unregister(const T_Key& uniqKey) {
            T_Ptr* existing = get(uniqKey);
            if (existing != nullptr) {
                base::utils::safeDelete(existing);
                this->list().erase(uniqKey);
            }
        }
    
        /// @brief Gets pointer from repository. If none found, nullptr is returned.
        inline T_Ptr* get(const T_Key& uniqKey) {
            iterator it = this->list().find(uniqKey);
            return it == this->list().end()
                    ? nullptr
                    : it->second;
        }
    
    private:
        virtual inline void deepCopy(const AbstractRegistry<T_Ptr, std::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));
            }
        }
    };
    
    /// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version)
    ///
    /// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry<T_Ptr, Container>. Any implementation of this class
    /// should be made thread-safe explicitly
    template <typename T_Ptr, typename Pred>
    class RegistryWithPred : public AbstractRegistry<T_Ptr, std::vector<T_Ptr*>> {
    public:
        typedef typename RegistryWithPred<T_Ptr, Pred>::iterator iterator;
        typedef typename RegistryWithPred<T_Ptr, Pred>::const_iterator const_iterator;
    
        RegistryWithPred(void) {
        }
    
        virtual ~RegistryWithPred(void) {
            unregisterAll();
        }
    
        /// @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);
        }
    
        /// @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;
        }
    
        friend inline 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;
        }
    
    protected:
        virtual inline void unregisterAll(void) ELPP_FINAL {
            if (!this->empty()) {