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
    3001 3002 3003 3004 3005 3006 3007 3008 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 3050 3051 3052 3053 3054 3055 3056 3057 3058 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 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 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 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 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 3319 3320 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 3383 3384 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 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 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 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 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 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 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 3958 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 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
                    setValue(conf->level(), static_cast<std::size_t>(getULong(conf->value())), &m_logFlushThresholdMap);
                }
            }
            // As mentioned early, we will now set filename configuration in separate loop to deal with non-existent files
            for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
                Configuration* conf = *it;
                if (conf->configurationType() == ConfigurationType::Filename) {
                    insertFile(conf->level(), conf->value());
                }
            }
            for (std::vector<Configuration*>::iterator conf = withFileSizeLimit.begin();
                    conf != withFileSizeLimit.end(); ++conf) {
                    // This is not unsafe as mutex is locked in currect scope
                    unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback);
            }
        }
    
        unsigned long getULong(std::string confVal) {  // NOLINT
            bool valid = true;
            base::utils::Str::trim(confVal);
            valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(),
                    [](char c) { return !base::utils::Str::isDigit(c); }) == confVal.end();
            if (!valid) {
                valid = false;
                ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]");
                return 0;
            }
            return atol(confVal.c_str());
        }
    
        std::string resolveFilename(const std::string& filename) {
            std::string resultingFilename = filename;
            std::size_t dateIndex = std::string::npos;
            std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename);
            if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) {
                while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
                    dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1);
                }
                if (dateIndex != std::string::npos) {
                    const char* ptr = resultingFilename.c_str() + dateIndex;
                    // Goto end of specifier
                    ptr += dateTimeFormatSpecifierStr.size();
                    std::string fmt;
                    if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) {
                        // User has provided format for date/time
                        ++ptr;
                        int count = 1;  // Start by 1 in order to remove starting brace
                        std::stringstream ss;
                        for (; *ptr; ++ptr, ++count) {
                            if (*ptr == '}') {
                                ++count;  // In order to remove ending brace
                                break;
                            }
                            ss << *ptr;
                        }
                        resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count);
                        fmt = ss.str();
                    } else {
                        fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename);
                    }
                    base::MillisecondsWidth msWidth(3);
                    std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &msWidth);
                    base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename
                    base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now);
                }
            }
            return resultingFilename;
        }
    
        void insertFile(Level level, const std::string& fullFilename) {
            std::string resolvedFilename = resolveFilename(fullFilename);
            if (resolvedFilename.empty()) {
                std::cerr << "Could not load empty file for logging, please re-check your configurations for level ["
                        << LevelHelper::convertToString(level) << "]";
            }
            std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator);
            if (filePath.size() < resolvedFilename.size()) {
                base::utils::File::createPath(filePath);
            }
            auto create = [&](Level level) {
                base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename);
                base::type::fstream_t* fs = nullptr;
                if (filestreamIter == m_logStreamsReference->end()) {
                    // We need a completely new stream, nothing to share with
                    fs = base::utils::File::newFileStream(resolvedFilename);
                    m_filenameMap.insert(std::make_pair(level, resolvedFilename));
                    m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs)));
                    m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level))));
                } else {
                    // Woops! we have an existing one, share it!
                    m_filenameMap.insert(std::make_pair(level, filestreamIter->first));
                    m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second)));
                    fs = filestreamIter->second.get();
                }
                if (fs == nullptr) {
                    // We display bad file error from newFileStream()
                    ELPP_INTERNAL_ERROR("Setting [TO_FILE] of [" 
                        << LevelHelper::convertToString(level) << "] to FALSE", false);
                    setValue(level, false, &m_toFileMap);
                }
            };  // NOLINT
            // If we dont have file conf for any level, create it for Level::Global first
            // otherwise create for specified level
            create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level);
        }
    
        bool unsafeValidateFileRolling(Level level, const PreRollOutCallback& PreRollOutCallback) {
            base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get();
            if (fs == nullptr) {
                return true;
            }
            std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize");
            std::size_t currFileSize = base::utils::File::getSizeOfFile(fs);
            if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) {
                std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename");
                ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level ["
                        << LevelHelper::convertToString(level) << "]");
                fs->close();
                PreRollOutCallback(fname.c_str(), currFileSize);
                fs->open(fname, std::fstream::out | std::fstream::trunc);
                return true;
            }
            return false;
        }
    
        bool validateFileRolling(Level level, const PreRollOutCallback& PreRollOutCallback) {
            base::threading::ScopedLock scopedLock(lock());
            return unsafeValidateFileRolling(level, PreRollOutCallback);
        }
    };
    /// @brief Class that keeps record of current line hit for occasional logging
    class HitCounter {
    public:
        HitCounter(void) :
            m_filename(""),
            m_lineNumber(0),
            m_hitCounts(0) {
        }
    
        HitCounter(const char* filename, unsigned long int lineNumber) :  // NOLINT
            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) {
            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, unsigned long int lineNumber) {  // NOLINT
            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 unsigned long int lineNumber(void) const {  // NOLINT
            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, unsigned long int lineNumber)  // NOLINT
                : 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;
            unsigned long int m_lineNumber;  // NOLINT
        };
    
    private:
        const char* m_filename;
        unsigned long int m_lineNumber;  // NOLINT
        std::size_t m_hitCounts;
    };
    /// @brief Repository for hit counters used across the application
    class RegisteredHitCounters : public base::utils::RegistryWithPred<base::HitCounter, base::HitCounter::Predicate> {
    public:
        /// @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, unsigned long int lineNumber, std::size_t n) {  // NOLINT
            base::threading::ScopedLock scopedLock(lock());
            base::HitCounter* counter = get(filename, lineNumber);
            if (counter == nullptr) {
                registerNew(counter = new base::HitCounter(filename, lineNumber));
            }
            counter->validateHitCounts(n);
            bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0);
            return result;
        }
    
        /// @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, unsigned long int lineNumber, std::size_t n) {  // NOLINT
            base::threading::ScopedLock scopedLock(lock());
            base::HitCounter* counter = get(filename, lineNumber);
            if (counter == nullptr) {
                registerNew(counter = new base::HitCounter(filename, lineNumber));
            }
            // Do not use validateHitCounts here since we do not want to reset counter here
            // Note the >= instead of > because we are incrementing
            // after this check
            if (counter->hitCounts() >= n)
                return true;
            counter->increment();
            return false;
        }
    
        /// @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, unsigned long int lineNumber, std::size_t n) {  // NOLINT
            base::threading::ScopedLock scopedLock(lock());
            base::HitCounter* counter = get(filename, lineNumber);
            if (counter == nullptr) {
                registerNew(counter = new base::HitCounter(filename, lineNumber));
            }
            counter->increment();
            // Do not use validateHitCounts here since we do not want to reset counter here
            if (counter->hitCounts() <= n)
                return true;
            return false;
        }
    
        /// @brief Gets hit counter registered at specified position
        inline const base::HitCounter* getCounter(const char* filename, unsigned long int lineNumber) {  // NOLINT
            base::threading::ScopedLock scopedLock(lock());
            return get(filename, lineNumber);
        }
    };
    /// @brief Action to be taken for dispatching
    enum class DispatchAction : base::type::EnumType {
        None = 1, NormalLog = 2, SysLog = 4
    };
    }  // namespace base
    template <typename T>
    class Callback : protected base::threading::ThreadSafe {
    public:
        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;
        }
    protected:
        virtual void handle(const T* handlePtr) = 0;
    private:
        bool m_enabled;
    };
    class LogDispatchData {
    public:
        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; }
    private:
        LogMessage* m_logMessage;
        base::DispatchAction m_dispatchAction;
        friend class base::LogDispatcher;
    
        inline void setLogMessage(LogMessage* logMessage) { m_logMessage = logMessage; }
        inline void setDispatchAction(base::DispatchAction dispatchAction) { m_dispatchAction = dispatchAction; }
    };
    class LogDispatchCallback : public Callback<LogDispatchData> {
    private:
        friend class base::LogDispatcher;
    };
    class PerformanceTrackingCallback : public Callback<PerformanceTrackingData> {
    private:
        friend class base::PerformanceTracker;
    };
    class LogBuilder : base::NoCopy {
    public:
        virtual ~LogBuilder(void) { ELPP_INTERNAL_INFO(3, "Destroying log builder...")}
        virtual base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const = 0;
    private:
        friend class el::base::DefaultLogDispatchCallback;
    
        void convertToColoredOutput(base::type::string_t* logLine, Level level) {
            if (!base::utils::s_termSupportsColor) return;
            const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m");
            if (level == Level::Error || level == Level::Fatal)
                *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor;
            else if (level == Level::Warning)
                *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor;
        }
    };
    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:
        Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) :
                m_id(id),
                m_typedConfigurations(nullptr),
                m_parentApplicationName(std::string()),
                m_isConfigured(false),
                m_logStreamsReference(logStreamsReference) {
            initUnflushedCount();
        }
    
        Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMap* logStreamsReference) :
                m_id(id),
                m_typedConfigurations(nullptr),
                m_parentApplicationName(std::string()),
                m_isConfigured(false),
                m_logStreamsReference(logStreamsReference) {
            initUnflushedCount();
            configure(configurations);
        }
    
        Logger(const Logger& logger) {
            base::utils::safeDelete(m_typedConfigurations);
            m_id = logger.m_id;
            m_typedConfigurations = logger.m_typedConfigurations;
            m_parentApplicationName = logger.m_parentApplicationName;
            m_isConfigured = logger.m_isConfigured;
            m_configurations = logger.m_configurations;
            m_unflushedCount = logger.m_unflushedCount;
            m_logStreamsReference = logger.m_logStreamsReference;
        }
    
        Logger& operator=(const Logger& logger) {
            base::utils::safeDelete(m_typedConfigurations);
            m_id = logger.m_id;
            m_typedConfigurations = logger.m_typedConfigurations;
            m_parentApplicationName = logger.m_parentApplicationName;
            m_isConfigured = logger.m_isConfigured;
            m_configurations = logger.m_configurations;
            m_unflushedCount = logger.m_unflushedCount;
            m_logStreamsReference = logger.m_logStreamsReference;
            return *this;
        }
    
        virtual ~Logger(void) {
            base::utils::safeDelete(m_typedConfigurations);
        }
    
        virtual inline void log(el::base::type::ostream_t& os) const {
            os << m_id.c_str();
        }
    
        /// @brief Configures the logger using specified configurations.
        void configure(const Configurations& configurations) {
            m_isConfigured = false;  // we set it to false in case if we fail
            initUnflushedCount();
            if (m_typedConfigurations != nullptr) {
                Configurations* c = const_cast<Configurations*>(m_typedConfigurations->configurations());
                if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) {
                    // This check is definitely needed for cases like _ELPP_NO_DEFAULT_LOG_FILE
                    flush();
                }
            }
            base::threading::ScopedLock scopedLock(lock());
            if (m_configurations != configurations) {
                m_configurations.setFromBase(const_cast<Configurations*>(&configurations));
            }
            base::utils::safeDelete(m_typedConfigurations);
            m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference);
            resolveLoggerFormatSpec();
            m_isConfigured = true;
        }
    
        /// @brief Reconfigures logger using existing configurations
        inline void reconfigure(void) {
            ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]");
            configure(m_configurations);
        }
    
        inline const std::string& id(void) const {
            return m_id;
        }
    
        inline const std::string& parentApplicationName(void) const {
            return m_parentApplicationName;
        }
    
        inline void setParentApplicationName(const std::string& parentApplicationName) {
            m_parentApplicationName = parentApplicationName;
        }
    
        inline Configurations* configurations(void) {
            return &m_configurations;
        }
    
        inline base::TypedConfigurations* typedConfigurations(void) {
            return m_typedConfigurations;
        }
    
        static inline bool isValidId(const std::string& id) {
            for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) {
                if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) {
                    return false;
                }
            }
            return true;
        }
        /// @brief Flushes logger to sync all log files for all levels
        inline void flush(void) {
            ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels");
            base::threading::ScopedLock scopedLock(lock());
            base::type::EnumType lIndex = LevelHelper::kMinValid;
            LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
                flush(LevelHelper::castFromInt(lIndex), nullptr);
                return false;
            });
        }
    
        inline LogBuilder* logBuilder(void) const {
            return m_logBuilder.get();
        }
    
        inline void setLogBuilder(const LogBuilderPtr& logBuilder) {
            m_logBuilder = logBuilder;
        }
    
        inline bool enabled(Level level) const {
            return m_typedConfigurations->enabled(level);
        }
        
    #if _ELPP_VARIADIC_TEMPLATES_SUPPORTED
    #   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
    private:
        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::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);
    
    #if _ELPP_VARIADIC_TEMPLATES_SUPPORTED
        template <typename T, typename... Args>
        void log_(Level, int, const char*, const T&, const Args&...);
    
        template <typename T>
        inline void log_(Level, int, const T&);
    
        template <typename T, typename... Args>
        void log(Level, const char*, const T&, const Args&...);
    
        template <typename T>
        inline void log(Level, const T&);
    #endif // _ELPP_VARIADIC_TEMPLATES_SUPPORTED
    
        void initUnflushedCount(void) {
            m_unflushedCount.clear();
            base::type::EnumType lIndex = LevelHelper::kMinValid;
            LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
                m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0));
                return false;
            });
        }
    
        inline base::type::stringstream_t& stream(void) {
            return m_stream;
        }
    
        inline void flush(Level level, base::type::fstream_t* fs) {
            if (fs == nullptr && m_typedConfigurations->toFile(level)) {
                fs = m_typedConfigurations->fileStream(level);
            }
            if (fs != nullptr) {
                fs->flush();
                m_unflushedCount.find(level)->second = 0;
            }
        }
    
        inline bool isFlushNeeded(Level level) {
            return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level);
        }
    
        void resolveLoggerFormatSpec(void) const {
            base::type::EnumType lIndex = LevelHelper::kMinValid;
            LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
                base::LogFormat* logFormat = 
                    const_cast<base::LogFormat*>(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex)));
                base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id);
                return false;
            });
        }
    };
    namespace base {
    /// @brief Loggers repository
    class RegisteredLoggers : public base::utils::Registry<Logger, std::string> {
    public:
        explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) :
            m_defaultLogBuilder(defaultLogBuilder) {
            m_defaultConfigurations.setToDefault();
        }
    
        virtual ~RegisteredLoggers(void) {
            flushAll();
        }
    
        inline void setDefaultConfigurations(const Configurations& configurations) {
            base::threading::ScopedLock scopedLock(lock());
            m_defaultConfigurations.setFromBase(const_cast<Configurations*>(&configurations));
        }
    
        inline Configurations* defaultConfigurations(void) {
            return &m_defaultConfigurations;
        }
    
        Logger* get(const std::string& id, bool forceCreation = true) {
            base::threading::ScopedLock scopedLock(lock());
            Logger* logger_ = base::utils::Registry<Logger, std::string>::get(id);
            if (logger_ == nullptr && forceCreation) {
                bool validId = Logger::isValidId(id);
                if (!validId) {
                    ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger.");
                    return nullptr;
                }
                logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference);
                logger_->m_logBuilder = m_defaultLogBuilder;
                registerNew(id, logger_);
            }
            return logger_;
        }
    
        bool remove(const std::string& id) {
            if (id == "default") {
                return false;
            }
            Logger* logger = base::utils::Registry<Logger, std::string>::get(id);
            if (logger != nullptr) {
                unregister(logger);
            }
            return true;
        }
    
        inline bool has(const std::string& id) {
            return get(id, false) != nullptr;
        }
    
        inline void unregister(Logger*& logger) {  // NOLINT
            base::threading::ScopedLock scopedLock(lock());
            base::utils::Registry<Logger, std::string>::unregister(logger->id());
        }
    
        inline base::LogStreamsReferenceMap* logStreamsReference(void) {
            return &m_logStreamsReference;
        }
    
        inline void flushAll(void) {
            ELPP_INTERNAL_INFO(1, "Flushing all log files");
            base::threading::ScopedLock scopedLock(lock());
            for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin();
                    it != m_logStreamsReference.end(); ++it) {
                if (it->second.get() == nullptr) continue;
                it->second->flush();
            }
        }
    
    private:
        LogBuilderPtr m_defaultLogBuilder;
        Configurations m_defaultConfigurations;
        base::LogStreamsReferenceMap m_logStreamsReference;
        friend class el::base::Storage;
    };
    /// @brief Represents registries for verbose logging
    class VRegistry : base::NoCopy, public base::threading::ThreadSafe {
    public:
        explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) {
        }
    
        /// @brief Sets verbose level. Accepted range is 0-9
        inline void setLevel(base::type::VerboseLevel level) {
            base::threading::ScopedLock scopedLock(lock());
            if (level < 0)
                m_level = 0;
            else if (level > 9)
                m_level = base::consts::kMaxVerboseLevel;
            else
                m_level = level;
        }
    
        inline base::type::VerboseLevel level(void) const {
            return m_level;
        }
    
        inline void clearModules(void) {
            base::threading::ScopedLock scopedLock(lock());
            m_modules.clear();
        }
    
        void setModules(const char* modules) {
            base::threading::ScopedLock scopedLock(lock());
            auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) {
                if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) {
                    std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev)));
                    ss.str(std::string(""));
                    ss << chr;
                }
                if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) {
                    std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx)));
                    ss.str(std::string(""));
                    ss << chr;
                }
                ss << sfx;
            };  // NOLINT
            auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) {
                if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) {
                    addSuffix(ss, ".h", nullptr);
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".c", ".h");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".cpp", ".c");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".cc", ".cpp");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".cxx", ".cc");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".-inl.h", ".cxx");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".hxx", ".-inl.h");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".hpp", ".hxx");
                    m_modules.insert(std::make_pair(ss.str(), level));
                    addSuffix(ss, ".hh", ".hpp");
                }
                m_modules.insert(std::make_pair(ss.str(), level));
            };  // NOLINT
            bool isMod = true;
            bool isLevel = false;
            std::stringstream ss;
            int level = -1;
            for (; *modules; ++modules) {
                switch (*modules) {
                case '=':
                    isLevel = true;
                    isMod = false;
                    break;
                case ',':
                    isLevel = false;
                    isMod = true;
                    if (!ss.str().empty() && level != -1) {
                        insert(ss, level);
                        ss.str(std::string(""));
                        level = -1;
                    }
                    break;
                default:
                    if (isMod) {
                        ss << *modules;
                    } else if (isLevel) {
                        if (isdigit(*modules)) {
                            level = static_cast<base::type::VerboseLevel>(*modules) - 48;
                        }
                    }
                    break;
                }
            }
            if (!ss.str().empty() && level != -1) {
                insert(ss, level);
            }
        }
    
        bool allowed(base::type::VerboseLevel vlevel, const char* file) {
            base::threading::ScopedLock scopedLock(lock());
            if (m_modules.empty() || file == nullptr) {
                return vlevel <= m_level;
            } else {
                std::map<std::string, base::type::VerboseLevel>::iterator it = m_modules.begin();
                for (; it != m_modules.end(); ++it) {
                    if (base::utils::Str::wildCardMatch(file, it->first.c_str())) {
                        return vlevel <= it->second;
                    }
                }
                if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) {
                    return true;
                }
                return false;
            }
        }
    
        inline const std::map<std::string, base::type::VerboseLevel>& modules(void) const {
            return m_modules;
        }
    
        void setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) {
            if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") ||
                commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) {
                setLevel(base::consts::kMaxVerboseLevel);
            } else if (commandLineArgs->hasParamWithValue("--v")) {
                setLevel(atoi(commandLineArgs->getParamValue("--v")));
            } else if (commandLineArgs->hasParamWithValue("--V")) {
                setLevel(atoi(commandLineArgs->getParamValue("--V")));
            } else if ((commandLineArgs->hasParamWithValue("-vmodule"))
                    && (!base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags))) {
                setModules(commandLineArgs->getParamValue("-vmodule"));
            } else if (commandLineArgs->hasParamWithValue("-VMODULE") 
                    && (!base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags))) {
                setModules(commandLineArgs->getParamValue("-VMODULE"));
            }
        }
    
    private:
        base::type::VerboseLevel m_level;
        base::type::EnumType* m_pFlags;
        std::map<std::string, base::type::VerboseLevel> m_modules;
    };
    }  // namespace base
    class LogMessage {
    public:
        LogMessage(Level level, const std::string& file, unsigned long int line, const std::string& func,  // NOLINT
                              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(std::move(logger->stream().str())) {
        }
        inline Level level(void) const { return m_level; }
        inline const std::string& file(void) const { return m_file; }
        inline unsigned long int line(void) const { return m_line; } // NOLINT
        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; }
    private:
        Level m_level;
        std::string m_file;
        unsigned long int m_line;  // NOLINT
        std::string m_func;
        base::type::VerboseLevel m_verboseLevel;
        Logger* m_logger;
        base::type::string_t m_message;
    };
    namespace base {
    /// @brief Easylogging++ management storage
    class Storage : base::NoCopy, public base::threading::ThreadSafe {
    public:
        explicit Storage(const LogBuilderPtr& defaultLogBuilder) :
            m_registeredHitCounters(new base::RegisteredHitCounters()),
            m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)),
            m_flags(0x0),
            m_vRegistry(new base::VRegistry(0, &m_flags)),
            m_preRollOutCallback(base::defaultPreRollOutCallback) {
            // Register default logger
            m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId));
            // Register performance logger and reconfigure format
            Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId));
            performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg"));
            performanceLogger->reconfigure();
    #if defined(_ELPP_SYSLOG)
            // Register syslog logger and reconfigure format
            Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId));
            sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg"));
            sysLogLogger->reconfigure();
    #else
            _ELPP_UNUSED(base::consts::kSysLogLoggerId);
    #endif  //  defined(_ELPP_SYSLOG)
            addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified);
            installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback"));
            installPerformanceTrackingCallback<base::DefaultPerformanceTrackingCallback>(std::string("DefaultPerformanceTrackingCallback"));
            ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized");
        }
    
        virtual ~Storage(void) {
            base::utils::safeDelete(m_registeredHitCounters);
            base::utils::safeDelete(m_registeredLoggers);
            base::utils::safeDelete(m_vRegistry);
        }
    
        inline bool validateEveryNCounter(const char* filename, unsigned long int lineNumber, std::size_t occasion) {  // NOLINT
            return hitCounters()->validateEveryN(filename, lineNumber, occasion);
        }
    
        inline bool validateAfterNCounter(const char* filename, unsigned long int lineNumber, std::size_t n) { // NOLINT
            return hitCounters()->validateAfterN(filename, lineNumber, n);
        }
    
        inline bool validateNTimesCounter(const char* filename, unsigned long int lineNumber, std::size_t n) { // NOLINT
            return hitCounters()->validateNTimes(filename, lineNumber, n);
        }
    
        inline base::RegisteredHitCounters* hitCounters(void) const {
            return m_registeredHitCounters;
        }
    
        inline base::RegisteredLoggers* registeredLoggers(void) const {
            return m_registeredLoggers;
        }
    
        inline base::VRegistry* vRegistry(void) const {
            return m_vRegistry;
        }
    
        inline const base::utils::CommandLineArgs* commandLineArgs(void) const {
            return &m_commandLineArgs;
        }
    
        inline void addFlag(LoggingFlag flag) {
            base::utils::addFlag(flag, &m_flags);
        }
    
        inline void removeFlag(LoggingFlag flag) {
            base::utils::removeFlag(flag, &m_flags);
        }
    
        inline bool hasFlag(LoggingFlag flag) const {
            return base::utils::hasFlag(flag, m_flags);
        }
    
        inline base::type::EnumType flags(void) const {
            return m_flags;
        }
    
        inline void setFlags(base::type::EnumType flags) {
            m_flags = flags;
        }
    
        inline void setPreRollOutCallback(const PreRollOutCallback& callback) {
            m_preRollOutCallback = callback;
        }
    
        inline void unsetPreRollOutCallback(void) {
            m_preRollOutCallback = base::defaultPreRollOutCallback;
        }
    
        inline PreRollOutCallback& preRollOutCallback(void) {
            return m_preRollOutCallback;
        }
    
        inline bool hasCustomFormatSpecifier(const char* formatSpecifier) {
            base::threading::ScopedLock scopedLock(lock());
            return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(),
                    formatSpecifier) != m_customFormatSpecifiers.end();
        }
    
        inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
            if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) {
                return;
            }
            base::threading::ScopedLock scopedLock(lock());
            m_customFormatSpecifiers.push_back(customFormatSpecifier);
        }
    
        inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) {
            base::threading::ScopedLock scopedLock(lock());
            std::vector<CustomFormatSpecifier>::iterator it = std::find(m_customFormatSpecifiers.begin(),
                    m_customFormatSpecifiers.end(), formatSpecifier);
            if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) {
                m_customFormatSpecifiers.erase(it);
                return true;
            }
            return false;
        }
    
        const std::vector<CustomFormatSpecifier>* customFormatSpecifiers(void) const {
            return &m_customFormatSpecifiers;
        }
    
        inline void setLoggingLevel(Level level) {
            m_loggingLevel = level;
        }
    
        template <typename T>
        inline bool installLogDispatchCallback(const std::string& id) {
            return installCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
        }
    
        template <typename T>
        inline void uninstallLogDispatchCallback(const std::string& id) {
            uninstallCallback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
        }
        template <typename T>
        inline T* logDispatchCallback(const std::string& id) {
            return callback<T, base::type::LogDispatchCallbackPtr>(id, &m_logDispatchCallbacks);
        }
    
        template <typename T>
        inline bool installPerformanceTrackingCallback(const std::string& id) {
            return installCallback<T, base::type::PerformanceTrackingCallbackPtr>(id, &m_performanceTrackingCallbacks);
        }
    
        template <typename T>
        inline void uninstallPerformanceTrackingCallback(const std::string& id) {
             uninstallCallback<T, base::type::PerformanceTrackingCallbackPtr>(id, &m_performanceTrackingCallbacks);
        }
    
        template <typename T>
        inline T* performanceTrackingCallback(const std::string& id) {
            return callback<T, base::type::PerformanceTrackingCallbackPtr>(id, &m_performanceTrackingCallbacks);
        }
    private:
        base::RegisteredHitCounters* m_registeredHitCounters;
        base::RegisteredLoggers* m_registeredLoggers;
        base::type::EnumType m_flags;
        base::VRegistry* m_vRegistry;
        base::utils::CommandLineArgs m_commandLineArgs;
        PreRollOutCallback m_preRollOutCallback;
        std::map<std::string, base::type::LogDispatchCallbackPtr> m_logDispatchCallbacks;
        std::map<std::string, base::type::PerformanceTrackingCallbackPtr> m_performanceTrackingCallbacks;
        std::vector<CustomFormatSpecifier> m_customFormatSpecifiers;
        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) {
            m_commandLineArgs.setArgs(argc, argv);
            m_vRegistry->setFromArgs(commandLineArgs());
            // default log file
    #if !defined(_ELPP_DISABLE_LOG_FILE_FROM_ARG)
            if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) {
                Configurations c;
                c.setGlobally(ConfigurationType::Filename, std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam)));
                registeredLoggers()->setDefaultConfigurations(c);
                for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin();
                        it != registeredLoggers()->end(); ++it) {
                    it->second->configure(c);
                }
            }
    #endif  // !defined(_ELPP_DISABLE_LOG_FILE_FROM_ARG)
    #if defined(_ELPP_LOGGING_FLAGS_FROM_ARG)
            if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) {
                m_flags = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam));
            }
    #endif  // defined(_ELPP_LOGGING_FLAGS_FROM_ARG)
        }
    
        inline void setApplicationArguments(int argc, const char** argv) {
            setApplicationArguments(argc, const_cast<char**>(argv));
        }