diff --git a/3rdparty/easyloggingpp/.gitignore b/3rdparty/easyloggingpp/.gitignore
deleted file mode 100644
index aad43a5..0000000
--- a/3rdparty/easyloggingpp/.gitignore
+++ /dev/null
@@ -1,7 +0,0 @@
-build-*
-*.pro.user
-.DS_Store
-release.info
-bin/*
-logs/*
-experiments/*
diff --git a/3rdparty/easyloggingpp/CMakeLists.txt b/3rdparty/easyloggingpp/CMakeLists.txt
deleted file mode 100644
index e69de29..0000000
diff --git a/3rdparty/easyloggingpp/LICENSE b/3rdparty/easyloggingpp/LICENSE
deleted file mode 100644
index 302737d..0000000
--- a/3rdparty/easyloggingpp/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2012-2018 Zuhd Web Services
-Copyright (c) 2012-2018 @abumusamq
-
-https://github.com/zuhd-org/
-https://zuhd.org
-https://muflihun.com
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/3rdparty/easyloggingpp/README.md b/3rdparty/easyloggingpp/README.md
deleted file mode 100644
index f6577d9..0000000
--- a/3rdparty/easyloggingpp/README.md
+++ /dev/null
@@ -1,1539 +0,0 @@
-
- ﷽
-
-
-![banner]
-
-> **Manual For v9.96.7**
-
-[![Build Status (Master)](https://img.shields.io/travis/zuhd-org/easyloggingpp/master.svg)](#build-matrix)
-[![Build Status (Develop)](https://img.shields.io/travis/zuhd-org/easyloggingpp/develop.svg)](#build-matrix)
-[![Build status](https://ci.appveyor.com/api/projects/status/sfcgrehu8ypkrun3?svg=true)](https://ci.appveyor.com/project/abumusamq/easyloggingpp-node)
-
-[![Node Binding Version](https://img.shields.io/github/release/zuhd-org/easyloggingpp.svg)](https://github.com/zuhd-org/easyloggingpp-node/releases/latest)
-[![Version](https://img.shields.io/npm/v/easyloggingpp.svg)](https://www.npmjs.com/package/easyloggingpp)
-
-[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/zuhd-org/easyloggingpp/blob/master/LICENCE)
-[![Downloads](https://img.shields.io/github/downloads/zuhd-org/easyloggingpp/total.svg)](https://github.com/zuhd-org/easyloggingpp/releases/latest)
-
-[![Donate](https://muflihun.github.io/donate.png?v2)](https://www.paypal.me/zuhd/25)
-
-
-### Quick Links
-
- [![download] Latest Release](https://github.com/zuhd-org/easyloggingpp/releases/latest)
-
- [![notes] Changelog](/CHANGELOG.md)
-
- [![samples] Samples](/samples)
-
----
-
-### Table of Contents
-
-Overview
- Why yet another library
- Features at a glance
-Getting Started
- Download
- Quick Start
- Install (Optional)
- Setting Application Arguments
-Configuration
- Level
- Configure
- Using Configuration File
- Using el::Configurations Class
- Using In line Configurations
- Default Configurations
- Global Configurations
- Logging Format Specifiers
- Date/Time Format Specifiers
- Custom Format Specifiers
- Logging Flags
- Application Arguments
- Configuration Macros
- Reading Configurations
-Logging
- Basic
- Conditional Logging
- Occasional Logging
- printf Like Logging
- Network Logging
- Verbose Logging
- Basic
- Conditional and Occasional
- Verbose Level
- Check If Verbose Logging Is On
- VModule
- Registering New Loggers
- Unregister Loggers
- Populating Existing Logger IDs
- Sharing Logging Repository
-Extra Features
- Performance Tracking
- Conditional Performance Tracking
- Make Use of Performance Tracking Data
- Log File Rotating
- Crash Handling
- Installing Custom Crash Handlers
- Stacktrace
- Multi-threading
- CHECK Macros
- Logging perror()
- Using Syslog
- STL Logging
- Supported Templates
- Qt Logging
- Boost Logging
- wxWidgets Logging
- Extending Library
- Logging Your Own Class
- Logging Third-party Class
- Manually Flushing and Rolling Log Files
- Log Dispatch Callback
- Logger Registration Callback
- Asynchronous Logging
- Helper Classes
-Contribution
- Submitting Patches
- Reporting a Bug
-Compatibility
- Build Matrix
-Licence
-Disclaimer
-
-
-# Overview
-Easylogging++ is single header efficient logging library for C++ applications. It is extremely powerful, highly extendable and configurable to user's requirements. It provides ability to [write your own _sinks_](/samples/send-to-network) (via featured referred as `LogDispatchCallback`). This library is currently used by [hundreds of open-source projects on github](https://github.com/search?q=%22easylogging%2B%2B.h%22&type=Code&utf8=%E2%9C%93) and other open-source source control management sites.
-
-This manual is for Easylogging++ v9.96.7. For other versions please refer to corresponding [release](https://github.com/zuhd-org/easyloggingpp/releases) on github.
-
-> You may also be interested in [Residue](https://github.com/muflihun/residue/) logging server.
-
- [![top] Goto Top](#table-of-contents)
-
-### Why yet another library
-If you are working on a small utility or large project in C++, this library can be handy. Its based on single header and only requires to link to single source file. (Originally it was header-only and was changed to use source file in [issue #445](https://github.com/zuhd-org/easyloggingpp/issues/445). You can still use header-only in [v9.89](https://github.com/zuhd-org/easyloggingpp/releases/tag/9.89)).
-
-This library has been designed with various thoughts in mind (i.e, portability, performance, usability, features and easy to setup).
-
-Why yet another library? Well, answer is pretty straight forward, use it as you wrote it so you can fix issues (if any) as you go or raise them on github. In addition to that, I personally have not seen any logging library based on single-header with such a design where you can configure on the go, extend it to your needs and get fast performance. I have seen other single-header logging libraries for C++ but either they use external libraries, e.g, boost or Qt to support certain features like threading, regular expression or date etc. This library has everything built-in to prevent usage of external libraries, not that I don't like those libraries, in fact I love them, but because not all projects use these libraries, I couldn't take risk of depending on them.
-
- [![top] Goto Top](#table-of-contents)
-
-### Features at a glance
-Easylogging++ is feature-rich containing many features that both typical and advanced developer will require while writing a software;
- * [Highly configurable](#configuration)
- * [Extendable](#extending-library)
- * Extremely fast
- * [Thread](#multi-threading) and type safe
- * [Cross-platform](#compatibility)
- * [Custom log patterns](#logging-format-specifiers)
- * [Conditional and occasional logging](#conditional-logging)
- * [Performance tracking](#performance-tracking)
- * [Verbose logging](#verbose-logging)
- * [Crash handling](#crash-handling)
- * [Helper CHECK macros](#check-macros)
- * [STL logging](#stl-logging)
- * [Send to Syslog](#syslog)
- * [Third-party library logging (Qt, boost, wxWidgets etc)](#logging-third-party-class)
- * [Extensible (Logging your own class or third-party class)](#logging-your-own-class)
- * [And many more...](#extra-features)
-
- [![top] Goto Top](#table-of-contents)
-
-# Getting Started
-### Download
-Download latest version from [Latest Release](https://github.com/zuhd-org/easyloggingpp/releases/latest)
-
-For other releases, please visit [releases page](https://github.com/zuhd-org/easyloggingpp/releases). If you application does not support C++11, please consider using [v8.91](https://github.com/zuhd-org/easyloggingpp/tree/v8.91). This is stable version for C++98 and C++03, just lack some features.
-
- [![top] Goto Top](#table-of-contents)
-
-### Quick Start
-In order to get started with Easylogging++, you can follow three easy steps:
-* Download latest version
-* Include into your project (`easylogging++.h` and `easylogging++.cc`)
-* Initialize using single macro... and off you go!
-
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-
-int main(int argc, char* argv[]) {
- LOG(INFO) << "My first info log using default logger";
- return 0;
-}
-```
-
-Now compile using
-
-```
-g++ main.cc easylogging++.cc -o prog -std=c++11
-```
-
-That simple! Please note that `INITIALIZE_EASYLOGGINGPP` should be used once and once-only otherwise you will end up getting compilation errors. This is definiting several `extern` variables. This means it can be defined only once per application. Best place to put this initialization statement is in file where `int main(int, char**)` function is defined, right after last include statement.
-
-### Install (Optional)
-If you want to install this header system-wide, you can do so via:
-```
-mkdir build
-cd build
-cmake -Dtest=ON ../
-make
-make test
-make install
-```
-
-Following options are supported by Easylogging++ cmake and you can turn these options on using `-D=ON`
-
- * `lib_utc_datetime` - Defines `ELPP_UTC_DATETIME`
- * `build_static_lib` - Builds static library for Easylogging++
-
-With that said, you will still need `easylogging++.cc` file in order to compile. For header only, please check [v9.89](https://github.com/zuhd-org/easyloggingpp/releases/tag/9.89) and lower.
-
- [![top] Goto Top](#table-of-contents)
-
-### Setting Application Arguments
-It is always recommended to pass application arguments to Easylogging++. Some features of Easylogging++ require you to set application arguments, e.g, verbose logging to set verbose level or vmodules (explained later). In order to do that you can use helper macro or helper class;
-
-```c++
-int main(int argc, char* argv[]) {
- START_EASYLOGGINGPP(argc, argv);
- ...
-}
-```
- [![top] Goto Top](#table-of-contents)
-
-# Configuration
-### Level
-In order to start configuring your logging library, you must understand severity levels. Easylogging++ deliberately does not use hierarchical logging in order to fully control what's enabled and what's not. That being said, there is still option to use hierarchical logging using `LoggingFlag::HierarchicalLogging`. Easylogging++ has following levels (ordered for hierarchical levels)
-
-| Level | Description |
-|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Global | Generic level that represents all levels. Useful when setting global configuration for all levels. |
-| Trace | Information that can be useful to back-trace certain events - mostly useful than debug logs. |
-| Debug | Informational events most useful for developers to debug application. Only applicable if NDEBUG is not defined (for non-VC++) or _DEBUG is defined (for VC++).|
-| Fatal | Very severe error event that will presumably lead the application to abort. |
-| Error | Error information but will continue application to keep running. |
-| Warning | Information representing errors in application but application will keep running. |
-| Info | Mainly useful to represent current progress of application. |
-| Verbose | Information that can be highly useful and vary with verbose logging level. Verbose logging is not applicable to hierarchical logging. |
-| Unknown | Only applicable to hierarchical logging and is used to turn off logging completely. |
-
- [![top] Goto Top](#table-of-contents)
-
-### Configure
-Easylogging++ is easy to configure. There are three possible ways to do so,
-* Using configuration file
-* Using el::Configurations class
-* Using inline configuration
-
-#### Using Configuration File
-Configuration can be done by file that is loaded at runtime by `Configurations` class. This file has following format;
-```
-* LEVEL:
- CONFIGURATION NAME = "VALUE" ## Comment
- ANOTHER CONFIG NAME = "VALUE"
-```
-
-Level name starts with a star (*) and ends with colon (:). It is highly recommended to start your configuration file with `Global` level so that any configuration not specified in the file will automatically use configuration from `Global`. For example, if you set `Filename` in `Global` and you want all the levels to use same filename, do not set it explicitly for each level, library will use configuration value from `Global` automatically.
-Following table contains configurations supported by configuration file.
-
-| Configuration Name | Type | Description |
-|-----------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `Enabled` | bool | Determines whether or not corresponding level for logger is enabled. You may disable all logs by using `el::Level::Global` |
-| `To_File` | bool | Whether or not to write corresponding log to log file |
-| `To_Standard_Output` | bool | Whether or not to write logs to standard output e.g, terminal or command prompt |
-| `Format` | char* | Determines format/pattern of logging for corresponding level and logger. |
-| `Filename` | char* | Determines log file (full path) to write logs to for corresponding level and logger |
-| `Subsecond_Precision` | uint | Specifies subsecond precision (previously called 'milliseconds width'). Width can be within range (1-6) |
-| `Performance_Tracking` | bool | Determines whether or not performance tracking is enabled. This does not depend on logger or level. Performance tracking always uses 'performance' logger unless specified|
-| `Max_Log_File_Size` | size_t | If log file size of corresponding level is >= specified size, log file will be truncated. |
-| `Log_Flush_Threshold` | size_t | Specifies number of log entries to hold until we flush pending log data |
-
-
-Please do not use double-quotes anywhere in comment, you might end up in unexpected behaviour.
-
-Sample Configuration File
-```
-* GLOBAL:
- FORMAT = "%datetime %msg"
- FILENAME = "/tmp/logs/my.log"
- ENABLED = true
- TO_FILE = true
- TO_STANDARD_OUTPUT = true
- SUBSECOND_PRECISION = 6
- PERFORMANCE_TRACKING = true
- MAX_LOG_FILE_SIZE = 2097152 ## 2MB - Comment starts with two hashes (##)
- LOG_FLUSH_THRESHOLD = 100 ## Flush after every 100 logs
-* DEBUG:
- FORMAT = "%datetime{%d/%M} %func %msg"
-```
-
-##### Explanation
-Configuration file contents in above sample is straightforward. We start with `GLOBAL` level in order to override all the levels. Any explicitly defined subsequent level will override configuration from `GLOBAL`. For example, all the levels except for `DEBUG` have the same format, i.e, datetime and log message. For `DEBUG` level, we have only date (with day and month), source function and log message. The rest of configurations for `DEBUG` are used from `GLOBAL`. Also, notice `{%d/%M}` in `DEBUG` format above, if you do not specify date format, default format is used. Default values of date/time is `%d/%M/%Y %h:%m:%s,%g` For more information on these format specifiers, please refer to [Date/Time Format Specifier](#datetime-format-specifiers) section below
-
-##### Usage
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-
-int main(int argc, const char** argv) {
- // Load configuration from file
- el::Configurations conf("/path/to/my-conf.conf");
- // Reconfigure single logger
- el::Loggers::reconfigureLogger("default", conf);
- // Actually reconfigure all loggers instead
- el::Loggers::reconfigureAllLoggers(conf);
- // Now all the loggers will use configuration from file
-}
-```
-
- > Your configuration file can be converted to `el::Configurations` object (using constructor) that can be used where ever it is needed (like in above example).
-
- [![top] Goto Top](#table-of-contents)
-
-#### Using el::Configurations Class
-You can set configurations or reset configurations;
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-
-int main(int argc, const char** argv) {
- el::Configurations defaultConf;
- defaultConf.setToDefault();
- // Values are always std::string
- defaultConf.set(el::Level::Info,
- el::ConfigurationType::Format, "%datetime %level %msg");
- // default logger uses default configurations
- el::Loggers::reconfigureLogger("default", defaultConf);
- LOG(INFO) << "Log using default file";
- // To set GLOBAL configurations you may use
- defaultConf.setGlobally(
- el::ConfigurationType::Format, "%date %msg");
- el::Loggers::reconfigureLogger("default", defaultConf);
- return 0;
-}
-```
-
- > Configuration just needs to be set once. If you are happy with default configuration, you may use it as well.
-
- [![top] Goto Top](#table-of-contents)
-
-#### Using In line Configurations
-Inline configuration means you can set configurations in `std::string` but make sure you add all the new line characters etc. This is not recommended because it's always messy.
-```c++
-el::Configurations c;
-c.setToDefault();
-c.parseFromText("*GLOBAL:\n FORMAT = %level %msg");
-```
-
- > Above code only sets Configurations object, you still need to re-configure logger/s using this configurations.
-
- [![top] Goto Top](#table-of-contents)
-
-### Default Configurations
-If you wish to have a configuration for existing and future loggers, you can use `el::Loggers::setDefaultConfigurations(el::Configurations& configurations, bool configureExistingLoggers = false)`. This is useful when you are working on fairly large scale, or using a third-party library that is already using Easylogging++. Any newly created logger will use default configurations. If you wish to configure existing loggers as well, you can set second argument to `true` (it defaults to `false`).
-
- [![top] Goto Top](#table-of-contents)
-
-### Global Configurations
-`Level::Global` is nothing to do with global configurations, it is concept where you can register configurations for all/or some loggers and even register new loggers using configuration file. Syntax of configuration file is:
-```
--- LOGGER ID ## Case sensitive
- ## Everything else is same as configuration file
-
-
--- ANOTHER LOGGER ID
- ## Configuration for this logger
-```
-
-Logger ID starts with two dashes. Once you have written your global configuration file you can configure your all loggers (and register new ones) using single function;
-```c++
-int main(void) {
- // Registers new and configures it or
- // configures existing logger - everything in global.conf
- el::Loggers::configureFromGlobal("global.conf");
- // .. Your prog
- return 0;
-}
-```
-Please note, it is not possible to register new logger using global configuration without defining its configuration. You must define at least single configuration. Other ways to register loggers are discussed in [Logging](#logging) section below.
-
- [![top] Goto Top](#table-of-contents)
-
-### Logging Format Specifiers
-You can customize format of logging using following specifiers:
-
-| Specifier | Replaced By |
-|-----------------|---------------------------------------------------------------------------------------------|
-| `%logger` | Logger ID |
-| `%thread` | Thread ID - Uses std::thread if available, otherwise GetCurrentThreadId() on windows |
-| `%thread_name` | Use `Helpers::setThreadName` to set name of current thread (where you run `setThreadName` from). See [Thread Names sample](/samples/STL/thread-names.cpp)|
-| `%level` | Severity level (Info, Debug, Error, Warning, Fatal, Verbose, Trace) |
-| `%levshort` | Severity level (Short version i.e, I for Info and respectively D, E, W, F, V, T) |
-| `%vlevel` | Verbosity level (Applicable to verbose logging) |
-| `%datetime` | Date and/or time - Pattern is customizable - see Date/Time Format Specifiers below |
-| `%user` | User currently running application |
-| `%host` | Computer name application is running on |
-| `%file`* | File name of source file (Full path) - This feature is subject to availability of `__FILE__` macro of compiler |
-| `%fbase`* | File name of source file (Only base name) |
-| `%line`* | Source line number - This feature is subject to availability of `__LINE__` macro of compile |
-| `%func`* | Logging function |
-| `%loc`* | Source filename and line number of logging (separated by colon) |
-| `%msg` | Actual log message |
-| `%` | Escape character (e.g, %%level will write %level) |
-
-* Subject to compiler's availability of certain macros, e.g, `__LINE__`, `__FILE__` etc
-
- [![top] Goto Top](#table-of-contents)
-
-### Date/Time Format Specifiers
-You can customize date/time format using following specifiers
-
-| Specifier | Replaced By |
-|-----------------|------------------------------------------------------------------------------------------------------------------|
-| `%d` | Day of month (zero-padded) |
-| `%a` | Day of the week - short (Mon, Tue, Wed, Thu, Fri, Sat, Sun) |
-| `%A` | Day of the week - long (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) |
-| `%M` | Month (zero-padded) |
-| `%b` | Month - short (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec) |
-| `%B` | Month - Long (January, February, March, April, May, June, July, August, September, October, November, December) |
-| `%y` | Year - Two digit (13, 14 etc) |
-| `%Y` | Year - Four digit (2013, 2014 etc) |
-| `%h` | Hour (12-hour format) |
-| `%H` | Hour (24-hour format) |
-| `%m` | Minute (zero-padded) |
-| `%s` | Second (zero-padded) |
-| `%g` | Subsecond part (precision is configured by ConfigurationType::SubsecondPrecision) |
-| `%F` | AM/PM designation |
-| `%` | Escape character |
-
-Please note, date/time is limited to `30` characters at most.
-
- [![top] Goto Top](#table-of-contents)
-
-### Custom Format Specifiers
-
-You can also specify your own format specifiers. In order to do that you can use `el::Helpers::installCustomFormatSpecifier`. A perfect example is `%ip_addr` for TCP server application;
-
-```C++
-const char* getIp(void) {
- return "192.168.1.1";
-}
-
-int main(void) {
- el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%ip_addr", getIp));
- el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, "%datetime %level %ip_addr : %msg");
- LOG(INFO) << "This is request from client";
- return 0;
-}
-```
-
- [![top] Goto Top](#table-of-contents)
-
-### Logging Flags
-Form some parts of logging you can set logging flags; here are flags supported:
-
-| Flag | Description |
-|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| `NewLineForContainer (1)` | Makes sure we have new line for each container log entry |
-| `AllowVerboseIfModuleNotSpecified (2)` | Makes sure if -vmodule is used and does not specifies a module, then verbose logging is allowed via that module. Say param was -vmodule=main*=3 and a verbose log is being written from a file called something.cpp then if this flag is enabled, log will be written otherwise it will be disallowed. Note: having this defeats purpose of -vmodule |
-| `LogDetailedCrashReason (4)` | When handling crashes by default, detailed crash reason will be logged as well (Disabled by default) ([issue #90](https://github.com/zuhd-org/easyloggingpp/issues/90)) |
-| `DisableApplicationAbortOnFatalLog (8)` | Allows to disable application abortion when logged using FATAL level. Note that this does not apply to default crash handlers as application should be aborted after crash signal is handled. (Not added by default) ([issue #119](https://github.com/zuhd-org/easyloggingpp/issues/119)) |
-| `ImmediateFlush (16)` | Flushes log with every log-entry (performance sensative) - Disabled by default |
-| `StrictLogFileSizeCheck (32)` | Makes sure log file size is checked with every log |
-| `ColoredTerminalOutput (64)` | Terminal output will be colorful if supported by terminal. |
-| `MultiLoggerSupport (128)` | Enables support for using multiple loggers to log single message. (E.g, `CLOG(INFO, "default", "network") << This will be logged using default and network loggers;`) |
-| `DisablePerformanceTrackingCheckpointComparison (256)` | Disables checkpoint comparison |
-| `DisableVModules (512)` | Disables usage of vmodules
-| `DisableVModulesExtensions (1024)` | Disables vmodules extension. This means if you have a vmodule -vmodule=main*=4 it will cover everything starting with main, where as if you do not have this defined you will be covered for any file starting with main and ending with one of the following extensions; .h .c .cpp .cc .cxx .-inl-.h .hxx .hpp. Please note following vmodule is not correct -vmodule=main.=4 with this macro not defined because this will check for main..c, notice double dots. If you want this to be valid, have a look at logging flag above: AllowVerboseIfModuleNotSpecified '?' and '' wildcards are supported |
-| `HierarchicalLogging (2048)` | Enables hierarchical logging. This is not applicable to verbose logging.|
-| `CreateLoggerAutomatically (4096)` | Creates logger automatically when not available. |
-| `AutoSpacing (8192)` | Automatically adds spaces. E.g, `LOG(INFO) << "DODGE" << "THIS!";` will output "DODGE THIS!"|
-| `FixedTimeFormat (16384)` | Applicable to performace tracking only - this prevents formatting time. E.g, `1001 ms` will be logged as is, instead of formatting it as `1.01 sec`|
-| `IgnoreSigInt (32768)` | When application crashes ignore Interruption signal |
-
-You can set/unset these flags by using static `el::Loggers::addFlag` and `el::Loggers::removeFlag`. You can check to see if certain flag is available by using `el::Loggers::hasFlag`, all these functions take strongly-typed enum `el::LoggingFlag`
-
- > You can set these flags by using `--logging-flags` command line arg. You need to enable this functionality by defining macro `ELPP_LOGGING_FLAGS_FROM_ARG` (You will need to make sure to use `START_EASYLOGGINGPP(argc, argv)` to configure arguments).
-
- > You can also set default (initial) flags using `ELPP_DEFAULT_LOGGING_FLAGS` and set numerical value for initial flags
-
- [![top] Goto Top](#table-of-contents)
-
-### Application Arguments
-Following table will explain all command line arguments that you may use to define certain behaviour; You will need to initialize application arguments by using `START_EASYLOGGINGPP(argc, argv)` in your `main(int, char**)` function.
-
-| Argument | Description |
-|----------------------------|-----------------------------------------------------------------------------------------|
-| `-v` | Activates maximum verbosity |
-| `--v=2` | Activates verbosity upto verbose level 2 (valid range: 0-9) |
-| `--verbose` | Activates maximum verbosity |
-| `-vmodule=MODULE_NAME` | Activates verbosity for files starting with main to level 1, the rest of the files depend on logging flag `AllowVerboseIfModuleNotSpecified` Please see Logging Flags section above. Two modules can be separated by comma. Please note vmodules are last in order of precedence of checking arguments for verbose logging, e.g, if we have -v in application arguments before vmodules, vmodules will be ignored. |
-| `--logging-flags=3` | Sets logging flag. In example `i.e, 3`, it sets logging flag to `NewLineForContainer` and `AllowVerboseIfModuleNotSpecified`. See logging flags section above for further details and values. See macros section to disable this function. |
-| `--default-log-file=FILE` |Sets default log file for existing and future loggers. You may want to consider defining `ELPP_NO_DEFAULT_LOG_FILE` to prevent creation of default empty log file during pre-processing. See macros section to disable this function. |
-
- [![top] Goto Top](#table-of-contents)
-
-### Configuration Macros
-Some of logging options can be set by macros, this is a thoughtful decision, for example if we have `ELPP_THREAD_SAFE` defined, all the thread-safe functionalities are enabled otherwise disabled (making sure over-head of thread-safety goes with it). To make it easy to remember and prevent possible conflicts, all the macros start with `ELPP_`
-
-**NOTE:** All the macros can be defined in one of the following ways:
-
- 1. Define macros using `-D` option of compiler, for example in case of `g++` you will do `g++ source.cpp ... -DELPP_SYSLOG -DELPP_THREAD_SAFE ...` (**recommended way**)
-
- 2. Define macros inside `"easylogging++.h"` ([defining macros in other files won't work](https://github.com/zuhd-org/easyloggingpp/issues/590#issuecomment-346753951))
-
-| Macro Name | Description |
-|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
-| `ELPP_DEBUG_ASSERT_FAILURE` | Aborts application on first assertion failure. This assertion is due to invalid input e.g, invalid configuration file etc. |
-| `ELPP_UNICODE` | Enables Unicode support when logging. Requires `START_EASYLOGGINGPP` |
-| `ELPP_THREAD_SAFE` | Enables thread-safety - make sure -lpthread linking for linux. |
-| `ELPP_FORCE_USE_STD_THREAD` | Forces to use C++ standard library for threading (Only useful when using `ELPP_THREAD_SAFE` |
-| `ELPP_FEATURE_CRASH_LOG` | Applicable to GCC only. Enables stacktrace on application crash |
-| `ELPP_DISABLE_DEFAULT_CRASH_HANDLING` | Disables default crash handling. You can use el::Helpers::setCrashHandler to use your own handler. |
-| `ELPP_DISABLE_LOGS` | Disables all logs - (preprocessing) |
-| `ELPP_DISABLE_DEBUG_LOGS` | Disables debug logs - (preprocessing) |
-| `ELPP_DISABLE_INFO_LOGS` | Disables info logs - (preprocessing) |
-| `ELPP_DISABLE_WARNING_LOGS` | Disables warning logs - (preprocessing) |
-| `ELPP_DISABLE_ERROR_LOGS` | Disables error logs - (preprocessing) |
-| `ELPP_DISABLE_FATAL_LOGS` | Disables fatal logs - (preprocessing) |
-| `ELPP_DISABLE_VERBOSE_LOGS` | Disables verbose logs - (preprocessing) |
-| `ELPP_DISABLE_TRACE_LOGS` | Disables trace logs - (preprocessing) |
-| `ELPP_FORCE_ENV_VAR_FROM_BASH` | If environment variable could not be found, force using alternative bash command to find value, e.g, `whoami` for username. (DO NOT USE THIS MACRO WITH `LD_PRELOAD` FOR LIBRARIES THAT ARE ALREADY USING Easylogging++ OR YOU WILL END UP IN STACK OVERFLOW FOR PROCESSES (`popen`) (see [issue #87](https://github.com/zuhd-org/easyloggingpp/issues/87) for details)) |
-| `ELPP_DEFAULT_LOG_FILE` | Full filename where you want initial files to be created. You need to embed value of this macro with quotes, e.g, `-DELPP_DEFAULT_LOG_FILE='"logs/el.gtest.log"'` Note the double quotes inside single quotes, double quotes are the values for `const char*` and single quotes specifies value of macro |
-| `ELPP_NO_LOG_TO_FILE` | Disable logging to file initially|
-| `ELPP_NO_DEFAULT_LOG_FILE` | If you dont want to initialize library with default log file, define this macro. This will log to null device for unix and windows. In other platforms you may get error and you will need to use `ELPP_DEFAULT_LOG_FILE`. (PR for other platform's null devices are most welcomed) |
-| `ELPP_FRESH_LOG_FILE` | Never appends log file whenever log file is created (Use with care as it may cause some unexpected result for some users) |
-| `ELPP_DEBUG_ERRORS` | If you wish to find out internal errors raised by Easylogging++ that can be because of configuration or something else, you can enable them by defining this macro. You will get your errors on standard output i.e, terminal or command prompt. |
-| `ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS` | Forcefully disables custom format specifiers |
-| `ELPP_DISABLE_LOGGING_FLAGS_FROM_ARG` | Forcefully disables ability to set logging flags using command-line arguments |
-| `ELPP_DISABLE_LOG_FILE_FROM_ARG` | Forcefully disables ability to set default log file from command-line arguments |
-| `ELPP_WINSOCK2` | On windows system force to use `winsock2.h` instead of `winsock.h` when `WIN32_LEAN_AND_MEAN` is defined |
-| `ELPP_CUSTOM_COUT` (advanced) | Resolves to a value e.g, `#define ELPP_CUSTOM_COUT qDebug()` or `#define ELPP_CUSTOM_COUT std::cerr`. This will use the value for standard output (instead of using `std::cout`|
-| `ELPP_CUSTOM_COUT_LINE` (advanced) | Used with `ELPP_CUSTOM_COUT` to define how to write a log line with custom cout. e.g, `#define ELPP_CUSTOM_COUT_LINE(msg) QString::fromStdString(msg).trimmed()` |
-| `ELPP_NO_CHECK_MACROS` | Do not define the *CHECK* macros |
-| `ELPP_NO_DEBUG_MACROS` | Do not define the *DEBUG* macros |
-| `ELPP_UTC_DATETIME` | Uses UTC time instead of local time (essentially uses `gmtime` instead of `localtime` and family functions)
-| `ELPP_NO_GLOBAL_LOCK` | Do not lock the whole storage on dispatch. This should be used with care. See [issue #580](https://github.com/zuhd-org/easyloggingpp/issues/580)|
-
- [![top] Goto Top](#table-of-contents)
-
-### Reading Configurations
-If you wish to read configurations of certain logger, you can do so by using `typedConfigurations()` function in Logger class.
-```c++
-el::Logger* l = el::Loggers::getLogger("default");
-bool enabled = l->typedConfigurations()->enabled(el::Level::Info);
-// Or to read log format/pattern
-std::string format =
- l->typedConfigurations()->logFormat(el::Level::Info).format();
-```
-
- [![top] Goto Top](#table-of-contents)
-
-# Logging
-Logging in easylogging++ is done using collection of macros. This is to make it easier for user and to prevent them knowing about unnecessary greater details of how things are done.
-
-### Basic
-You are provided with two basic macros that you can use in order to write logs:
-* `LOG(LEVEL)`
-* `CLOG(LEVEL, logger ID)`
-
-`LOG` uses 'default' logger while in CLOG (Custom LOG) you specify the logger ID. For LEVELs please refer to Configurations - Levels section above. Different loggers might have different configurations depending on your need, you may as well write custom macro to access custom logger. You also have different macros for verbose logging that is explained in section below.
-Here is very simple example of using these macros after you have initialized easylogging++.
-```c++
-LOG(INFO) << "This is info log";
-CLOG(ERROR, "performance") << "This is info log using performance logger";
-```
-
-There is another way to use same macro i.e, `LOG` (and associated macros). This is that you define macro `ELPP_DEFAULT_LOGGER` and `ELPP_DEFAULT_PERFORMANCE_LOGGER` with logger ID that is already registered, and now when you use `LOG` macro, it automatically will use specified logger instead of `default` logger. Please note that this should be defined in source file instead of header file. This is so that when we include header we dont accidently use invalid logger.
-
-A quick example is here
-```c++
-#ifndef ELPP_DEFAULT_LOGGER
-# define ELPP_DEFAULT_LOGGER "update_manager"
-#endif
-#ifndef ELPP_DEFAULT_PERFORMANCE_LOGGER
-# define ELPP_DEFAULT_PERFORMANCE_LOGGER ELPP_DEFAULT_LOGGER
-#endif
-#include "easylogging++.h"
-UpdateManager::UpdateManager {
- _TRACE; // Logs using LOG(TRACE) provided logger is already registered - i.e, update_manager
- LOG(INFO) << "This will log using update_manager logger as well";
-}
-```
-
-```c++
-#include "easylogging++.h"
-UpdateManager::UpdateManager {
- _TRACE; // Logs using LOG(TRACE) using default logger because no `ELPP_DEFAULT_LOGGER` is defined unless you have it in makefile
-}
-```
-
- > You can also write logs by using `Logger` class directly. This feature is available on compilers that support variadic templates. You can explore more by looking at `samples/STL/logger-log-functions.cpp`.
-
- [![top] Goto Top](#table-of-contents)
-
-### Conditional Logging
-Easylogging++ provides certain aspects of logging, one these aspects is conditional logging, i.e, log will be written only if certain condition fulfils. This comes very handy in some situations.
-Helper macros end with _IF;
-* `LOG_IF(condition, LEVEL)`
-* `CLOG_IF(condition, LEVEL, logger ID)`
-
-
-#### Some examples:
-```c++
-LOG_IF(condition, INFO) << "Logged if condition is true";
-
-LOG_IF(false, WARNING) << "Never logged";
-CLOG_IF(true, INFO, "performance") << "Always logged (performance logger)"
-```
-
-Same macros are available for verbose logging with `V` in the beginning, i.e, `VLOG_IF` and `CVLOG_IF`. see verbose logging section below for further information. You may have as complicated conditions as you want depending on your need.
-
- [![top] Goto Top](#table-of-contents)
-
-### Occasional Logging
-Occasional logging is another useful aspect of logging with Easylogging++. This means a log will be written if it's hit certain times or part of certain times, e.g, every 10th hit or 100th hit or 2nd hit.
-Helper macros end with `_EVERY_N`;
-* `LOG_EVERY_N(n, LEVEL)`
-* `CLOG_EVERY_N(n, LEVEL, logger ID)`
-
-#### Other Hit Counts Based Logging
-There are some other ways of logging as well based on hit counts. These useful macros are
-* `LOG_AFTER_N(n, LEVEL)`; Only logs when we have reached hit counts of `n`
-* `LOG_N_TIMES(n, LEVEL)`; Logs n times
-
-#### Some examples:
-```c++
-for (int i = 1; i <= 10; ++i) {
- LOG_EVERY_N(2, INFO) << "Logged every second iter";
-}
-// 5 logs written; 2, 4, 6, 7, 10
-
-for (int i = 1; i <= 10; ++i) {
- LOG_AFTER_N(2, INFO) << "Log after 2 hits; " << i;
-}
-// 8 logs written; 3, 4, 5, 6, 7, 8, 9, 10
-
-for (int i = 1; i <= 100; ++i) {
- LOG_N_TIMES(3, INFO) << "Log only 3 times; " << i;
-}
-// 3 logs writter; 1, 2, 3
-```
-
- > Same versions of macros are available for `DEBUG` only mode, these macros start with `D` (for debug) followed by the same name. e.g, `DLOG` to log only in debug mode (i.e, when `_DEBUG` is defined or `NDEBUG` is undefined)
-
- [![top] Goto Top](#table-of-contents)
-
-### `printf` Like Logging
-For compilers that support C++11's variadic templates, ability to log like "printf" is available. This is done by using `Logger` class. This feature is thread and type safe (as we do not use any macros like `LOG(INFO)` etc)
-
-This is done in two steps:
- 1. Pulling registered logger using `el::Loggers::getLogger();`
- 2. Using one of logging functions
-
-The only difference from `printf` is that logging using these functions require `%v` for each arg (This is for type-safety); instead of custom format specifiers. You can escape this by `%%v`
-
-Following are various function signatures:
- * `info(const char*, const T&, const Args&...)`
- * `warn(const char*, const T&, const Args&...)`
- * `error(const char*, const T&, const Args&...)`
- * `debug(const char*, const T&, const Args&...)`
- * `fatal(const char*, const T&, const Args&...)`
- * `trace(const char*, const T&, const Args&...)`
- * `verbose(int vlevel, const char*, const T&, const Args&...)`
-
-#### Simple example:
-
-```c++
-// Use default logger
-el::Logger* defaultLogger = el::Loggers::getLogger("default");
-
-// STL logging (`ELPP_STL_LOGGING` should be defined)
-std::vector i;
-i.push_back(1);
-defaultLogger->warn("My first ultimate log message %v %v %v", 123, 222, i);
-
-// Escaping
-defaultLogger->info("My first ultimate log message %% %%v %v %v", 123, 222);
-
-```
-
- > `%file`, `%func` `%line` and `%loc` format specifiers will not work with `printf` like logging.
-
- [![top] Goto Top](#table-of-contents)
-
-### Network Logging
-
-You can send your messages to network. But you will have to implement your own way using log dispatcher API. We have written fully working sample for this purpose. Please see [Send to Network sample](/samples/send-to-network)
-
- [![top] Goto Top](#table-of-contents)
-
-### Verbose Logging
-#### Basic
-Verbose logging is useful in every software to record more information than usual. Very useful for troubleshooting. Following are verbose logging specific macros;
-* `VLOG(verbose-level)`
-* `CVLOG(verbose-level, logger ID)`
-
- [![top] Goto Top](#table-of-contents)
-
-#### Conditional and Occasional Logging
-Verbose logging also has conditional and occasional logging aspects i.e,
-* `VLOG_IF(condition, verbose-level)`
-* `CVLOG_IF(condition, verbose-level, loggerID)`
-* `VLOG_EVERY_N(n, verbose-level)`
-* `CVLOG_EVERY_N(n, verbose-level, loggerID)`
-* `VLOG_AFTER_N(n, verbose-level)`
-* `CVLOG_AFTER_N(n, verbose-level, loggerID)`
-* `VLOG_N_TIMES(n, verbose-level)`
-* `CVLOG_N_TIMES(n, verbose-level, loggerID)`
-
- [![top] Goto Top](#table-of-contents)
-
-
-#### Verbose-Level
-Verbose level is level of verbosity that can have range of 1-9. Verbose level will not be active unless you either set application arguments for it. Please read through [Application Arguments](#application-arguments) section to understand more about verbose logging.
-
-In order to change verbose level on the fly, please use `Loggers::setVerboseLevel(base::type::VerboseLevel)` aka `Loggers::setVerboseLevel(int)` function. (You can check current verbose level by `Loggers::verboseLevel()`
-
- [![top] Goto Top](#table-of-contents)
-
-#### Check If Verbose Logging Is On
-You can use a macro `VLOG_IS_ON(verbose-level)` to check to see if certain logging is on for source file for specified verbose level. This returns boolean that you can embed into if condition.
-```c++
-if (VLOG_IS_ON(2)) {
- // Verbosity level 2 is on for this file
-}
-```
-
- [![top] Goto Top](#table-of-contents)
-
-#### VModule
-VModule is functionality for verbose logging (as mentioned in above table) where you can specify verbosity by modules/source file. Following are some examples with explanation; Any of vmodule below starts with `-vmodule=` and `LoggingFlag::DisableVModulesExtensions` flag not set. Vmodule can completely be disabled by adding flag `LoggingFlag::DisableVModules`
-
-Example with `LoggingFlag::AllowVerboseIfModuleNotSpecified` flag;
-
-`main=3,parser*=4`:
- * A bad example but good enough for explanation;
- * Verbosity for any following file will be allowed;
- `main{.h, .c, .cpp, .cc, .cxx, -inl.h, .hxx, .hpp}`
- `parser{.h, .c, .cpp, .cc, .cxx, -inl.h, .hxx, .hpp}`
- * No other file will be logged for verbose level
-
-Example with no `LoggingFlag::AllowVerboseIfModuleNotSpecified` flag;
-
-`main=3,parser*=4`:
- Same explanation but any other file that does not fall under specified modules will have verbose logging enabled.
-
-In order to change vmodules on the fly (instead of via command line args) - use `Loggers::setVModules(const char*)` where `const char*` represents the modules e.g, `main=3,parser*=4` (as per above example)
-
- [![top] Goto Top](#table-of-contents)
-
-### Registering New Loggers
-Loggers are unique in logger repository by ID. You can register new logger the same way as you would get logger. Using `getLogger(.., ..)` from `el::Loggers` helper class. This function takes two params, first being ID and second being boolean (optional) to whether or not to register new logger if does not already exist and returns pointer to existing (or newly created) el::Logger class. This second param is optional and defaults to true. If you set it to false and logger does not exist already, it will return nullptr.
-
-By default, Easylogging++ registers three loggers (+ an internal logger);
-* Default logger (ID: `default`)
-* Performance logger (ID: `performance`)
-* Syslog logger (if `ELPP_SYSLOG` macro is defined) (ID: `syslog`)
-
-If you wish to register a new logger, say e.g, with ID `business`
-```c++
-el::Logger* businessLogger = el::Loggers::getLogger("business");
-```
-
-This will register a new logger if it does not already exist otherwise it will get an existing one. But if you have passed in `false` to the second param and logger does not already exist, `businessLogger` will be nullptr.
-
-When you register a new logger, default configurations are used (see Default Configurations section above). Also worth noticing, logger IDs are case sensitive.
-
- [![top] Goto Top](#table-of-contents)
-
-### Unregister Loggers
-You may unregister loggers; any logger except for `default`. You should be really careful with this function, only unregister loggers that you have created yourself otherwise you may end up in unexpected errors. For example, you dont want to unregister logger that is used or initialized by a third-party library and it may be using it.
-
-To unregister logger, use `el::Loggers::unregisterLogger("logger-id")`
-
- [![top] Goto Top](#table-of-contents)
-
-### Populating Existing Logger IDs
-Although this is a rare situation but if you wish to get list of all the logger IDs currently in repository, you may use `el::Loggers::populateAllLoggerIds(std::vector&)` function to do that. The list passed in is cleared and filled up with all existing logger IDs.
-
- [![top] Goto Top](#table-of-contents)
-
-### Sharing Logging Repository
-For advance logging, you can share your logging repositories to shared or static libraries, or even from library to application. This is rare case but a very good example is as follows;
-
-Let's say we have an application that uses easylogging++ and has its own configuration, now you are importing library that uses easylogging++ and wants to access logging repository of main application. You can do this using two ways;
-
- * Instead of using `INITIALIZE_EASYLOGGINGPP` you use `SHARE_EASYLOGGINGPP(access-function-to-repository)`
- * Instead of using `INITIALIZE_EASYLOGGINGPP` you use `INITIALIZE_NULL_EASYLOGGINGPP` and then `el::Helpers::setStorage(el::base::type::StoragePointer)`
-
-After you share repository, you can reconfigure the only repository (i.e, the one that is used by application and library both), and use both to write logs.
-
- [![top] Goto Top](#table-of-contents)
-
-# Extra Features
-Easylogging++ is feature-rich logging library. Apart from features already mentioned above, here are some extra features. If code snippets don't make sense and further sample is needed, there are many samples available at github repository (samples). Feel free to browse around.
-
-Some features require you to define macros (marked as prerequisite in each section) to enable them. This is to reduce compile time. If you want to enable all features you can define `ELPP_FEATURE_ALL`.
-
-### Performance Tracking
-Prerequisite: Define macro `ELPP_FEATURE_PERFORMANCE_TRACKING`
-
-One of the most notable features of Easylogging++ is its ability to track performance of your function or block of function.
-Please note, this is not backward compatible as previously we had macros that user must had defined in order to track performance and I am sure many users had avoided in doing so. (Read v8.91 ReadMe for older way of doing it)
-The new way of tracking performance is much easier and reliable. All you need to do is use one of two macros from where you want to start tracking.
-* `TIMED_FUNC(obj-name)`
-* `TIMED_SCOPE(obj-name, block-name)`
-* `TIMED_BLOCK(obj-name, block-name)`
-
-An example that just uses usleep
-```c++
-void performHeavyTask(int iter) {
- TIMED_FUNC(timerObj);
- // Some initializations
- // Some more heavy tasks
- usleep(5000);
- while (iter-- > 0) {
- TIMED_SCOPE(timerBlkObj, "heavy-iter");
- // Perform some heavy task in each iter
- usleep(10000);
- }
-}
-```
-
-The result of above execution for iter = 10, is as following
-```
-06:22:31,368 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,379 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,389 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,399 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,409 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,419 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,429 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,440 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,450 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,460 INFO Executed [heavy-iter] in [10 ms]
-06:22:31,460 INFO Executed [void performHeavyTask(int)] in [106 ms]
-```
-
-In the above example, we have used both the macros. In line-2 we have `TIMED_FUNC` with object pointer name timerObj and line-7 we have TIMED_SCOPE with object pointer name `timerBlkObj` and block name `heavy-iter`. Notice how block name is thrown out to the logs with every hit. (Note: `TIMED_FUNC` is `TIMED_SCOPE` with block name = function name)
-
-You might wonder why do we need object name. Well easylogging++ performance tracking feature takes it further and provides ability to add, what's called checkpoints.
-Checkpoints have two macros:
-* `PERFORMANCE_CHECKPOINT(timed-block-obj-name)`
-* `PERFORMANCE_CHECKPOINT_WITH_ID(timed-block-obj-name, id)`
-
-Take a look at following example
-```c++
-void performHeavyTask(int iter) {
- TIMED_FUNC(timerObj);
- // Some initializations
- // Some more heavy tasks
- usleep(5000);
- while (iter-- > 0) {
- TIMED_SCOPE(timerBlkObj, "heavy-iter");
- // Perform some heavy task in each iter
- // Notice following sleep varies with each iter
- usleep(iter * 1000);
- if (iter % 3) {
- PERFORMANCE_CHECKPOINT(timerBlkObj);
- }
- }
-}
-```
-
-Notice macro on line-11 (also note comment on line-8). It's checkpoint for heavy-iter block. Now notice following output
-```
-06:33:07,558 INFO Executed [heavy-iter] in [9 ms]
-06:33:07,566 INFO Performance checkpoint for block [heavy-iter] : [8 ms]
-06:33:07,566 INFO Executed [heavy-iter] in [8 ms]
-06:33:07,573 INFO Performance checkpoint for block [heavy-iter] : [7 ms]
-06:33:07,573 INFO Executed [heavy-iter] in [7 ms]
-06:33:07,579 INFO Executed [heavy-iter] in [6 ms]
-06:33:07,584 INFO Performance checkpoint for block [heavy-iter] : [5 ms]
-06:33:07,584 INFO Executed [heavy-iter] in [5 ms]
-06:33:07,589 INFO Performance checkpoint for block [heavy-iter] : [4 ms]
-06:33:07,589 INFO Executed [heavy-iter] in [4 ms]
-06:33:07,592 INFO Executed [heavy-iter] in [3 ms]
-06:33:07,594 INFO Performance checkpoint for block [heavy-iter] : [2 ms]
-06:33:07,594 INFO Executed [heavy-iter] in [2 ms]
-06:33:07,595 INFO Performance checkpoint for block [heavy-iter] : [1 ms]
-06:33:07,595 INFO Executed [heavy-iter] in [1 ms]
-06:33:07,595 INFO Executed [heavy-iter] in [0 ms]
-06:33:07,595 INFO Executed [void performHeavyTask(int)] in [51 ms]
-```
-
-You can also compare two checkpoints if they are in sub-blocks e.g, changing from `PERFORMANCE_CHECKPOINT(timerBlkObj)` to `PERFORMANCE_CHECKPOINT(timerObj)` will result in following output
-```
-06:40:35,522 INFO Performance checkpoint for block [void performHeavyTask(int)] : [51 ms ([1 ms] from last checkpoint)]
-```
-
-If you had used `PERFORMANCE_CHECKPOINT_WITH_ID(timerObj, "mychkpnt");` instead, you will get
-```
-06:44:37,979 INFO Performance checkpoint [mychkpnt] for block [void performHeavyTask(int)] : [51 ms ([1 ms] from checkpoint 'mychkpnt')]
-```
-
-Following are some useful macros that you can define to change the behaviour
-
-| Macro Name | Description |
-|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
-| `ELPP_DISABLE_PERFORMANCE_TRACKING` | Disables performance tracking |
-| `ELPP_PERFORMANCE_MICROSECONDS` | Track up-to microseconds (this includes initializing of el::base::PerformanceTracker as well so might time not be 100% accurate) |
-
-Notes:
-
-1. Performance tracking uses `performance` logger (INFO level) by default unless `el::base::PerformanceTracker` is constructed manually (not using macro - not recommended). When configuring other loggers, make sure you configure this one as well.
-
-2. In above examples, `timerObj` and `timerBlkObj` is of type `el::base::type::PerformanceTrackerPtr`. The `checkpoint()` routine of the `el::base::PerformanceTracker` can be accessed by `timerObj->checkpoint()` but not recommended as this will override behaviour of using macros, behaviour like location of checkpoint.
-
-3. In order to access `el::base::type::PerformanceTrackerPtr` while in `TIMED_BLOCK`, you can use `timerObj.timer`
-
-4. `TIMED_BLOCK` macro resolves to a single-looped for-loop, so be careful where you define `TIMED_BLOCK`, if for-loop is allowed in the line where you use it, you should have no errors.
-
- > You may be interested in [python script to parse performance logs](https://github.com/zuhd-org/easyloggingpp/issues/206)
-
- [![top] Goto Top](#table-of-contents)
-
-#### Conditional Performance Tracking
-If you want to enable performance tracking for certain conditions only, e.g. based on a certain verbosity level, you can use the variants `TIMED_FUNC_IF` or `TIMED_SCOPE_IF`.
-
- A verbosity level example is given below
-
-```c++
- void performHeavyTask(int iter) {
- // enable performance tracking for verbosity level 4 or higher
- TIMED_FUNC_IF( timerObj, VLOG_IS_ON(4) );
- // Some more heavy tasks
- }
-```
-
- [![top] Goto Top](#table-of-contents)
-
-#### Make Use of Performance Tracking Data
-If you wish to capture performance tracking data right after it is finished, you can do so by extending `el::PerformanceTrackingCallback`.
-
-In order to install this handler, use `void Helpers::installPerformanceTrackingCallback(const std::string& id)`. Where `T` is type of your handler. If you wish to uninstall a callback, you can do so by using `Helpers::uninstallPerformanceTrackingCallback(const std::string& id)`. See samples for details
-
- > DO NOT TRACK PERFORMANCE IN THIS HANDLER OR YOU WILL END UP IN INFINITE-LOOP
-
- [![top] Goto Top](#table-of-contents)
-
-### Log File Rotating
-Easylogging++ has ability to roll out (or throw away / rotate) log files if they reach certain limit. You can configure this by setting `Max_Log_File_Size`. See Configuration section above.
-
-Rollout checking happens when Easylogging++ flushes the log file, or, if you have added the flag `el::LoggingFlags::StrictLogFileSizeCheck`, at each log output.
-
-This feature has its own section in this reference manual because you can do stuffs with the file being thrown away. This is useful, for example if you wish to back this file up etc.
-This can be done by using `el::Helpers::installPreRollOutCallback(const PreRollOutCallback& handler)` where `PreRollOutCallback` is typedef of type `std::function`. Please note following if you are using this feature
-
-There is a [sample](/samples/STL/logrotate.cpp) available that you can use as basis.
-
-> You should not log anything in this function. This is because logger would already be locked in multi-threaded application and you can run into dead lock conditions. If you are sure that you are not going to log to same file and not using same logger, feel free to give it a try.
-
- [![top] Goto Top](#table-of-contents)
-
-### Crash Handling
-Prerequisite: Define macro `ELPP_FEATURE_CRASH_LOG`
-
-Easylogging++ provides ability to handle unexpected crashes for GCC compilers. This is active by default and can be disabled by defining macro `ELPP_DISABLE_DEFAULT_CRASH_HANDLING`. By doing so you are telling library not to handle any crashes. Later on if you wish to handle crash yourself, you can assign crash handler of type void func(int) where int is signal caught.
-
-Following signals are handled;
-* SIGABRT (If `ELPP_HANDLE_SIGABRT` macro is defined)
-* SIGFPE
-* SIGILL
-* SIGSEGV
-* SIGINT
-
-Stacktraces are not printed by default, in order to do so define macro `ELPP_FEATURE_CRASH_LOG`. Remember, stack trace is only available for GCC compiler.
-
-> Default handler and stack trace uses `default` logger.
-
-Following are some useful macros that you can define to change the behaviour
-
-| Macro Name | Description |
-|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
-| `ELPP_DISABLE_DEFAULT_CRASH_HANDLING` | Disables default crash handling. |
-| `ELPP_HANDLE_SIGABRT` | Enables handling `SIGABRT`. This is disabled by default to prevent annoying `CTRL + C` behaviour when you wish to abort. |
-
- [![top] Goto Top](#table-of-contents)
-
-#### Installing Custom Crash Handlers
-You can use your own crash handler by using `el::Helpers::setCrashHandler(const el::base::debug::CrashHandler::Handler&);`.
-
-> Make sure to abort application at the end of your crash handler using `el::Helpers::crashAbort(int)`. If you fail to do so, you will get into endless loop of crashes.
-
-Here is a good example of your own handler
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-
-void myCrashHandler(int sig) {
- LOG(ERROR) << "Woops! Crashed!";
- // FOLLOWING LINE IS ABSOLUTELY NEEDED AT THE END IN ORDER TO ABORT APPLICATION
- el::Helpers::crashAbort(sig);
-}
-int main(void) {
- el::Helpers::setCrashHandler(myCrashHandler);
-
- LOG(INFO) << "My crash handler!";
-
- int* i;
- *i = 0; // Crash!
-
- return 0;
-}
-```
-
-> If you wish to log reason for crash you can do so by using `el::Helpers::logCrashReason(int, bool, const el::Level&, const char*)`. Following are default parameters for this function:
-```c++
-> bool stackTraceIfAvailable = false
-> const el::Level& level = el::Level::Fatal
-> const char* logger = "default"
-```
-
- [![top] Goto Top](#table-of-contents)
-
-### Stacktrace
-Prerequisite: Define macro `ELPP_FEATURE_CRASH_LOG`
-
-Easylogging++ supports stack trace printing for GCC compilers. You can print stack trace at anytime by calling `el::base::debug::StackTrace()`, formatting will be done automatically. Note, if you are using non-GCC compiler, you will end-up getting empty output.
-
- [![top] Goto Top](#table-of-contents)
-
-### Multi-threading
-Prerequisite: Define macro `ELPP_THREAD_SAFE`
-
-Easylogging++ is thread-safe. By default thread-safety is disabled. You can enable it by defining `ELPP_THREAD_SAFE` otherwise you will see unexpected results. This is intentional to make library efficient for single threaded application.
-
- [![top] Goto Top](#table-of-contents)
-
-### CHECK Macros
-Easylogging++ supports CHECK macros, with these macros you can quickly check whether certain condition fulfills or not. If not Easylogging++ writes FATAL log, causing application to stop (unless defined macro to prevent stopping application on fatal).
-
-| CHECK Name | Notes + Example |
-|---------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
-| `CHECK(condition)` | Checks for condition e.g, `CHECK(isLoggedIn()) << "Not logged in";` |
-| `CHECK_EQ(a, b)` | Equality check e.g, `CHECK_EQ(getId(), getLoggedOnId()) << "Invalid user logged in";` |
-| `CHECK_NE(a, b)` | Inequality check e.g, `CHECK_NE(isUserBlocked(userId), false) << "User is blocked";` |
-| `CHECK_LT(a, b)` | Less than e.g, `CHECK_LT(1, 2) << "How 1 is not less than 2";` |
-| `CHECK_GT(a, b)` | Greater than e.g, `CHECK_GT(2, 1) << "How 2 is not greater than 1?";` |
-| `CHECK_LE(a, b)` | Less than or equal e.g, `CHECK_LE(1, 1) << "1 is not equal or less than 1";` |
-| `CHECK_GE(a, b)` | Greater than or equal e.g, `CHECK_GE(1, 1) << "1 is not equal or greater than 1";` |
-| `CHECK_NOTNULL(pointer)` | Ensures pointer is not null. This function does not return anything |
-| `CHECK_STREQ(str1, str2)` | C-string equality (case-sensitive) e.g, `CHECK_STREQ(argv[1], "0") << "First arg cannot be 0";` |
-| `CHECK_STRNE(str1, str2)` | C-string inequality (case-sensitive) e.g, `CHECK_STRNE(username1, username2) << "Usernames cannot be same";` |
-| `CHECK_STRCASEEQ(str1, str2)` | C-string inequality (*case-insensitive*) e.g, `CHECK_CASESTREQ(argv[1], "Z") << "First arg cannot be 'z' or 'Z'";` |
-| `CHECK_STRCASENE(str1, str2)` | C-string inequality (*case-insensitive*) e.g, `CHECK_STRCASENE(username1, username2) << "Same username not allowed";` |
-| `CHECK_BOUNDS(val, min, max)` | Checks that `val` falls under the `min` and `max` range e.g, `CHECK_BOUNDS(i, 0, list.size() - 1) << "Index out of bounds";` |
-
-> Same versions of macros are available for `DEBUG` only mode, these macros start with `D` (for debug) followed by the same name. e.g, `DCHECK` to check only in debug mode (i.e, when `_DEBUG` is defined or `NDEBUG` is undefined)
-
- [![top] Goto Top](#table-of-contents)
-
-### Logging perror()
-Easylogging++ supports `perror()` styled logging using `PLOG(LEVEL)`, `PLOG_IF(Condition, LEVEL)`, and `PCHECK()` using `default` logger; and for custom logger use `CPLOG(LEVEL, LoggerId)`, `CPLOG_IF(Condition, LEVEL, LoggerId)`. This will append `: log-error [errno]` in the end of log line.
-
- [![top] Goto Top](#table-of-contents)
-
-### Syslog
-Prerequisite: Define macro `ELPP_SYSLOG`
-
-Easylogging++ supports syslog for platforms that have `syslog.h` header. If your platform does not have `syslog.h`, make sure you do not define this macro or you will end up in errors. Once you are ready to use syslog, you can do so by using one of `SYSLOG(LEVEL)`, `SYSLOG_IF(Condition, LEVEL)`, `SYSLOG_EVERY_N(n, LEVEL)` and uses logger ID: `syslog`. If you want to use custom logger you can do so by using `CSYSLOG(LEVEL, loggerId)` or `CSYSLOG_IF(Condition, LEVEL, loggerId)` or `CSYSLOG_EVERY_N(n, LEVEL, loggerId)`
-
-Syslog in Easylogging++ supports C++ styled streams logging, following example;
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-int main(void) {
- ELPP_INITIALIZE_SYSLOG("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER) // This is optional, you may not add it if you dont want to specify options
- // Alternatively you may do
- // el::SysLogInitializer elSyslogInit("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER);
- SYSLOG(INFO) << "This is syslog - read it from /var/log/syslog"
- return 0;
-}
-```
-
-Syslog support for Easylogging++ only supports following levels; each level is corresponded with syslog priority as following
-
- * INFO (LOG_INFO)
- * DEBUG (LOG_DEBUG)
- * WARNING (LOG_WARNING)
- * ERROR (LOG_ERR)
- * FATAL (LOG_EMERG)
-
-Following levels are not supported and correspond to `LOG_NOTICE`: TRACE, whereas VERBOSE level is completely not supported
-
- [![top] Goto Top](#table-of-contents)
-
-### STL Logging
-Prerequisite: Define macro `ELPP_STL_LOGGING`
-
-As mentioned earlier, with easylogging++, you can log your STL templates including most containers. In order to do so you will need to define `ELPP_STL_LOGGING` macro. This enables including all the necessary headers and defines all necessary functions.
-For performance, containers are limited to log maximum of 100 entries. This behaviour can be changed by changed header file (base::consts::kMaxLogPerContainer) but not recommended as in order to log, writer has to go through each entry causing potential delays. But if you are not really concerned with performance, you may change this value.
-
- [![top] Goto Top](#table-of-contents)
-
-#### Supported Templates
-Following templates are supported as part of STL Logging; note: basic and primitive types e.g, std::string or long are not listed as they is supported anyway, following list only contains non-basic types e.g, containers or bitset etc.
-
-| * | * | * | * |
-|-------------|-------------------------|------------------|------------------|
-| std::vector | std::list | std::deque | std::queue |
-| std::stack | std::priority_queue | std::set | std::multiset |
-| std::pair | std::bitset | std::map | std::multimap |
-
-Some C++11 specific templates are supported by further explicit macro definitions; note these also need `ELPP_STL_LOGGING`
-
-| Template | Macro Needed |
-|-------------------------|-----------------------------|
-| std::array | `ELPP_LOG_STD_ARRAY` |
-| std::unordered_map | `ELPP_LOG_UNORDERED_MAP` |
-| std::unordered_multimap | `ELPP_LOG_UNORDERED_MAP` |
-| std::unordered_set | `ELPP_LOG_UNORDERED_SET` |
-| std::unordered_multiset | `ELPP_LOG_UNORDERED_SET` |
-
-Standard manipulators are also supported, in addition std::stringstream is also supported.
-
-[![top] Goto Top](#table-of-contents)
-
-### Qt Logging
-Prerequisite: Define macro `ELPP_QT_LOGGING`
-
-Easylogging++ has complete logging support for Qt core library. When enabled, this will include all the headers supported Qt logging. Once you did that, you should be good to go.
-
-Following Qt classes and containers are supported by Easylogging++ v9.0+
-
-| * | * | * | * | * | * |
-|---------------|---------------------------|--------------------|--------------------|--------------------|--------------------|
-| `QString` | `QByteArray` | `QLatin` | `QList` | `QVector` | `QQueue` |
-| `QSet` | `QPair` | `QMap` | `QMultiMap` | `QHash` | `QMultiHash` |
-| `QLinkedList` | `QStack` | `QChar` | `q[u]int[64]` | | |
-
-Similar to STL logging, Qt containers are also limit to log 100 entries per log, you can change this behaviour by changing base::consts::kMaxLogPerContainer from header but this is not recommended as this was done for performance purposes.
-
-Also note, if you are logging a container that contains custom class, make sure you have read Extending Library section below.
-
- [![top] Goto Top](#table-of-contents)
-
-### Boost Logging
-Prerequisite: Define macro `ELPP_BOOST_LOGGING`
-
-Easylogging++ supports some of boost templates. Following table shows the templates supported.
-
-| * | * |
-|-------------------------------------|------------------------------------------|
-| `boost::container::vector` | `boost::container::stable_vector` |
-| `boost::container::map` | `boost::container::flat_map` |
-| `boost::container::set` | `boost::container::flat_set` |
-| `boost::container::deque` | `boost::container::list` |
-| `boost::container::string` | |
-
- [![top] Goto Top](#table-of-contents)
-
-### wxWidgets Logging
-Prerequisite: Define macro `ELPP_WXWIDGETS_LOGGING`
-
-Easylogging++ supports some of wxWidgets templates.
-
-Following table shows the templates supported.
-
-| * | * | * | * | * | * |
-|---------------------|-------------------|---------------------------|---------------------------|---------------------|----------------------|
-| `wxString` | `wxVector` | `wxList` | `wxString` | `wxHashSet` | `wxHashMap` |
-
-wxWidgets has its own way of declaring and defining some templates e.g, `wxList` where you use `WX_DECLARE_LIST` macro to declare a list.
-
-In order to setup a container for logging that holds pointers to object, use `ELPP_WX_PTR_ENABLED`, otherwise if container holds actual object e.g, wxHashSet use `ELPP_WX_ENABLED`. For containers like `wxHashMap` because it contains value and pair, use `ELPP_WX_HASH_MAP_ENABLED` macro.
-
-```c++
-// wxList example
-WX_DECLARE_LIST(int, MyList);
-WX_DEFINE_LIST(MyList);
-// Following line does the trick
-ELPP_WX_PTR_ENABLED(MyList);
-
-// wxHashSet example
-WX_DECLARE_HASH_SET(int, wxIntegerHash, wxIntegerEqual, IntHashSet);
-// Following line does the trick!
-ELPP_WX_ENABLED(IntHashSet)
-
-// wxHashMap example
-WX_DECLARE_STRING_HASH_MAP(wxString, MyHashMap);
-// Following line does the trick
-ELPP_WX_HASH_MAP_ENABLED(MyHashMap)
-```
-You may also have a look at wxWidgets sample
-
- [![top] Goto Top](#table-of-contents)
-
-### Extending Library
-You can extend this library using various callback handlers and inheritable classes.
-
-A perfect example of using these features is the logging server built with this library. It's called [Residue](https://github.com/muflihun/residue/) that is feature rich. In fact, you may be interested in using that instead of this library for your medium to large sized projects.
-
-#### Logging Your Own Class
-
-You can log your own classes by extending `el::Loggable` class and implementing pure-virtual function `void log(std::ostream& os) const`. Following example shows a good way to extend a class.
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-class Integer : public el::Loggable {
-public:
- Integer(int i) : m_underlyingInt(i) {
- }
- Integer& operator=(const Integer& integer) {
- m_underlyingInt = integer.m_underlyingInt;
- return *this;
- }
- // Following line does the trick!
- // Note: el::base::type::ostream_t is either std::wostream or std::ostream depending on unicode enabled or not
- virtual void log(el::base::type::ostream_t& os) const {
- os << m_underlyingInt;
- }
-private:
- int m_underlyingInt;
-};
-
-int main(void) {
- Integer count = 5;
- LOG(INFO) << count;
- return 0;
-}
-```
-
- [![top] Goto Top](#table-of-contents)
-
-#### Logging Third-party Class
-Let's say you have third-party class that you don't have access to make changes to, and it's not yet loggable. In order to make it loggable, you can use `MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance)` to make it Easylogging++ friendly.
-
-Following sample shows a good usage:
-```c++
-#include "easylogging++.h"
-
-INITIALIZE_EASYLOGGINGPP
-
-class Integer {
-public:
- Integer(int i) : m_underlyingInt(i) {
- }
- Integer& operator=(const Integer& integer) {
- m_underlyingInt = integer.m_underlyingInt;
- return *this;
- }
- int getInt(void) const { return m_underlyingInt; }
-private:
- int m_underlyingInt;
-};
-
-// Following line does the trick!
-inline MAKE_LOGGABLE(Integer, integer, os) {
- os << integer.getInt();
- return os;
-}
-int main(void) {
- Integer count = 5;
- LOG(INFO) << count;
- return 0;
-}
-```
-
-Another very nice example (to log `std::chrono::system_clock::time_point`)
-
-```c++
-inline MAKE_LOGGABLE(std::chrono::system_clock::time_point, when, os) {
- time_t t = std::chrono::system_clock::to_time_t(when);
- auto tm = std::localtime(&t);
- char buf[1024];
- strftime(buf,sizeof(buf), "%F %T (%Z)", tm);
- os << buf;
- return os;
-}
-```
-
-This may not be practically best implementation but you get the point.
-
- > Just be careful with this as having a time-consuming overloading of `log(el::base::type::ostream_t& os)` and `MAKE_LOGGABLE`, they get called everytime class is being logged.
-
- [![top] Goto Top](#table-of-contents)
-
-### Manually Flushing and Rolling Log Files
-You can manually flush log files using `el::Logger::flush()` (to flush single logger with all referencing log files) or `el::Loggers::flushAll()` (to flush all log files for all levels).
-
-If you have not set flag `LoggingFlag::StrictLogFileSizeCheck` for some reason, you can manually check for log files that need rolling; by using `el::Helpers::validateFileRolling(el::Logger*, const el::Level&)`.
-
- [![top] Goto Top](#table-of-contents)
-
-### Log Dispatch Callback
-If you wish to capture log message right after it is dispatched, you can do so by having a class that extends `el::LogDispatchCallback` and implement the pure-virtual functions, then install it at anytime using `el::Helpers::installLogDispatchCallback(const std::string&)`. If you wish to uninstall a pre-installed handler with same ID, you can do so by using `el::Helpers::uninstallLogDispatchCallback(const std::string&)`
-
-You can use this feature to send it to custom destinations e.g, log stash or TCP client etc.
-
-You can also look at [send-to-network](/samples/send-to-network) sample for practical usage of this.
-
-```c++
-// samples/send-to-network/network-logger.cpp
-
-#include "easylogging++.h"
-
-#include
-
-INITIALIZE_EASYLOGGINGPP
-
-
-class Client
-{
- boost::asio::io_service* io_service;
- boost::asio::ip::tcp::socket socket;
-
-public:
- Client(boost::asio::io_service* svc, const std::string& host, const std::string& port)
- : io_service(svc), socket(*io_service)
- {
- boost::asio::ip::tcp::resolver resolver(*io_service);
- boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port));
- boost::asio::connect(this->socket, endpoint);
- };
-
- void send(std::string const& message) {
- socket.send(boost::asio::buffer(message));
- }
-};
-
-class NetworkDispatcher : public el::LogDispatchCallback
-{
-public:
- void updateServer(const std::string& host, int port) {
- m_client = std::unique_ptr(new Client(&m_svc, host, std::to_string(port)));
- }
-protected:
- void handle(const el::LogDispatchData* data) noexcept override {
- m_data = data;
- // Dispatch using default log builder of logger
- dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
- m_data->dispatchAction() == el::base::DispatchAction::NormalLog));
- }
-private:
- const el::LogDispatchData* m_data;
- boost::asio::io_service m_svc;
- std::unique_ptr m_client;
-
- void dispatch(el::base::type::string_t&& logLine) noexcept
- {
- m_client->send(logLine);
- }
-};
-
-
-int main() {
- el::Helpers::installLogDispatchCallback("NetworkDispatcher");
- // you can uninstall default one by
- // el::Helpers::uninstallLogDispatchCallback("DefaultLogDispatchCallback");
- // Set server params
- NetworkDispatcher* dispatcher = el::Helpers::logDispatchCallback("NetworkDispatcher");
- dispatcher->setEnabled(true);
- dispatcher->updateServer("127.0.0.1", 9090);
-
- // Start logging and normal program...
- LOG(INFO) << "First network log";
-
- // You can even use a different logger, say "network" and send using a different log pattern
-}
-```
-
- > DO NOT LOG ANYTHING IN THIS HANDLER OR YOU WILL END UP IN INFINITE-LOOP
-
- [![top] Goto Top](#table-of-contents)
-
-### Logger Registration Callback
-If you wish to capture event of logger registration (and potentially want to reconfigure this logger without changing default configuration) you can use `el::LoggerRegistrationCallback`. The syntax is similar to [other callbacks](#log-dispatch-callback). You can use [this sample](https://github.com/zuhd-org/easyloggingpp/blob/master/samples/STL/new-logger-registration-callback.cpp) as basis.
-
- > DO NOT LOG ANYTHING IN THIS HANDLER
-
- [![top] Goto Top](#table-of-contents)
-
-### Asynchronous Logging
-Prerequisite: Define macro `ELPP_EXPERIMENTAL_ASYNC`
-
-Asynchronous logging is in experimental stages and they are not widely promoted. You may enable and test this feature by defining macro `ELPP_EXPERIMENTAL_ASYNC` and if you find some issue with the feature please report in [this issue](https://github.com/zuhd-org/easyloggingpp/issues/202). Reporting issues always help for constant improvements.
-
-Please note:
-* Asynchronous will only work with few compilers (it purely uses `std::thread`)
-* Compiler should support `std::this_thread::sleep_for`. This restriction may (or may not) be removed in future (stable) version of asynchronous logging.
-* You should not rely on asynchronous logging in production, this is because feature is in experiemental stages.
-
- [![top] Goto Top](#table-of-contents)
-
-### Helper Classes
-There are static helper classes available to make it easy to do stuffs;
-
- * `el::Helpers`
- * `el::Loggers`
-
-You can do various cool stuffs using functions in these classes, see [this issue](https://github.com/zuhd-org/easyloggingpp/issues/210) for instance.
-
- [![top] Goto Top](#table-of-contents)
-
-# Contribution
-### Submitting Patches
-You can submit patches to `develop` branch and we will try and merge them. Since it's based on single header, it can be sometimes difficult to merge without having merge conflicts.
-
- [![top] Goto Top](#table-of-contents)
-
-### Reporting a Bug
-If you have found a bug and wish to report it, feel free to do so at [github issue tracker](https://github.com/zuhd-org/easyloggingpp/issues?state=open). I will try to look at it as soon as possible. Some information should be provided to make it easy to reproduce;
-* Platform (OS, Compiler)
-* Log file location
-* Macros defined (on compilation) OR simple compilation
-* Please assign issue label.
-
-Try to provide as much information as possible. Any bug with no clear information will be ignored and closed.
-
- [![top] Goto Top](#table-of-contents)
-
-# Compatibility
-
-Easylogging++ requires a decent C++0x complient compiler. Some compilers known to work with v9.0+ are shown in table below, for older versions please refer to readme on corresponding release at github
-
-| ***** | Compiler/Platform | Notes |
-|---------|---------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
-|![gcc] | GCC 4.6.4+ | Stack trace logging. Very close to support GCC 4.6.0 if it had supported strong enum types casting to underlying type. It causes internal compiler error. |
-|![llvm] | Clang++ 3.1+ | Stack trace logging only with gcc compliant. |
-|![intel] | Intel C++ 13.0+ | Workarounds to support: Use if instead of switch on strong enum type. No `final` keyword etc. Stack trace logging only with gcc compliant |
-|![vcpp] | Visual C++ 11.0+ | Tested with VS2012, VS2013; Use of argument templates instead of variadic templates. CRT warnings control. No stack trace logging. |
-|![mingw] | MinGW | (gcc version 4.7+) Workarounds to support: Mutex wrapper, no stack trace logging. No thread ID on windows |
-|![tdm] | TDM-GCC 4.7.1 | Tested with TDM-GCC 4.7.1 32 and 64 bit compilers |
-|![cygwin]| Cygwin | Tested with gcc version 4.8+ |
-|![devcpp]| Dev C++ 5.4+ | Tested with Dev-C++ 5.4.2 using TDM-GCC 4.7.1 32 & 64-bit compilers |
-
-Operating systems that have been tested are shown in table below. Easylogging++ should work on other major operating systems that are not in the list.
-
-| ***** | Operating System | Notes |
-|---------------|------------------------|-------------------------------------------------------------------------------------|
-|![win10] | Windows 10 | Tested on 64-bit, should also work on 32-bit |
-|![win8] | Windows 8 | Tested on 64-bit, should also work on 32-bit |
-|![win7] | Windows 7 | Tested on 64-bit, should also work on 32-bit |
-|![winxp] | Windows XP | Tested on 32-bit, should also work on 64-bit |
-|![mac] | Mac OSX | Clang++ 3.1, g++ (You need `-std=c++11 -stdlib=libc++` to successfully compile) |
-|![sl] | Scientific Linux 6.2 | Tested using Intel C++ 13.1.3 (gcc version 4.4.6 compatibility) |
-|![mint] | Linux Mint 14 | 64-bit, mainly developed on this machine using all compatible linux compilers |
-|![fedora] | Fedora 19 | 64-bit, using g++ 4.8.1 |
-|![ubuntu] | Ubuntu 13.04 | 64-bit, using g++ 4.7.3 (libstdc++6-4.7-dev) |
-|![freebsd] | FreeBSD | (from github user) |
-|![android] | Android | Tested with C4droid (g++) on Galaxy Tab 2 |
-|![raspberrypi] | RaspberryPi 7.6 | Tested with 7.6.2-1.1 (gcc version 4.9.1 (Raspbian 4.9.1-1)) by contributor |
-|![solaris] | Solaris i86 | Tested by contributor |
-|![aix] | IBM AIX | Support added by contributor |
-
-Easylogging++ has also been tested with following C++ libraries;
-
-| ***** | Library | Notes |
-|-------------|------------------------|-------------------------------------------------------------------------------------|
-|![qt] | Qt | Tested with Qt 4.6.2, Qt 5 and Qt 5.5 (with C++0x and C++11) |
-|![boost] | Boost | Tested with boost 1.51 |
-|![wxwidgets] | wxWidgets | Tested with wxWidgets 2.9.4 |
-|![gtkmm] | gtkmm | Tested with gtkmm 2.4 |
-
- [![top] Goto Top](#table-of-contents)
-
- ## Build Matrix
-
- | Branch | Platform | Build Status |
- | -------- |:------------:|:------------:|
- | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `clang++` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/develop/1)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-4.9` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/develop/2)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-5` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/develop/3)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-6` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/develop/4)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-7` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/develop/5)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `clang++` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/master/1)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-4.9` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/master/2)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-5` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/master/3)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-6` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/master/4)](https://travis-ci.org/zuhd-org/easyloggingpp) |
- | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-7` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/zuhd-org/easyloggingpp/branches/master/5)](https://travis-ci.org/zuhd-org/easyloggingpp) |
-
- [![top] Goto Top](#table-of-contents)
-
-# Licence
-```
-The MIT License (MIT)
-
-Copyright (c) 2012-2018 Zuhd Web Services
-Copyright (c) 2012-2018 @abumusamq
-
-https://github.com/zuhd-org/
-https://zuhd.org
-https://muflihun.com
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-```
-
- [![top] Goto Top](#table-of-contents)
-
-# Disclaimer
-Icons used in this manual (in compatibility section) are solely for information readability purposes. I do not own these icons. If anyone has issues with usage of these icon, please feel free to contact me via company's email and I will look for an alternative. Company's email address is required so that I can verify the ownership, any other email address for this purpose will be ignored.
-
-"Pencil +" icon is Easylogging++ logo and should only be used where giving credit to Easylogging++ library.
-
-
- [![top] Goto Top](#table-of-contents)
-
- [banner]: https://muflihun.github.io/easyloggingpp/images/banner.png?v=4
- [ubuntu]: https://muflihun.github.io/easyloggingpp/images/icons/ubuntu.png?v=2
- [mint]: https://muflihun.github.io/easyloggingpp/images/icons/linux-mint.png?v=2
- [freebsd]: https://muflihun.github.io/easyloggingpp/images/icons/free-bsd.png?v=2
- [sl]: https://muflihun.github.io/easyloggingpp/images/icons/scientific-linux.png?v=2
- [fedora]: https://muflihun.github.io/easyloggingpp/images/icons/fedora.png?v=3
- [mac]: https://muflihun.github.io/easyloggingpp/images/icons/mac-osx.png?v=2
- [winxp]: https://muflihun.github.io/easyloggingpp/images/icons/windowsxp.png?v=2
- [win7]: https://muflihun.github.io/easyloggingpp/images/icons/windows7.png?v=2
- [win8]: https://muflihun.github.io/easyloggingpp/images/icons/windows8.png?v=2
- [win10]: https://muflihun.github.io/easyloggingpp/images/icons/windows10.png?v=2
- [qt]: https://muflihun.github.io/easyloggingpp/images/icons/qt.png?v=3
- [boost]: https://muflihun.github.io/easyloggingpp/images/icons/boost.png?v=3
- [wxwidgets]: https://muflihun.github.io/easyloggingpp/images/icons/wxwidgets.png?v=3
- [devcpp]: https://muflihun.github.io/easyloggingpp/images/icons/devcpp.png?v=3
- [gtkmm]: https://muflihun.github.io/easyloggingpp/images/icons/gtkmm.png?v=3
- [tdm]: https://muflihun.github.io/easyloggingpp/images/icons/tdm.png?v=3
- [raspberrypi]: https://muflihun.github.io/easyloggingpp/images/icons/raspberry-pi.png?v=3
- [solaris]: https://muflihun.github.io/easyloggingpp/images/icons/solaris.png?v=3
- [aix]: https://muflihun.github.io/easyloggingpp/images/icons/aix.png?v=4
-
-
- [gcc]: https://muflihun.github.io/easyloggingpp/images/icons/gcc.png?v=4
- [mingw]: https://muflihun.github.io/easyloggingpp/images/icons/mingw.png?v=2
- [cygwin]: https://muflihun.github.io/easyloggingpp/images/icons/cygwin.png?v=2
- [vcpp]: https://muflihun.github.io/easyloggingpp/images/icons/vcpp.png?v=2
- [llvm]: https://muflihun.github.io/easyloggingpp/images/icons/llvm.png?v=2
- [intel]: https://muflihun.github.io/easyloggingpp/images/icons/intel.png?v=2
- [android]: https://muflihun.github.io/easyloggingpp/images/icons/android.png?v=2
- [manual]: https://muflihun.github.io/easyloggingpp/images/help.png?v=3
- [download]: https://muflihun.github.io/easyloggingpp/images/download.png?v=2
- [samples]: https://muflihun.github.io/easyloggingpp/images/sample.png?v=2
- [notes]: https://muflihun.github.io/easyloggingpp/images/notes.png?v=4
- [top]: https://muflihun.github.io/easyloggingpp/images/up.png?v=4
- [www]: https://muflihun.github.io/easyloggingpp/images/logo-www.png?v=6
diff --git a/3rdparty/easyloggingpp/src/easylogging++.cc b/3rdparty/easyloggingpp/src/easylogging++.cc
deleted file mode 100644
index d763ee7..0000000
--- a/3rdparty/easyloggingpp/src/easylogging++.cc
+++ /dev/null
@@ -1,3112 +0,0 @@
-//
-// Bismillah ar-Rahmaan ar-Raheem
-//
-// Easylogging++ v9.96.7
-// Cross-platform logging library for C++ applications
-//
-// Copyright (c) 2012-2018 Zuhd Web Services
-// Copyright (c) 2012-2018 @abumusamq
-//
-// This library is released under the MIT Licence.
-// https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE
-//
-// https://zuhd.org
-// http://muflihun.com
-//
-
-#include "easylogging++.h"
-
-#if defined(AUTO_INITIALIZE_EASYLOGGINGPP)
-INITIALIZE_EASYLOGGINGPP
-#endif
-
-namespace el {
-
-// el::base
-namespace base {
-// el::base::consts
-namespace consts {
-
-// Level log values - These are values that are replaced in place of %level format specifier
-// Extra spaces after format specifiers are only for readability purposes in log files
-static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO");
-static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG");
-static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING");
-static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR");
-static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL");
-static const base::type::char_t* kVerboseLevelLogValue =
- ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level
-static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE");
-static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I");
-static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D");
-static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W");
-static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E");
-static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F");
-static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V");
-static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T");
-// Format specifiers - These are used to define log format
-static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app");
-static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger");
-static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread");
-static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level");
-static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort");
-static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime");
-static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file");
-static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase");
-static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line");
-static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc");
-static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func");
-static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user");
-static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host");
-static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg");
-static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel");
-static const char* kDateTimeFormatSpecifierForFilename = "%datetime";
-// Date/time
-static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
-static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
-static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August",
- "September", "October", "November", "December"
- };
-static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
-static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g";
-static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m";
-static const int kYearBase = 1900;
-static const char* kAm = "AM";
-static const char* kPm = "PM";
-// Miscellaneous constants
-
-static const char* kNullPointer = "nullptr";
-#if ELPP_VARIADIC_TEMPLATES_SUPPORTED
-#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED
-static const base::type::VerboseLevel kMaxVerboseLevel = 9;
-static const char* kUnknownUser = "user";
-static const char* kUnknownHost = "unknown-host";
-
-
-//---------------- DEFAULT LOG FILE -----------------------
-
-#if defined(ELPP_NO_DEFAULT_LOG_FILE)
-# if ELPP_OS_UNIX
-static const char* kDefaultLogFile = "/dev/null";
-# elif ELPP_OS_WINDOWS
-static const char* kDefaultLogFile = "nul";
-# endif // ELPP_OS_UNIX
-#elif defined(ELPP_DEFAULT_LOG_FILE)
-static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE;
-#else
-static const char* kDefaultLogFile = "myeasylog.log";
-#endif // defined(ELPP_NO_DEFAULT_LOG_FILE)
-
-
-#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
-static const char* kDefaultLogFileParam = "--default-log-file";
-#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG)
-#if defined(ELPP_LOGGING_FLAGS_FROM_ARG)
-static const char* kLoggingFlagsParam = "--logging-flags";
-#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
-static const char* kValidLoggerIdSymbols =
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
-static const char* kConfigurationComment = "##";
-static const char* kConfigurationLevel = "*";
-static const char* kConfigurationLoggerId = "--";
-}
-// el::base::utils
-namespace utils {
-
-/// @brief Aborts application due with user-defined status
-static void abort(int status, const std::string& reason) {
- // Both status and reason params are there for debugging with tools like gdb etc
- ELPP_UNUSED(status);
- ELPP_UNUSED(reason);
-#if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
- // Ignore msvc critical error dialog - break instead (on debug mode)
- _asm int 3
-#else
- ::abort();
-#endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG)
-}
-
-} // namespace utils
-} // namespace base
-
-// el
-
-// LevelHelper
-
-const char* LevelHelper::convertToString(Level level) {
- // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
- if (level == Level::Global) return "GLOBAL";
- if (level == Level::Debug) return "DEBUG";
- if (level == Level::Info) return "INFO";
- if (level == Level::Warning) return "WARNING";
- if (level == Level::Error) return "ERROR";
- if (level == Level::Fatal) return "FATAL";
- if (level == Level::Verbose) return "VERBOSE";
- if (level == Level::Trace) return "TRACE";
- return "UNKNOWN";
-}
-
-struct StringToLevelItem {
- const char* levelString;
- Level level;
-};
-
-static struct StringToLevelItem stringToLevelMap[] = {
- { "global", Level::Global },
- { "debug", Level::Debug },
- { "info", Level::Info },
- { "warning", Level::Warning },
- { "error", Level::Error },
- { "fatal", Level::Fatal },
- { "verbose", Level::Verbose },
- { "trace", Level::Trace }
-};
-
-Level LevelHelper::convertFromString(const char* levelStr) {
- for (auto& item : stringToLevelMap) {
- if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) {
- return item.level;
- }
- }
- return Level::Unknown;
-}
-
-void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function& fn) {
- base::type::EnumType lIndexMax = LevelHelper::kMaxValid;
- do {
- if (fn()) {
- break;
- }
- *startIndex = static_cast(*startIndex << 1);
- } while (*startIndex <= lIndexMax);
-}
-
-// ConfigurationTypeHelper
-
-const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) {
- // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
- if (configurationType == ConfigurationType::Enabled) return "ENABLED";
- if (configurationType == ConfigurationType::Filename) return "FILENAME";
- if (configurationType == ConfigurationType::Format) return "FORMAT";
- if (configurationType == ConfigurationType::ToFile) return "TO_FILE";
- if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT";
- if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION";
- if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING";
- if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE";
- if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD";
- return "UNKNOWN";
-}
-
-struct ConfigurationStringToTypeItem {
- const char* configString;
- ConfigurationType configType;
-};
-
-static struct ConfigurationStringToTypeItem configStringToTypeMap[] = {
- { "enabled", ConfigurationType::Enabled },
- { "to_file", ConfigurationType::ToFile },
- { "to_standard_output", ConfigurationType::ToStandardOutput },
- { "format", ConfigurationType::Format },
- { "filename", ConfigurationType::Filename },
- { "subsecond_precision", ConfigurationType::SubsecondPrecision },
- { "milliseconds_width", ConfigurationType::MillisecondsWidth },
- { "performance_tracking", ConfigurationType::PerformanceTracking },
- { "max_log_file_size", ConfigurationType::MaxLogFileSize },
- { "log_flush_threshold", ConfigurationType::LogFlushThreshold },
-};
-
-ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) {
- for (auto& item : configStringToTypeMap) {
- if (base::utils::Str::cStringCaseEq(configStr, item.configString)) {
- return item.configType;
- }
- }
- return ConfigurationType::Unknown;
-}
-
-void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function& fn) {
- base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid;
- do {
- if (fn()) {
- break;
- }
- *startIndex = static_cast(*startIndex << 1);
- } while (*startIndex <= cIndexMax);
-}
-
-// Configuration
-
-Configuration::Configuration(const Configuration& c) :
- m_level(c.m_level),
- m_configurationType(c.m_configurationType),
- m_value(c.m_value) {
-}
-
-Configuration& Configuration::operator=(const Configuration& c) {
- if (&c != this) {
- m_level = c.m_level;
- m_configurationType = c.m_configurationType;
- m_value = c.m_value;
- }
- return *this;
-}
-
-/// @brief Full constructor used to sets value of configuration
-Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) :
- m_level(level),
- m_configurationType(configurationType),
- m_value(value) {
-}
-
-void Configuration::log(el::base::type::ostream_t& os) const {
- os << LevelHelper::convertToString(m_level)
- << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType)
- << ELPP_LITERAL(" = ") << m_value.c_str();
-}
-
-/// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
-Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) :
- m_level(level),
- m_configurationType(configurationType) {
-}
-
-bool Configuration::Predicate::operator()(const Configuration* conf) const {
- return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType));
-}
-
-// Configurations
-
-Configurations::Configurations(void) :
- m_configurationFile(std::string()),
- m_isFromFile(false) {
-}
-
-Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining,
- Configurations* base) :
- m_configurationFile(configurationFile),
- m_isFromFile(false) {
- parseFromFile(configurationFile, base);
- if (useDefaultsForRemaining) {
- setRemainingToDefault();
- }
-}
-
-bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) {
- // We initial assertion with true because if we have assertion diabled, we want to pass this
- // check and if assertion is enabled we will have values re-assigned any way.
- bool assertionPassed = true;
- ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true,
- "Configuration file [" << configurationFile << "] does not exist!");
- if (!assertionPassed) {
- return false;
- }
- bool success = Parser::parseFromFile(configurationFile, this, base);
- m_isFromFile = success;
- return success;
-}
-
-bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) {
- bool success = Parser::parseFromText(configurationsString, this, base);
- if (success) {
- m_isFromFile = false;
- }
- return success;
-}
-
-void Configurations::setFromBase(Configurations* base) {
- if (base == nullptr || base == this) {
- return;
- }
- base::threading::ScopedLock scopedLock(base->lock());
- for (Configuration*& conf : base->list()) {
- set(conf);
- }
-}
-
-bool Configurations::hasConfiguration(ConfigurationType configurationType) {
- base::type::EnumType lIndex = LevelHelper::kMinValid;
- bool result = false;
- LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
- if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) {
- result = true;
- }
- return result;
- });
- return result;
-}
-
-bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) {
- base::threading::ScopedLock scopedLock(lock());
-#if ELPP_COMPILER_INTEL
- // We cant specify template types here, Intel C++ throws compilation error
- // "error: type name is not allowed"
- return RegistryWithPred::get(level, configurationType) != nullptr;
-#else
- return RegistryWithPred::get(level, configurationType) != nullptr;
-#endif // ELPP_COMPILER_INTEL
-}
-
-void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) {
- base::threading::ScopedLock scopedLock(lock());
- unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex
- if (level == Level::Global) {
- unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either
- }
-}
-
-void Configurations::set(Configuration* conf) {
- if (conf == nullptr) {
- return;
- }
- set(conf->level(), conf->configurationType(), conf->value());
-}
-
-void Configurations::setToDefault(void) {
- setGlobally(ConfigurationType::Enabled, std::string("true"), true);
- setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true);
-#if defined(ELPP_NO_LOG_TO_FILE)
- setGlobally(ConfigurationType::ToFile, std::string("false"), true);
-#else
- setGlobally(ConfigurationType::ToFile, std::string("true"), true);
-#endif // defined(ELPP_NO_LOG_TO_FILE)
- setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true);
- setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true);
- setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true);
- setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true);
- setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true);
-
- setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true);
- set(Level::Debug, ConfigurationType::Format,
- std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
- // INFO and WARNING are set to default by Level::Global
- set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
- set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
- set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
- set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
-}
-
-void Configurations::setRemainingToDefault(void) {
- base::threading::ScopedLock scopedLock(lock());
-#if defined(ELPP_NO_LOG_TO_FILE)
- unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false"));
-#else
- unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true"));
-#endif // defined(ELPP_NO_LOG_TO_FILE)
- unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile));
- unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true"));
- unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3"));
- unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true"));
- unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0"));
- unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
- unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format,
- std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg"));
- // INFO and WARNING are set to default by Level::Global
- unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
- unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"));
- unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg"));
- unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format,
- std::string("%datetime %level [%logger] [%func] [%loc] %msg"));
-}
-
-bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender,
- Configurations* base) {
- sender->setFromBase(base);
- std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in);
- ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing.");
- bool parsedSuccessfully = false;
- std::string line = std::string();
- Level currLevel = Level::Unknown;
- std::string currConfigStr = std::string();
- std::string currLevelStr = std::string();
- while (fileStream_.good()) {
- std::getline(fileStream_, line);
- parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
- ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
- }
- return parsedSuccessfully;
-}
-
-bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender,
- Configurations* base) {
- sender->setFromBase(base);
- bool parsedSuccessfully = false;
- std::stringstream ss(configurationsString);
- std::string line = std::string();
- Level currLevel = Level::Unknown;
- std::string currConfigStr = std::string();
- std::string currLevelStr = std::string();
- while (std::getline(ss, line)) {
- parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender);
- ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line);
- }
- return parsedSuccessfully;
-}
-
-void Configurations::Parser::ignoreComments(std::string* line) {
- std::size_t foundAt = 0;
- std::size_t quotesStart = line->find("\"");
- std::size_t quotesEnd = std::string::npos;
- if (quotesStart != std::string::npos) {
- quotesEnd = line->find("\"", quotesStart + 1);
- while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') {
- // Do not erase slash yet - we will erase it in parseLine(..) while loop
- quotesEnd = line->find("\"", quotesEnd + 2);
- }
- }
- if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) {
- if (foundAt < quotesEnd) {
- foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1);
- }
- *line = line->substr(0, foundAt);
- }
-}
-
-bool Configurations::Parser::isLevel(const std::string& line) {
- return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel));
-}
-
-bool Configurations::Parser::isComment(const std::string& line) {
- return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment));
-}
-
-bool Configurations::Parser::isConfig(const std::string& line) {
- std::size_t assignment = line.find('=');
- return line != "" &&
- ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) &&
- (assignment != std::string::npos) &&
- (line.size() > assignment);
-}
-
-bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr,
- Level* currLevel,
- Configurations* conf) {
- ConfigurationType currConfig = ConfigurationType::Unknown;
- std::string currValue = std::string();
- *line = base::utils::Str::trim(*line);
- if (isComment(*line)) return true;
- ignoreComments(line);
- *line = base::utils::Str::trim(*line);
- if (line->empty()) {
- // Comment ignored
- return true;
- }
- if (isLevel(*line)) {
- if (line->size() <= 2) {
- return true;
- }
- *currLevelStr = line->substr(1, line->size() - 2);
- *currLevelStr = base::utils::Str::toUpper(*currLevelStr);
- *currLevelStr = base::utils::Str::trim(*currLevelStr);
- *currLevel = LevelHelper::convertFromString(currLevelStr->c_str());
- return true;
- }
- if (isConfig(*line)) {
- std::size_t assignment = line->find('=');
- *currConfigStr = line->substr(0, assignment);
- *currConfigStr = base::utils::Str::toUpper(*currConfigStr);
- *currConfigStr = base::utils::Str::trim(*currConfigStr);
- currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str());
- currValue = line->substr(assignment + 1);
- currValue = base::utils::Str::trim(currValue);
- std::size_t quotesStart = currValue.find("\"", 0);
- std::size_t quotesEnd = std::string::npos;
- if (quotesStart != std::string::npos) {
- quotesEnd = currValue.find("\"", quotesStart + 1);
- while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') {
- currValue = currValue.erase(quotesEnd - 1, 1);
- quotesEnd = currValue.find("\"", quotesEnd + 2);
- }
- }
- if (quotesStart != std::string::npos && quotesEnd != std::string::npos) {
- // Quote provided - check and strip if valid
- ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in ["
- << currConfigStr << "]");
- ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]");
- if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) {
- // Explicit check in case if assertion is disabled
- currValue = currValue.substr(quotesStart + 1, quotesEnd - 1);
- }
- }
- }
- ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]");
- ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]");
- if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) {
- return false; // unrecognizable level or config
- }
- conf->set(*currLevel, currConfig, currValue);
- return true;
-}
-
-void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) {
- Configuration* conf = RegistryWithPred::get(level, configurationType);
- if (conf == nullptr) {
- unsafeSet(level, configurationType, value);
- }
-}
-
-void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) {
- Configuration* conf = RegistryWithPred::get(level, configurationType);
- if (conf == nullptr) {
- registerNew(new Configuration(level, configurationType, value));
- } else {
- conf->setValue(value);
- }
- if (level == Level::Global) {
- unsafeSetGlobally(configurationType, value, false);
- }
-}
-
-void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value,
- bool includeGlobalLevel) {
- if (includeGlobalLevel) {
- set(Level::Global, configurationType, value);
- }
- base::type::EnumType lIndex = LevelHelper::kMinValid;
- LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
- set(LevelHelper::castFromInt(lIndex), configurationType, value);
- return false; // Do not break lambda function yet as we need to set all levels regardless
- });
-}
-
-void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value,
- bool includeGlobalLevel) {
- if (includeGlobalLevel) {
- unsafeSet(Level::Global, configurationType, value);
- }
- base::type::EnumType lIndex = LevelHelper::kMinValid;
- LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
- unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value);
- return false; // Do not break lambda function yet as we need to set all levels regardless
- });
-}
-
-// LogBuilder
-
-void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) {
- if (!m_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;
- else if (level == Level::Debug)
- *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor;
- else if (level == Level::Info)
- *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor;
- else if (level == Level::Trace)
- *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor;
-}
-
-// Logger
-
-Logger::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::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::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& Logger::operator=(const Logger& logger) {
- if (&logger != this) {
- 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;
-}
-
-void Logger::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(m_typedConfigurations->configurations());
- if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) {
- flush();
- }
- }
- base::threading::ScopedLock scopedLock(lock());
- if (m_configurations != configurations) {
- m_configurations.setFromBase(const_cast(&configurations));
- }
- base::utils::safeDelete(m_typedConfigurations);
- m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference);
- resolveLoggerFormatSpec();
- m_isConfigured = true;
-}
-
-void Logger::reconfigure(void) {
- ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]");
- configure(m_configurations);
-}
-
-bool Logger::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;
-}
-
-void Logger::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;
- });
-}
-
-void Logger::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();
- std::unordered_map::iterator iter = m_unflushedCount.find(level);
- if (iter != m_unflushedCount.end()) {
- iter->second = 0;
- }
- Helpers::validateFileRolling(this, level);
- }
-}
-
-void Logger::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;
- });
-}
-
-void Logger::resolveLoggerFormatSpec(void) const {
- base::type::EnumType lIndex = LevelHelper::kMinValid;
- LevelHelper::forEachLevel(&lIndex, [&](void) -> bool {
- base::LogFormat* logFormat =
- const_cast(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex)));
- base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id);
- return false;
- });
-}
-
-// el::base
-namespace base {
-
-// el::base::utils
-namespace utils {
-
-// File
-
-base::type::fstream_t* File::newFileStream(const std::string& filename) {
- base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(),
- base::type::fstream_t::out
-#if !defined(ELPP_FRESH_LOG_FILE)
- | base::type::fstream_t::app
-#endif
- );
-#if defined(ELPP_UNICODE)
- std::locale elppUnicodeLocale("");
-# if ELPP_OS_WINDOWS
- std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16);
- elppUnicodeLocale = elppUnicodeLocaleWindows;
-# endif // ELPP_OS_WINDOWS
- 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;
-}
-
-std::size_t File::getSizeOfFile(base::type::fstream_t* fs) {
- if (fs == nullptr) {
- return 0;
- }
- // Since the file stream is appended to or truncated, the current
- // offset is the file size.
- std::size_t size = static_cast(fs->tellg());
- return size;
-}
-
-bool File::pathExists(const char* path, bool considerFile) {
- 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
-}
-
-bool File::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(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_ = nullptr;
- 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;
-}
-
-std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) {
- if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) {
- return fullPath;
- }
- std::size_t lastSlashAt = fullPath.find_last_of(separator);
- if (lastSlashAt == 0) {
- return std::string(separator);
- }
- return fullPath.substr(0, lastSlashAt + 1);
-}
-
-void File::buildStrippedFilename(const char* filename, char buff[], std::size_t limit) {
- 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);
-}
-
-void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) {
- const char *filename = fullPath.c_str();
- std::size_t lastSlashAt = fullPath.find_last_of(separator);
- 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);
-}
-
-// Str
-
-bool Str::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;
- default:
- if (*str++ != *pattern++)
- return false;
- break;
- }
- }
- return !*str && !*pattern;
-}
-
-std::string& Str::ltrim(std::string& str) {
- str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) {
- return !std::isspace(c);
- } ));
- return str;
-}
-
-std::string& Str::rtrim(std::string& str) {
- str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) {
- return !std::isspace(c);
- }).base(), str.end());
- return str;
-}
-
-std::string& Str::trim(std::string& str) {
- return ltrim(rtrim(str));
-}
-
-bool Str::startsWith(const std::string& str, const std::string& start) {
- return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0);
-}
-
-bool Str::endsWith(const std::string& str, const std::string& end) {
- return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0);
-}
-
-std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) {
- std::replace(str.begin(), str.end(), replaceWhat, replaceWith);
- return str;
-}
-
-std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat,
- 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;
-}
-
-void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
- 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 - 1, 1);
- ++foundAt;
- } else {
- str.replace(foundAt, replaceWhat.length(), replaceWith);
- return;
- }
- }
-}
-#if defined(ELPP_UNICODE)
-void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
- const std::string& replaceWith) {
- replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end()));
-}
-#endif // defined(ELPP_UNICODE)
-
-std::string& Str::toUpper(std::string& str) {
- std::transform(str.begin(), str.end(), str.begin(),
- [](char c) {
- return static_cast(::toupper(c));
- });
- return str;
-}
-
-bool Str::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;
-}
-
-bool Str::cStringCaseEq(const char* s1, const char* s2) {
- if (s1 == nullptr && s2 == nullptr) return true;
- if (s1 == nullptr || s2 == nullptr) return false;
-
- // With thanks to cygwin for this code
- int d = 0;
-
- while (true) {
- const int c1 = toupper(*s1++);
- const int c2 = toupper(*s2++);
-
- if (((d = c1 - c2) != 0) || (c2 == '\0')) {
- break;
- }
- }
-
- return d == 0;
-}
-
-bool Str::contains(const char* str, char c) {
- for (; *str; ++str) {
- if (*str == c)
- return true;
- }
- return false;
-}
-
-char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) {
- 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(n % 10 + '0');
- } else {
- *--p = '0';
- --len;
- }
- if (zeroPadded)
- while (p > localBuff && len-- > 0) *--p = static_cast('0');
- return addToBuff(p, buf, bufLim);
-}
-
-char* Str::addToBuff(const char* str, char* buf, const char* bufLim) {
- while ((buf < bufLim) && ((*buf = *str++) != '\0'))
- ++buf;
- return buf;
-}
-
-char* Str::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!
-char* Str::wcharPtrToCharPtr(const wchar_t* line) {
- std::size_t len_ = wcslen(line) + 1;
- char* buff_ = static_cast(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(&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_;
-}
-
-// OS
-
-#if ELPP_OS_WINDOWS
-/// @brief Gets environment variables for Windows based OS.
-/// We are not using getenv(const char*)
because of CRT deprecation
-/// @param varname Variable name to get environment variable value for
-/// @return If variable exist the value of it otherwise nullptr
-const char* OS::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
-std::string OS::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);
-}
-
-std::string OS::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
-
-const std::string OS::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);
- const std::size_t buffLen = strlen(hBuff);
- if (buffLen > 0 && hBuff[buffLen - 1] == '\n') {
- hBuff[buffLen - 1] = '\0';
- }
- return std::string(hBuff);
- } else {
- pclose(proc);
- }
- return std::string();
-#else
- ELPP_UNUSED(command);
- return std::string();
-#endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN)
-}
-
-std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal,
- const char* alternativeBashCommand) {
-#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);
-}
-
-std::string OS::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
-}
-
-std::string OS::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
-}
-
-bool OS::termSupportsColor(void) {
- std::string term = getEnvironmentVariable("TERM", "");
- return term == "xterm" || term == "xterm-color" || term == "xterm-256color"
- || term == "screen" || term == "linux" || term == "cygwin"
- || term == "screen-256color";
-}
-
-// DateTime
-
-void DateTime::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;
- 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(present * secOffSet);
- tv->tv_usec = static_cast(present % usecOffSet);
- }
-#else
- ::gettimeofday(tv, nullptr);
-#endif // ELPP_OS_WINDOWS
-}
-
-std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) {
- struct timeval currTime;
- gettimeofday(&currTime);
- return timevalToString(currTime, format, ssPrec);
-}
-
-std::string DateTime::timevalToString(struct timeval tval, const char* format,
- const el::base::SubsecondPrecision* ssPrec) {
- struct ::tm timeInfo;
- buildTimeInfo(&tval, &timeInfo);
- const int kBuffSize = 30;
- char buff_[kBuffSize] = "";
- parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast(tval.tv_usec / ssPrec->m_offset),
- ssPrec);
- return std::string(buff_);
-}
-
-base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) {
- base::type::EnumType start = static_cast(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 (time <= base::consts::kTimeFormats[i].value) {
- break;
- }
- if (base::consts::kTimeFormats[i].value == 1000.0f && time / 1000.0f < 1.9f) {
- break;
- }
- time /= static_cast(base::consts::kTimeFormats[i].value);
- unit = base::consts::kTimeFormats[i + 1].unit;
- }
- base::type::stringstream_t ss;
- ss << time << " " << unit;
- return ss.str();
-}
-
-unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
- base::TimestampUnit timestampUnit) {
- if (timestampUnit == base::TimestampUnit::Microsecond) {
- return static_cast(static_cast(1000000 * endTime.tv_sec + endTime.tv_usec) -
- static_cast(1000000 * startTime.tv_sec + startTime.tv_usec));
- }
- // milliseconds
- auto conv = [](const struct timeval& tim) {
- return static_cast((tim.tv_sec * 1000) + (tim.tv_usec / 1000));
- };
- return static_cast(conv(endTime) - conv(startTime));
-}
-
-struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) {
-#if ELPP_OS_UNIX
- time_t rawTime = currTime->tv_sec;
- ::elpptime_r(&rawTime, timeInfo);
- return timeInfo;
-#else
-# if ELPP_COMPILER_MSVC
- ELPP_UNUSED(currTime);
- time_t t;
-# if defined(_USE_32BIT_TIME_T)
- _time32(&t);
-# else
- _time64(&t);
-# endif
- elpptime_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;
- struct tm* tmInf = elpptime(&rawTime);
- *timeInfo = *tmInf;
- return timeInfo;
-# endif // ELPP_COMPILER_MSVC
-#endif // ELPP_OS_UNIX
-}
-
-char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
- std::size_t msec, const base::SubsecondPrecision* ssPrec) {
- 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': // subsecond part
- case 'g':
- buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->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;
-}
-
-// CommandLineArgs
-
-void CommandLineArgs::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]));
- }
- }
- }
-}
-
-bool CommandLineArgs::hasParamWithValue(const char* paramKey) const {
- return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end();
-}
-
-const char* CommandLineArgs::getParamValue(const char* paramKey) const {
- std::unordered_map::const_iterator iter = m_paramsWithValue.find(std::string(paramKey));
- return iter != m_paramsWithValue.end() ? iter->second.c_str() : "";
-}
-
-bool CommandLineArgs::hasParam(const char* paramKey) const {
- return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end();
-}
-
-bool CommandLineArgs::empty(void) const {
- return m_params.empty() && m_paramsWithValue.empty();
-}
-
-std::size_t CommandLineArgs::size(void) const {
- return m_params.size() + m_paramsWithValue.size();
-}
-
-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;
-}
-
-} // namespace utils
-
-// el::base::threading
-namespace threading {
-
-#if ELPP_THREADING_ENABLED
-# if ELPP_USE_STD_THREADING
-# if ELPP_ASYNC_LOGGING
-static void msleep(int ms) {
- // Only when async logging enabled - this is because async is strict on compiler
-# if defined(ELPP_NO_SLEEP_FOR)
- usleep(ms * 1000);
-# else
- std::this_thread::sleep_for(std::chrono::milliseconds(ms));
-# endif // defined(ELPP_NO_SLEEP_FOR)
-}
-# endif // ELPP_ASYNC_LOGGING
-# endif // !ELPP_USE_STD_THREADING
-#endif // ELPP_THREADING_ENABLED
-
-} // namespace threading
-
-// el::base
-
-// SubsecondPrecision
-
-void SubsecondPrecision::init(int width) {
- if (width < 1 || width > 6) {
- width = base::consts::kDefaultSubsecondPrecision;
- }
- m_width = width;
- switch (m_width) {
- case 3:
- m_offset = 1000;
- break;
- case 4:
- m_offset = 100;
- break;
- case 5:
- m_offset = 10;
- break;
- case 6:
- m_offset = 1;
- break;
- default:
- m_offset = 1000;
- break;
- }
-}
-
-// LogFormat
-
-LogFormat::LogFormat(void) :
- m_level(Level::Unknown),
- m_userFormat(base::type::string_t()),
- m_format(base::type::string_t()),
- m_dateTimeFormat(std::string()),
- m_flags(0x0),
- m_currentUser(base::utils::OS::currentUser()),
- m_currentHost(base::utils::OS::currentHost()) {
-}
-
-LogFormat::LogFormat(Level level, const base::type::string_t& format)
- : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()),
- m_currentHost(base::utils::OS::currentHost()) {
- parseFromFormat(m_userFormat);
-}
-
-LogFormat::LogFormat(const LogFormat& logFormat):
- m_level(logFormat.m_level),
- m_userFormat(logFormat.m_userFormat),
- m_format(logFormat.m_format),
- m_dateTimeFormat(logFormat.m_dateTimeFormat),
- m_flags(logFormat.m_flags),
- m_currentUser(logFormat.m_currentUser),
- m_currentHost(logFormat.m_currentHost) {
-}
-
-LogFormat::LogFormat(LogFormat&& logFormat) {
- m_level = std::move(logFormat.m_level);
- m_userFormat = std::move(logFormat.m_userFormat);
- m_format = std::move(logFormat.m_format);
- m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat);
- m_flags = std::move(logFormat.m_flags);
- m_currentUser = std::move(logFormat.m_currentUser);
- m_currentHost = std::move(logFormat.m_currentHost);
-}
-
-LogFormat& LogFormat::operator=(const LogFormat& logFormat) {
- if (&logFormat != this) {
- m_level = logFormat.m_level;
- m_userFormat = logFormat.m_userFormat;
- m_dateTimeFormat = logFormat.m_dateTimeFormat;
- m_flags = logFormat.m_flags;
- m_currentUser = logFormat.m_currentUser;
- m_currentHost = logFormat.m_currentHost;
- }
- return *this;
-}
-
-bool LogFormat::operator==(const LogFormat& other) {
- return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format &&
- m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags;
-}
-
-/// @brief Updates format to be used while logging.
-/// @param userFormat User provided format
-void LogFormat::parseFromFormat(const base::type::string_t& userFormat) {
- // We make copy because we will be changing the format
- // i.e, removing user provided date format from original format
- // and then storing it.
- base::type::string_t formatCopy = userFormat;
- m_flags = 0x0;
- auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) {
- std::size_t foundAt = base::type::string_t::npos;
- while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) {
- if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) {
- if (hasFlag(flag)) {
- // If we already have flag we remove the escape chars so that '%%' is turned to '%'
- // even after specifier resolution - this is because we only replaceFirst specifier
- formatCopy.erase(foundAt - 1, 1);
- ++foundAt;
- }
- } else {
- if (!hasFlag(flag)) addFlag(flag);
- }
- }
- };
- conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName);
- conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level);
- conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort);
- conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId);
- conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId);
- conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File);
- conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase);
- conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line);
- conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location);
- conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function);
- conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User);
- conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host);
- conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage);
- conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel);
- // For date/time we need to extract user's date format first
- std::size_t dateIndex = std::string::npos;
- if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) {
- while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) {
- dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1);
- }
- if (dateIndex != std::string::npos) {
- addFlag(base::FormatFlags::DateTime);
- updateDateFormat(dateIndex, formatCopy);
- }
- }
- m_format = formatCopy;
- updateFormatSpec();
-}
-
-void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) {
- if (hasFlag(base::FormatFlags::DateTime)) {
- index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier);
- }
- const base::type::char_t* ptr = currFormat.c_str() + index;
- if ((currFormat.size() > index) && (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 << static_cast(*ptr);
- }
- currFormat.erase(index, count);
- m_dateTimeFormat = ss.str();
- } else {
- // No format provided, use default
- if (hasFlag(base::FormatFlags::DateTime)) {
- m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat);
- }
- }
-}
-
-void LogFormat::updateFormatSpec(void) {
- // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet.
- if (m_level == Level::Debug) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kDebugLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kDebugLevelShortLogValue);
- } else if (m_level == Level::Info) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kInfoLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kInfoLevelShortLogValue);
- } else if (m_level == Level::Warning) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kWarningLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kWarningLevelShortLogValue);
- } else if (m_level == Level::Error) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kErrorLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kErrorLevelShortLogValue);
- } else if (m_level == Level::Fatal) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kFatalLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kFatalLevelShortLogValue);
- } else if (m_level == Level::Verbose) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kVerboseLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kVerboseLevelShortLogValue);
- } else if (m_level == Level::Trace) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier,
- base::consts::kTraceLevelLogValue);
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier,
- base::consts::kTraceLevelShortLogValue);
- }
- if (hasFlag(base::FormatFlags::User)) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier,
- m_currentUser);
- }
- if (hasFlag(base::FormatFlags::Host)) {
- base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier,
- m_currentHost);
- }
- // Ignore Level::Global and Level::Unknown
-}
-
-// TypedConfigurations
-
-TypedConfigurations::TypedConfigurations(Configurations* configurations,
- base::LogStreamsReferenceMap* logStreamsReference) {
- m_configurations = configurations;
- m_logStreamsReference = logStreamsReference;
- build(m_configurations);
-}
-
-TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) {
- this->m_configurations = other.m_configurations;
- this->m_logStreamsReference = other.m_logStreamsReference;
- build(m_configurations);
-}
-
-bool TypedConfigurations::enabled(Level level) {
- return getConfigByVal(level, &m_enabledMap, "enabled");
-}
-
-bool TypedConfigurations::toFile(Level level) {
- return getConfigByVal(level, &m_toFileMap, "toFile");
-}
-
-const std::string& TypedConfigurations::filename(Level level) {
- return getConfigByRef(level, &m_filenameMap, "filename");
-}
-
-bool TypedConfigurations::toStandardOutput(Level level) {
- return getConfigByVal(level, &m_toStandardOutputMap, "toStandardOutput");
-}
-
-const base::LogFormat& TypedConfigurations::logFormat(Level level) {
- return getConfigByRef(level, &m_logFormatMap, "logFormat");
-}
-
-const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) {
- return getConfigByRef(level, &m_subsecondPrecisionMap, "subsecondPrecision");
-}
-
-const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) {
- return getConfigByRef(level, &m_subsecondPrecisionMap, "millisecondsWidth");
-}
-
-bool TypedConfigurations::performanceTracking(Level level) {
- return getConfigByVal(level, &m_performanceTrackingMap, "performanceTracking");
-}
-
-base::type::fstream_t* TypedConfigurations::fileStream(Level level) {
- return getConfigByRef(level, &m_fileStreamMap, "fileStream").get();
-}
-
-std::size_t TypedConfigurations::maxLogFileSize(Level level) {
- return getConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize");
-}
-
-std::size_t TypedConfigurations::logFlushThreshold(Level level) {
- return getConfigByVal(level, &m_logFlushThresholdMap, "logFlushThreshold");
-}
-
-void TypedConfigurations::build(Configurations* configurations) {
- base::threading::ScopedLock scopedLock(lock());
- auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming
- base::utils::Str::trim(boolStr);
- return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1");
- };
- std::vector withFileSizeLimit;
- for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) {
- Configuration* conf = *it;
- // We cannot use switch on strong enums because Intel C++ dont support them yet
- if (conf->configurationType() == ConfigurationType::Enabled) {
- setValue(conf->level(), getBool(conf->value()), &m_enabledMap);
- } else if (conf->configurationType() == ConfigurationType::ToFile) {
- setValue(conf->level(), getBool(conf->value()), &m_toFileMap);
- } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) {
- setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap);
- } else if (conf->configurationType() == ConfigurationType::Filename) {
- // We do not yet configure filename but we will configure in another
- // loop. This is because if file cannot be created, we will force ToFile
- // to be false. Because configuring logger is not necessarily performance
- // sensative operation, we can live with another loop; (by the way this loop
- // is not very heavy either)
- } else if (conf->configurationType() == ConfigurationType::Format) {
- setValue(conf->level(), base::LogFormat(conf->level(),
- base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap);
- } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) {
- setValue(Level::Global,
- base::SubsecondPrecision(static_cast(getULong(conf->value()))), &m_subsecondPrecisionMap);
- } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) {
- setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap);
- } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) {
- auto v = getULong(conf->value());
- setValue(conf->level(), static_cast(v), &m_maxLogFileSizeMap);
- if (v != 0) {
- withFileSizeLimit.push_back(conf);
- }
- } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) {
- setValue(conf->level(), static_cast(getULong(conf->value())), &m_logFlushThresholdMap);
- }
- }
- // As mentioned earlier, 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::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 TypedConfigurations::getULong(std::string confVal) {
- 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 TypedConfigurations::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::SubsecondPrecision ssPrec(3);
- std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec);
- base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename
- base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now);
- }
- }
- return resultingFilename;
-}
-
-void TypedConfigurations::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);
- }
- };
- // 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 TypedConfigurations::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;
-}
-
-// RegisteredHitCounters
-
-bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
- 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 RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
- 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 RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) {
- 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;
-}
-
-// RegisteredLoggers
-
-RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) :
- m_defaultLogBuilder(defaultLogBuilder) {
- m_defaultConfigurations.setToDefault();
-}
-
-Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) {
- base::threading::ScopedLock scopedLock(lock());
- Logger* logger_ = base::utils::Registry::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_);
- LoggerRegistrationCallback* callback = nullptr;
- for (const std::pair& h
- : m_loggerRegistrationCallbacks) {
- callback = h.second.get();
- if (callback != nullptr && callback->enabled()) {
- callback->handle(logger_);
- }
- }
- }
- return logger_;
-}
-
-bool RegisteredLoggers::remove(const std::string& id) {
- if (id == base::consts::kDefaultLoggerId) {
- return false;
- }
- // get has internal lock
- Logger* logger = base::utils::Registry::get(id);
- if (logger != nullptr) {
- // unregister has internal lock
- unregister(logger);
- }
- return true;
-}
-
-void RegisteredLoggers::unsafeFlushAll(void) {
- ELPP_INTERNAL_INFO(1, "Flushing all log files");
- for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin();
- it != m_logStreamsReference.end(); ++it) {
- if (it->second.get() == nullptr) continue;
- it->second->flush();
- }
-}
-
-// VRegistry
-
-VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) {
-}
-
-/// @brief Sets verbose level. Accepted range is 0-9
-void VRegistry::setLevel(base::type::VerboseLevel level) {
- base::threading::ScopedLock scopedLock(lock());
- if (level > 9)
- m_level = base::consts::kMaxVerboseLevel;
- else
- m_level = level;
-}
-
-void VRegistry::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;
- };
- 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));
- };
- 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, static_cast(level));
- ss.str(std::string(""));
- level = -1;
- }
- break;
- default:
- if (isMod) {
- ss << *modules;
- } else if (isLevel) {
- if (isdigit(*modules)) {
- level = static_cast(*modules) - 48;
- }
- }
- break;
- }
- }
- if (!ss.str().empty() && level != -1) {
- insert(ss, static_cast(level));
- }
-}
-
-bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) {
- base::threading::ScopedLock scopedLock(lock());
- if (m_modules.empty() || file == nullptr) {
- return vlevel <= m_level;
- } else {
- char baseFilename[base::consts::kSourceFilenameMaxLength] = "";
- base::utils::File::buildBaseFilename(file, baseFilename);
- std::unordered_map::iterator it = m_modules.begin();
- for (; it != m_modules.end(); ++it) {
- if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) {
- return vlevel <= it->second;
- }
- }
- if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) {
- return true;
- }
- return false;
- }
-}
-
-void VRegistry::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(static_cast(atoi(commandLineArgs->getParamValue("--v"))));
- } else if (commandLineArgs->hasParamWithValue("--V")) {
- setLevel(static_cast(atoi(commandLineArgs->getParamValue("--V"))));
- } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) {
- setModules(commandLineArgs->getParamValue("-vmodule"));
- } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) {
- setModules(commandLineArgs->getParamValue("-VMODULE"));
- }
-}
-
-#if !defined(ELPP_DEFAULT_LOGGING_FLAGS)
-# define ELPP_DEFAULT_LOGGING_FLAGS 0x0
-#endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS)
-// Storage
-#if ELPP_ASYNC_LOGGING
-Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) :
-#else
-Storage::Storage(const LogBuilderPtr& defaultLogBuilder) :
-#endif // ELPP_ASYNC_LOGGING
- m_registeredHitCounters(new base::RegisteredHitCounters()),
- m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)),
- m_flags(ELPP_DEFAULT_LOGGING_FLAGS),
- m_vRegistry(new base::VRegistry(0, &m_flags)),
-
-#if ELPP_ASYNC_LOGGING
- m_asyncLogQueue(new base::AsyncLogQueue()),
- m_asyncDispatchWorker(asyncDispatchWorker),
-#endif // ELPP_ASYNC_LOGGING
-
- m_preRollOutCallback(base::defaultPreRollOutCallback) {
- // Register default logger
- m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId));
- // We register default logger anyway (worse case it's not going to register) just in case
- m_registeredLoggers->get("default");
-
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
- // Register performance logger and reconfigure format
- Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId));
- m_registeredLoggers->get("performance");
- performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg"));
- performanceLogger->reconfigure();
-#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
-
-#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();
-#endif // defined(ELPP_SYSLOG)
- addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified);
-#if ELPP_ASYNC_LOGGING
- installLogDispatchCallback(std::string("AsyncLogDispatchCallback"));
-#else
- installLogDispatchCallback(std::string("DefaultLogDispatchCallback"));
-#endif // ELPP_ASYNC_LOGGING
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
- installPerformanceTrackingCallback
- (std::string("DefaultPerformanceTrackingCallback"));
-#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
- ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized");
-#if ELPP_ASYNC_LOGGING
- m_asyncDispatchWorker->start();
-#endif // ELPP_ASYNC_LOGGING
-}
-
-Storage::~Storage(void) {
- ELPP_INTERNAL_INFO(4, "Destroying storage");
-#if ELPP_ASYNC_LOGGING
- ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous");
- uninstallLogDispatchCallback(std::string("AsyncLogDispatchCallback"));
- installLogDispatchCallback(std::string("DefaultLogDispatchCallback"));
- ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker");
- base::utils::safeDelete(m_asyncDispatchWorker);
- ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue");
- base::utils::safeDelete(m_asyncLogQueue);
-#endif // ELPP_ASYNC_LOGGING
- ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters");
- base::utils::safeDelete(m_registeredHitCounters);
- ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers");
- base::utils::safeDelete(m_registeredLoggers);
- ELPP_INTERNAL_INFO(5, "Destroying vRegistry");
- base::utils::safeDelete(m_vRegistry);
-}
-
-bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) {
- base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
- return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(),
- formatSpecifier) != m_customFormatSpecifiers.end();
-}
-
-void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) {
- if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) {
- return;
- }
- base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
- m_customFormatSpecifiers.push_back(customFormatSpecifier);
-}
-
-bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) {
- base::threading::ScopedLock scopedLock(customFormatSpecifiersLock());
- std::vector::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;
-}
-
-void Storage::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)) {
- int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam));
- if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) {
- m_flags = userInput;
- } else {
- base::utils::addFlag(userInput, &m_flags);
- }
- }
-#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG)
-}
-
-} // namespace base
-
-// LogDispatchCallback
-void LogDispatchCallback::handle(const LogDispatchData* data) {
-#if defined(ELPP_THREAD_SAFE)
- base::threading::ScopedLock scopedLock(m_fileLocksMapLock);
- std::string filename = data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level());
- auto lock = m_fileLocks.find(filename);
- if (lock == m_fileLocks.end()) {
- m_fileLocks.emplace(std::make_pair(filename, std::unique_ptr(new base::threading::Mutex)));
- }
-#endif
-}
-
-base::threading::Mutex& LogDispatchCallback::fileHandle(const LogDispatchData* data) {
- auto it = m_fileLocks.find(data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level()));
- return *(it->second.get());
-}
-
-namespace base {
-// DefaultLogDispatchCallback
-
-void DefaultLogDispatchCallback::handle(const LogDispatchData* data) {
-#if defined(ELPP_THREAD_SAFE)
- LogDispatchCallback::handle(data);
- base::threading::ScopedLock scopedLock(fileHandle(data));
-#endif
- m_data = data;
- dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
- m_data->dispatchAction() == base::DispatchAction::NormalLog));
-}
-
-void DefaultLogDispatchCallback::dispatch(base::type::string_t&& logLine) {
- if (m_data->dispatchAction() == base::DispatchAction::NormalLog) {
- if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) {
- base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream(
- m_data->logMessage()->level());
- if (fs != nullptr) {
- fs->write(logLine.c_str(), logLine.size());
- if (fs->fail()) {
- ELPP_INTERNAL_ERROR("Unable to write log to file ["
- << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n"
- << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
- << " * Disk full\n" << " * Disk is not writable", true);
- } else {
- if (ELPP->hasFlag(LoggingFlag::ImmediateFlush)
- || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) {
- m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs);
- }
- }
- } else {
- ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] "
- << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: "
- << m_data->logMessage()->logger()->id() << "]", false);
- }
- }
- if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) {
- if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
- m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, m_data->logMessage()->level());
- ELPP_COUT << ELPP_COUT_LINE(logLine);
- }
- }
-#if defined(ELPP_SYSLOG)
- else if (m_data->dispatchAction() == base::DispatchAction::SysLog) {
- // Determine syslog priority
- int sysLogPriority = 0;
- if (m_data->logMessage()->level() == Level::Fatal)
- sysLogPriority = LOG_EMERG;
- else if (m_data->logMessage()->level() == Level::Error)
- sysLogPriority = LOG_ERR;
- else if (m_data->logMessage()->level() == Level::Warning)
- sysLogPriority = LOG_WARNING;
- else if (m_data->logMessage()->level() == Level::Info)
- sysLogPriority = LOG_INFO;
- else if (m_data->logMessage()->level() == Level::Debug)
- sysLogPriority = LOG_DEBUG;
- else
- sysLogPriority = LOG_NOTICE;
-# if defined(ELPP_UNICODE)
- char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
- syslog(sysLogPriority, "%s", line);
- free(line);
-# else
- syslog(sysLogPriority, "%s", logLine.c_str());
-# endif
- }
-#endif // defined(ELPP_SYSLOG)
-}
-
-#if ELPP_ASYNC_LOGGING
-
-// AsyncLogDispatchCallback
-
-void AsyncLogDispatchCallback::handle(const LogDispatchData* data) {
- base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(),
- data->dispatchAction() == base::DispatchAction::NormalLog);
- if (data->dispatchAction() == base::DispatchAction::NormalLog
- && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) {
- if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput))
- data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level());
- ELPP_COUT << ELPP_COUT_LINE(logLine);
- }
- // Save resources and only queue if we want to write to file otherwise just ignore handler
- if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) {
- ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine));
- }
-}
-
-// AsyncDispatchWorker
-AsyncDispatchWorker::AsyncDispatchWorker() {
- setContinueRunning(false);
-}
-
-AsyncDispatchWorker::~AsyncDispatchWorker() {
- setContinueRunning(false);
- ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue");
- clean();
- ELPP_INTERNAL_INFO(6, "Log queue cleaned");
-}
-
-bool AsyncDispatchWorker::clean(void) {
- std::mutex m;
- std::unique_lock lk(m);
- cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); });
- emptyQueue();
- lk.unlock();
- cv.notify_one();
- return ELPP->asyncLogQueue()->empty();
-}
-
-void AsyncDispatchWorker::emptyQueue(void) {
- while (!ELPP->asyncLogQueue()->empty()) {
- AsyncLogItem data = ELPP->asyncLogQueue()->next();
- handle(&data);
- base::threading::msleep(100);
- }
-}
-
-void AsyncDispatchWorker::start(void) {
- base::threading::msleep(5000); // 5s (why?)
- setContinueRunning(true);
- std::thread t1(&AsyncDispatchWorker::run, this);
- t1.join();
-}
-
-void AsyncDispatchWorker::handle(AsyncLogItem* logItem) {
- LogDispatchData* data = logItem->data();
- LogMessage* logMessage = logItem->logMessage();
- Logger* logger = logMessage->logger();
- base::TypedConfigurations* conf = logger->typedConfigurations();
- base::type::string_t logLine = logItem->logLine();
- if (data->dispatchAction() == base::DispatchAction::NormalLog) {
- if (conf->toFile(logMessage->level())) {
- base::type::fstream_t* fs = conf->fileStream(logMessage->level());
- if (fs != nullptr) {
- fs->write(logLine.c_str(), logLine.size());
- if (fs->fail()) {
- ELPP_INTERNAL_ERROR("Unable to write log to file ["
- << conf->filename(logMessage->level()) << "].\n"
- << "Few possible reasons (could be something else):\n" << " * Permission denied\n"
- << " * Disk full\n" << " * Disk is not writable", true);
- } else {
- if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) {
- logger->flush(logMessage->level(), fs);
- }
- }
- } else {
- ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] "
- << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false);
- }
- }
- }
-# if defined(ELPP_SYSLOG)
- else if (data->dispatchAction() == base::DispatchAction::SysLog) {
- // Determine syslog priority
- int sysLogPriority = 0;
- if (logMessage->level() == Level::Fatal)
- sysLogPriority = LOG_EMERG;
- else if (logMessage->level() == Level::Error)
- sysLogPriority = LOG_ERR;
- else if (logMessage->level() == Level::Warning)
- sysLogPriority = LOG_WARNING;
- else if (logMessage->level() == Level::Info)
- sysLogPriority = LOG_INFO;
- else if (logMessage->level() == Level::Debug)
- sysLogPriority = LOG_DEBUG;
- else
- sysLogPriority = LOG_NOTICE;
-# if defined(ELPP_UNICODE)
- char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str());
- syslog(sysLogPriority, "%s", line);
- free(line);
-# else
- syslog(sysLogPriority, "%s", logLine.c_str());
-# endif
- }
-# endif // defined(ELPP_SYSLOG)
-}
-
-void AsyncDispatchWorker::run(void) {
- while (continueRunning()) {
- emptyQueue();
- base::threading::msleep(10); // 10ms
- }
-}
-#endif // ELPP_ASYNC_LOGGING
-
-// DefaultLogBuilder
-
-base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const {
- base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations();
- const base::LogFormat* logFormat = &tc->logFormat(logMessage->level());
- base::type::string_t logLine = logFormat->format();
- char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = "";
- const char* bufLim = buff + sizeof(buff);
- if (logFormat->hasFlag(base::FormatFlags::AppName)) {
- // App name
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier,
- logMessage->logger()->parentApplicationName());
- }
- if (logFormat->hasFlag(base::FormatFlags::ThreadId)) {
- // Thread ID
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier,
- ELPP->getThreadName(base::threading::getCurrentThreadId()));
- }
- if (logFormat->hasFlag(base::FormatFlags::DateTime)) {
- // DateTime
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier,
- base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(),
- &tc->subsecondPrecision(logMessage->level())));
- }
- if (logFormat->hasFlag(base::FormatFlags::Function)) {
- // Function
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func());
- }
- if (logFormat->hasFlag(base::FormatFlags::File)) {
- // File
- base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
- base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff);
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff));
- }
- if (logFormat->hasFlag(base::FormatFlags::FileBase)) {
- // FileBase
- base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength);
- base::utils::File::buildBaseFilename(logMessage->file(), buff);
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff));
- }
- if (logFormat->hasFlag(base::FormatFlags::Line)) {
- // Line
- char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength);
- buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false);
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff));
- }
- if (logFormat->hasFlag(base::FormatFlags::Location)) {
- // Location
- char* buf = base::utils::Str::clearBuff(buff,
- base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength);
- base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff);
- buf = base::utils::Str::addToBuff(buff, buf, bufLim);
- buf = base::utils::Str::addToBuff(":", buf, bufLim);
- buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim,
- false);
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff));
- }
- if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) {
- // Verbose level
- char* buf = base::utils::Str::clearBuff(buff, 1);
- buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false);
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff));
- }
- if (logFormat->hasFlag(base::FormatFlags::LogMessage)) {
- // Log message
- base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message());
- }
-#if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
- el::base::threading::ScopedLock lock_(ELPP->customFormatSpecifiersLock());
- ELPP_UNUSED(lock_);
- for (std::vector::const_iterator it = ELPP->customFormatSpecifiers()->begin();
- it != ELPP->customFormatSpecifiers()->end(); ++it) {
- std::string fs(it->formatSpecifier());
- base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end());
- base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage));
- }
-#endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS)
- if (appendNewLine) logLine += ELPP_LITERAL("\n");
- return logLine;
-}
-
-// LogDispatcher
-
-void LogDispatcher::dispatch(void) {
- if (m_proceed && m_dispatchAction == base::DispatchAction::None) {
- m_proceed = false;
- }
- if (!m_proceed) {
- return;
- }
-#ifndef ELPP_NO_GLOBAL_LOCK
- // see https://github.com/muflihun/easyloggingpp/issues/580
- // global lock is turned off by default unless
- // ELPP_NO_GLOBAL_LOCK is defined
- base::threading::ScopedLock scopedLock(ELPP->lock());
-#endif
- base::TypedConfigurations* tc = m_logMessage->logger()->m_typedConfigurations;
- if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) {
- tc->validateFileRolling(m_logMessage->level(), ELPP->preRollOutCallback());
- }
- LogDispatchCallback* callback = nullptr;
- LogDispatchData data;
- for (const std::pair& h
- : ELPP->m_logDispatchCallbacks) {
- callback = h.second.get();
- if (callback != nullptr && callback->enabled()) {
- data.setLogMessage(m_logMessage);
- data.setDispatchAction(m_dispatchAction);
- callback->handle(&data);
- }
- }
-}
-
-// MessageBuilder
-
-void MessageBuilder::initialize(Logger* logger) {
- m_logger = logger;
- m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ?
- ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");
-}
-
-MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) {
- if (msg == nullptr) {
- m_logger->stream() << base::consts::kNullPointer;
- return *this;
- }
-# if defined(ELPP_UNICODE)
- m_logger->stream() << msg;
-# else
- char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg);
- m_logger->stream() << buff_;
- free(buff_);
-# endif
- if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {
- m_logger->stream() << " ";
- }
- return *this;
-}
-
-// Writer
-
-Writer& Writer::construct(Logger* logger, bool needLock) {
- m_logger = logger;
- initializeLogger(logger->id(), false, needLock);
- m_messageBuilder.initialize(m_logger);
- return *this;
-}
-
-Writer& Writer::construct(int count, const char* loggerIds, ...) {
- if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
- va_list loggersList;
- va_start(loggersList, loggerIds);
- const char* id = loggerIds;
- m_loggerIds.reserve(count);
- for (int i = 0; i < count; ++i) {
- m_loggerIds.push_back(std::string(id));
- id = va_arg(loggersList, const char*);
- }
- va_end(loggersList);
- initializeLogger(m_loggerIds.at(0));
- } else {
- initializeLogger(std::string(loggerIds));
- }
- m_messageBuilder.initialize(m_logger);
- return *this;
-}
-
-void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) {
- if (lookup) {
- m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically));
- }
- if (m_logger == nullptr) {
- {
- if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) {
- // Somehow default logger has been unregistered. Not good! Register again
- ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId));
- }
- }
- Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
- << "Logger [" << loggerId << "] is not registered yet!";
- m_proceed = false;
- } else {
- if (needLock) {
- m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because
- // m_proceed can be changed by lines below
- }
- if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) {
- m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) :
- LevelHelper::castToInt(m_level) >= LevelHelper::castToInt(ELPP->m_loggingLevel);
- } else {
- m_proceed = m_logger->enabled(m_level);
- }
- }
-}
-
-void Writer::processDispatch() {
-#if ELPP_LOGGING_ENABLED
- if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) {
- bool firstDispatched = false;
- base::type::string_t logMessage;
- std::size_t i = 0;
- do {
- if (m_proceed) {
- if (firstDispatched) {
- m_logger->stream() << logMessage;
- } else {
- firstDispatched = true;
- if (m_loggerIds.size() > 1) {
- logMessage = m_logger->stream().str();
- }
- }
- triggerDispatch();
- } else if (m_logger != nullptr) {
- m_logger->stream().str(ELPP_LITERAL(""));
- m_logger->releaseLock();
- }
- if (i + 1 < m_loggerIds.size()) {
- initializeLogger(m_loggerIds.at(i + 1));
- }
- } while (++i < m_loggerIds.size());
- } else {
- if (m_proceed) {
- triggerDispatch();
- } else if (m_logger != nullptr) {
- m_logger->stream().str(ELPP_LITERAL(""));
- m_logger->releaseLock();
- }
- }
-#else
- if (m_logger != nullptr) {
- m_logger->stream().str(ELPP_LITERAL(""));
- m_logger->releaseLock();
- }
-#endif // ELPP_LOGGING_ENABLED
-}
-
-void Writer::triggerDispatch(void) {
- if (m_proceed) {
- if (m_msg == nullptr) {
- LogMessage msg(m_level, m_file, m_line, m_func, m_verboseLevel,
- m_logger);
- base::LogDispatcher(m_proceed, &msg, m_dispatchAction).dispatch();
- } else {
- base::LogDispatcher(m_proceed, m_msg, m_dispatchAction).dispatch();
- }
- }
- if (m_logger != nullptr) {
- m_logger->stream().str(ELPP_LITERAL(""));
- m_logger->releaseLock();
- }
- if (m_proceed && m_level == Level::Fatal
- && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) {
- base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId)
- << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]";
- std::stringstream reasonStream;
- reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]"
- << " If you wish to disable 'abort on fatal log' please use "
- << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)";
- base::utils::abort(1, reasonStream.str());
- }
- m_proceed = false;
-}
-
-// PErrorWriter
-
-PErrorWriter::~PErrorWriter(void) {
- if (m_proceed) {
-#if ELPP_COMPILER_MSVC
- char buff[256];
- strerror_s(buff, 256, errno);
- m_logger->stream() << ": " << buff << " [" << errno << "]";
-#else
- m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]";
-#endif
- }
-}
-
-// PerformanceTracker
-
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
-
-PerformanceTracker::PerformanceTracker(const std::string& blockName,
- base::TimestampUnit timestampUnit,
- const std::string& loggerId,
- bool scopedLog, Level level) :
- m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog),
- m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) {
-#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
- // We store it locally so that if user happen to change configuration by the end of scope
- // or before calling checkpoint, we still depend on state of configuraton at time of construction
- el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false);
- m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level);
- if (m_enabled) {
- base::utils::DateTime::gettimeofday(&m_startTime);
- }
-#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
-}
-
-PerformanceTracker::~PerformanceTracker(void) {
-#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
- if (m_enabled) {
- base::threading::ScopedLock scopedLock(lock());
- if (m_scopedLog) {
- base::utils::DateTime::gettimeofday(&m_endTime);
- base::type::string_t formattedTime = getFormattedTimeTaken();
- PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete);
- data.init(this);
- data.m_formattedTimeTaken = formattedTime;
- PerformanceTrackingCallback* callback = nullptr;
- for (const std::pair& h
- : ELPP->m_performanceTrackingCallbacks) {
- callback = h.second.get();
- if (callback != nullptr && callback->enabled()) {
- callback->handle(&data);
- }
- }
- }
- }
-#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING)
-}
-
-void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line,
- const char* func) {
-#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
- if (m_enabled) {
- base::threading::ScopedLock scopedLock(lock());
- base::utils::DateTime::gettimeofday(&m_endTime);
- base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL("");
- PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint);
- data.init(this);
- data.m_checkpointId = id;
- data.m_file = file;
- data.m_line = line;
- data.m_func = func;
- data.m_formattedTimeTaken = formattedTime;
- PerformanceTrackingCallback* callback = nullptr;
- for (const std::pair& h
- : ELPP->m_performanceTrackingCallbacks) {
- callback = h.second.get();
- if (callback != nullptr && callback->enabled()) {
- callback->handle(&data);
- }
- }
- base::utils::DateTime::gettimeofday(&m_lastCheckpointTime);
- m_hasChecked = true;
- m_lastCheckpointId = id;
- }
-#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED
- ELPP_UNUSED(id);
- ELPP_UNUSED(file);
- ELPP_UNUSED(line);
- ELPP_UNUSED(func);
-}
-
-const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const {
- if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) {
- base::type::stringstream_t ss;
- ss << base::utils::DateTime::getTimeDifference(m_endTime,
- startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast
- (m_timestampUnit)].unit;
- return ss.str();
- }
- return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime,
- startTime, m_timestampUnit), m_timestampUnit);
-}
-
-#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
-
-namespace debug {
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
-
-// StackTrace
-
-StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang,
- const std::string& hex,
- const std::string& addr) :
- m_index(index),
- m_location(loc),
- m_demangled(demang),
- m_hex(hex),
- m_addr(addr) {
-}
-
-std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) {
- ss << "[" << si.m_index << "] " << si.m_location << (si.m_hex.empty() ? "" : "+") << si.m_hex << " " << si.m_addr <<
- (si.m_demangled.empty() ? "" : ":") << si.m_demangled;
- return ss;
-}
-
-std::ostream& operator<<(std::ostream& os, const StackTrace& st) {
- std::vector::const_iterator it = st.m_stack.begin();
- while (it != st.m_stack.end()) {
- os << " " << *it++ << "\n";
- }
- return os;
-}
-
-void StackTrace::generateNew(void) {
-#if ELPP_STACKTRACE
- m_stack.clear();
- void* stack[kMaxStack];
- unsigned int size = backtrace(stack, kMaxStack);
- char** strings = backtrace_symbols(stack, size);
- if (size > kStackStart) { // Skip StackTrace c'tor and generateNew
- for (std::size_t i = kStackStart; i < size; ++i) {
- std::string mangName;
- std::string location;
- std::string hex;
- std::string addr;
-
- // entry: 2 crash.cpp.bin 0x0000000101552be5 _ZN2el4base5debug10StackTraceC1Ev + 21
- const std::string line(strings[i]);
- auto p = line.find("_");
- if (p != std::string::npos) {
- mangName = line.substr(p);
- mangName = mangName.substr(0, mangName.find(" +"));
- }
- p = line.find("0x");
- if (p != std::string::npos) {
- addr = line.substr(p);
- addr = addr.substr(0, addr.find("_"));
- }
- // Perform demangling if parsed properly
- if (!mangName.empty()) {
- int status = 0;
- char* demangName = abi::__cxa_demangle(mangName.data(), 0, 0, &status);
- // if demangling is successful, output the demangled function name
- if (status == 0) {
- // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html)
- StackTraceEntry entry(i - 1, location, demangName, hex, addr);
- m_stack.push_back(entry);
- } else {
- // Not successful - we will use mangled name
- StackTraceEntry entry(i - 1, location, mangName, hex, addr);
- m_stack.push_back(entry);
- }
- free(demangName);
- } else {
- StackTraceEntry entry(i - 1, line);
- m_stack.push_back(entry);
- }
- }
- }
- free(strings);
-#else
- ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler");
-#endif // ELPP_STACKTRACE
-}
-
-// Static helper functions
-
-static std::string crashReason(int sig) {
- std::stringstream ss;
- bool foundReason = false;
- for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) {
- if (base::consts::kCrashSignals[i].numb == sig) {
- ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal";
- if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) {
- ss << std::endl <<
- " " << base::consts::kCrashSignals[i].brief << std::endl <<
- " " << base::consts::kCrashSignals[i].detail;
- }
- foundReason = true;
- }
- }
- if (!foundReason) {
- ss << "Application has crashed due to unknown signal [" << sig << "]";
- }
- return ss.str();
-}
-/// @brief Logs reason of crash from sig
-static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
- if (sig == SIGINT && ELPP->hasFlag(el::LoggingFlag::IgnoreSigInt)) {
- return;
- }
- std::stringstream ss;
- ss << "CRASH HANDLED; ";
- ss << crashReason(sig);
-#if ELPP_STACKTRACE
- if (stackTraceIfAvailable) {
- ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace();
- }
-#else
- ELPP_UNUSED(stackTraceIfAvailable);
-#endif // ELPP_STACKTRACE
- ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str();
-}
-
-static inline void crashAbort(int sig) {
- base::utils::abort(sig, std::string());
-}
-
-/// @brief Default application crash handler
-///
-/// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program.
-static inline void defaultCrashHandler(int sig) {
- base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId);
- base::debug::crashAbort(sig);
-}
-
-// CrashHandler
-
-CrashHandler::CrashHandler(bool useDefault) {
- if (useDefault) {
- setHandler(defaultCrashHandler);
- }
-}
-
-void CrashHandler::setHandler(const Handler& cHandler) {
- m_handler = cHandler;
-#if defined(ELPP_HANDLE_SIGABRT)
- int i = 0; // SIGABRT is at base::consts::kCrashSignals[0]
-#else
- int i = 1;
-#endif // defined(ELPP_HANDLE_SIGABRT)
- for (; i < base::consts::kCrashSignalsCount; ++i) {
- m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler);
- }
-}
-
-#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
-} // namespace debug
-} // namespace base
-
-// el
-
-// Helpers
-
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
-
-void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) {
- std::stringstream ss;
- ss << base::debug::crashReason(sig).c_str();
- ss << " - [Called el::Helpers::crashAbort(" << sig << ")]";
- if (sourceFile != nullptr && strlen(sourceFile) > 0) {
- ss << " - Source: " << sourceFile;
- if (line > 0)
- ss << ":" << line;
- else
- ss << " (line number not specified)";
- }
- base::utils::abort(sig, ss.str());
-}
-
-void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) {
- el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger);
-}
-
-#endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG)
-
-// Loggers
-
-Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) {
- return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable);
-}
-
-void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) {
- ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr);
-}
-
-bool Loggers::unregisterLogger(const std::string& identity) {
- return ELPP->registeredLoggers()->remove(identity);
-}
-
-bool Loggers::hasLogger(const std::string& identity) {
- return ELPP->registeredLoggers()->has(identity);
-}
-
-Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) {
- if (!logger) return nullptr;
- logger->configure(configurations);
- return logger;
-}
-
-Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) {
- return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations);
-}
-
-Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType,
- const std::string& value) {
- Logger* logger = Loggers::getLogger(identity);
- if (logger == nullptr) {
- return nullptr;
- }
- logger->configurations()->set(Level::Global, configurationType, value);
- logger->reconfigure();
- return logger;
-}
-
-void Loggers::reconfigureAllLoggers(const Configurations& configurations) {
- for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
- it != ELPP->registeredLoggers()->end(); ++it) {
- Loggers::reconfigureLogger(it->second, configurations);
- }
-}
-
-void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType,
- const std::string& value) {
- for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin();
- it != ELPP->registeredLoggers()->end(); ++it) {
- Logger* logger = it->second;
- logger->configurations()->set(level, configurationType, value);
- logger->reconfigure();
- }
-}
-
-void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) {
- ELPP->registeredLoggers()->setDefaultConfigurations(configurations);
- if (reconfigureExistingLoggers) {
- Loggers::reconfigureAllLoggers(configurations);
- }
-}
-
-const Configurations* Loggers::defaultConfigurations(void) {
- return ELPP->registeredLoggers()->defaultConfigurations();
-}
-
-const base::LogStreamsReferenceMap* Loggers::logStreamsReference(void) {
- return ELPP->registeredLoggers()->logStreamsReference();
-}
-
-base::TypedConfigurations Loggers::defaultTypedConfigurations(void) {
- return base::TypedConfigurations(
- ELPP->registeredLoggers()->defaultConfigurations(),
- ELPP->registeredLoggers()->logStreamsReference());
-}
-
-std::vector* Loggers::populateAllLoggerIds(std::vector* targetList) {
- targetList->clear();
- for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin();
- it != ELPP->registeredLoggers()->list().end(); ++it) {
- targetList->push_back(it->first);
- }
- return targetList;
-}
-
-void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) {
- std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in);
- ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath
- << "] for parsing.");
- std::string line = std::string();
- std::stringstream ss;
- Logger* logger = nullptr;
- auto configure = [&](void) {
- ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str()
- << "\n--------------");
- Configurations c;
- c.parseFromText(ss.str());
- logger->configure(c);
- };
- while (gcfStream.good()) {
- std::getline(gcfStream, line);
- ELPP_INTERNAL_INFO(1, "Parsing line: " << line);
- base::utils::Str::trim(line);
- if (Configurations::Parser::isComment(line)) continue;
- Configurations::Parser::ignoreComments(&line);
- base::utils::Str::trim(line);
- if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) {
- if (!ss.str().empty() && logger != nullptr) {
- configure();
- }
- ss.str(std::string(""));
- line = line.substr(2);
- base::utils::Str::trim(line);
- if (line.size() > 1) {
- ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'");
- logger = getLogger(line);
- }
- } else {
- ss << line << "\n";
- }
- }
- if (!ss.str().empty() && logger != nullptr) {
- configure();
- }
-}
-
-bool Loggers::configureFromArg(const char* argKey) {
-#if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
- ELPP_UNUSED(argKey);
-#else
- if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) {
- return false;
- }
- configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey));
-#endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS)
- return true;
-}
-
-void Loggers::flushAll(void) {
- ELPP->registeredLoggers()->flushAll();
-}
-
-void Loggers::setVerboseLevel(base::type::VerboseLevel level) {
- ELPP->vRegistry()->setLevel(level);
-}
-
-base::type::VerboseLevel Loggers::verboseLevel(void) {
- return ELPP->vRegistry()->level();
-}
-
-void Loggers::setVModules(const char* modules) {
- if (ELPP->vRegistry()->vModulesEnabled()) {
- ELPP->vRegistry()->setModules(modules);
- }
-}
-
-void Loggers::clearVModules(void) {
- ELPP->vRegistry()->clearModules();
-}
-
-// VersionInfo
-
-const std::string VersionInfo::version(void) {
- return std::string("9.96.7");
-}
-/// @brief Release date of current version
-const std::string VersionInfo::releaseDate(void) {
- return std::string("24-11-2018 0728hrs");
-}
-
-} // namespace el
diff --git a/3rdparty/easyloggingpp/src/easylogging++.h b/3rdparty/easyloggingpp/src/easylogging++.h
deleted file mode 100644
index 688d537..0000000
--- a/3rdparty/easyloggingpp/src/easylogging++.h
+++ /dev/null
@@ -1,4569 +0,0 @@
-//
-// Bismillah ar-Rahmaan ar-Raheem
-//
-// Easylogging++ v9.96.7
-// Single-header only, cross-platform logging library for C++ applications
-//
-// Copyright (c) 2012-2018 Zuhd Web Services
-// Copyright (c) 2012-2018 @abumusamq
-//
-// This library is released under the MIT Licence.
-// https://github.com/zuhd-org/easyloggingpp/blob/master/LICENSE
-//
-// https://zuhd.org
-// http://muflihun.com
-//
-
-#ifndef EASYLOGGINGPP_H
-#define EASYLOGGINGPP_H
-// Compilers and C++0x/C++11 Evaluation
-#if __cplusplus >= 201103L
-# define ELPP_CXX11 1
-#endif // __cplusplus >= 201103L
-#if (defined(__GNUC__))
-# define ELPP_COMPILER_GCC 1
-#else
-# define ELPP_COMPILER_GCC 0
-#endif
-#if ELPP_COMPILER_GCC
-# define ELPP_GCC_VERSION (__GNUC__ * 10000 \
-+ __GNUC_MINOR__ * 100 \
-+ __GNUC_PATCHLEVEL__)
-# if defined(__GXX_EXPERIMENTAL_CXX0X__)
-# define ELPP_CXX0X 1
-# endif
-#endif
-// Visual C++
-#if defined(_MSC_VER)
-# define ELPP_COMPILER_MSVC 1
-#else
-# define ELPP_COMPILER_MSVC 0
-#endif
-#define ELPP_CRT_DBG_WARNINGS ELPP_COMPILER_MSVC
-#if ELPP_COMPILER_MSVC
-# if (_MSC_VER == 1600)
-# define ELPP_CXX0X 1
-# elif(_MSC_VER >= 1700)
-# define ELPP_CXX11 1
-# endif
-#endif
-// Clang++
-#if (defined(__clang__) && (__clang__ == 1))
-# define ELPP_COMPILER_CLANG 1
-#else
-# define ELPP_COMPILER_CLANG 0
-#endif
-#if ELPP_COMPILER_CLANG
-# if __has_include()
-# include // Make __GLIBCXX__ defined when using libstdc++
-# if !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
-# define ELPP_CLANG_SUPPORTS_THREAD
-# endif // !defined(__GLIBCXX__) || __GLIBCXX__ >= 20150426
-# endif // __has_include()
-#endif
-#if (defined(__MINGW32__) || defined(__MINGW64__))
-# define ELPP_MINGW 1
-#else
-# define ELPP_MINGW 0
-#endif
-#if (defined(__CYGWIN__) && (__CYGWIN__ == 1))
-# define ELPP_CYGWIN 1
-#else
-# define ELPP_CYGWIN 0
-#endif
-#if (defined(__INTEL_COMPILER))
-# define ELPP_COMPILER_INTEL 1
-#else
-# define ELPP_COMPILER_INTEL 0
-#endif
-// Operating System Evaluation
-// Windows
-#if (defined(_WIN32) || defined(_WIN64))
-# define ELPP_OS_WINDOWS 1
-#else
-# define ELPP_OS_WINDOWS 0
-#endif
-// Linux
-#if (defined(__linux) || defined(__linux__))
-# define ELPP_OS_LINUX 1
-#else
-# define ELPP_OS_LINUX 0
-#endif
-#if (defined(__APPLE__))
-# define ELPP_OS_MAC 1
-#else
-# define ELPP_OS_MAC 0
-#endif
-#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
-# define ELPP_OS_FREEBSD 1
-#else
-# define ELPP_OS_FREEBSD 0
-#endif
-#if (defined(__sun))
-# define ELPP_OS_SOLARIS 1
-#else
-# define ELPP_OS_SOLARIS 0
-#endif
-#if (defined(_AIX))
-# define ELPP_OS_AIX 1
-#else
-# define ELPP_OS_AIX 0
-#endif
-#if (defined(__NetBSD__))
-# define ELPP_OS_NETBSD 1
-#else
-# define ELPP_OS_NETBSD 0
-#endif
-#if defined(__EMSCRIPTEN__)
-# define ELPP_OS_EMSCRIPTEN 1
-#else
-# define ELPP_OS_EMSCRIPTEN 0
-#endif
-// Unix
-#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_NETBSD || ELPP_OS_SOLARIS || ELPP_OS_AIX || ELPP_OS_EMSCRIPTEN) && (!ELPP_OS_WINDOWS))
-# define ELPP_OS_UNIX 1
-#else
-# define ELPP_OS_UNIX 0
-#endif
-#if (defined(__ANDROID__))
-# define ELPP_OS_ANDROID 1
-#else
-# define ELPP_OS_ANDROID 0
-#endif
-// Evaluating Cygwin as *nix OS
-#if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
-# undef ELPP_OS_UNIX
-# undef ELPP_OS_LINUX
-# define ELPP_OS_UNIX 1
-# define ELPP_OS_LINUX 1
-#endif // !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN
-#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO)
-# define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout
-#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
-#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR)
-# define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr
-#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
-#if !defined(ELPP_INTERNAL_DEBUGGING_ENDL)
-# define ELPP_INTERNAL_DEBUGGING_ENDL std::endl
-#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
-#if !defined(ELPP_INTERNAL_DEBUGGING_MSG)
-# define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg
-#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT)
-// Internal Assertions and errors
-#if !defined(ELPP_DISABLE_ASSERT)
-# if (defined(ELPP_DEBUG_ASSERT_FAILURE))
-# define ELPP_ASSERT(expr, msg) if (!(expr)) { \
-std::stringstream internalInfoStream; internalInfoStream << msg; \
-ELPP_INTERNAL_DEBUGGING_OUT_ERROR \
-<< "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \
-<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; base::utils::abort(1, \
-"ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE"); }
-# else
-# define ELPP_ASSERT(expr, msg) if (!(expr)) { \
-std::stringstream internalInfoStream; internalInfoStream << msg; \
-ELPP_INTERNAL_DEBUGGING_OUT_ERROR\
-<< "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " \
-<< __LINE__ << ") [" #expr << "] WITH MESSAGE \"" << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" \
-<< ELPP_INTERNAL_DEBUGGING_ENDL; }
-# endif // (defined(ELPP_DEBUG_ASSERT_FAILURE))
-#else
-# define ELPP_ASSERT(x, y)
-#endif //(!defined(ELPP_DISABLE_ASSERT)
-#if ELPP_COMPILER_MSVC
-# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \
-{ char buff[256]; strerror_s(buff, 256, errno); \
-ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]";} (void)0
-#else
-# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \
-ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; (void)0
-#endif // ELPP_COMPILER_MSVC
-#if defined(ELPP_DEBUG_ERRORS)
-# if !defined(ELPP_INTERNAL_ERROR)
-# define ELPP_INTERNAL_ERROR(msg, pe) { \
-std::stringstream internalInfoStream; internalInfoStream << " " << msg; \
-ELPP_INTERNAL_DEBUGGING_OUT_ERROR \
-<< "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \
-<< ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << ELPP_INTERNAL_DEBUGGING_ENDL; \
-if (pe) { ELPP_INTERNAL_DEBUGGING_OUT_ERROR << " "; ELPP_INTERNAL_DEBUGGING_WRITE_PERROR; }} (void)0
-# endif
-#else
-# undef ELPP_INTERNAL_INFO
-# define ELPP_INTERNAL_ERROR(msg, pe)
-#endif // defined(ELPP_DEBUG_ERRORS)
-#if (defined(ELPP_DEBUG_INFO))
-# if !(defined(ELPP_INTERNAL_INFO_LEVEL))
-# define ELPP_INTERNAL_INFO_LEVEL 9
-# endif // !(defined(ELPP_INTERNAL_INFO_LEVEL))
-# if !defined(ELPP_INTERNAL_INFO)
-# define ELPP_INTERNAL_INFO(lvl, msg) { if (lvl <= ELPP_INTERNAL_INFO_LEVEL) { \
-std::stringstream internalInfoStream; internalInfoStream << " " << msg; \
-ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \
-<< ELPP_INTERNAL_DEBUGGING_ENDL; }}
-# endif
-#else
-# undef ELPP_INTERNAL_INFO
-# define ELPP_INTERNAL_INFO(lvl, msg)
-#endif // (defined(ELPP_DEBUG_INFO))
-#if (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
-# if (ELPP_COMPILER_GCC && !ELPP_MINGW && !ELPP_OS_ANDROID && !ELPP_OS_EMSCRIPTEN)
-# define ELPP_STACKTRACE 1
-# else
-# if ELPP_COMPILER_MSVC
-# pragma message("Stack trace not available for this compiler")
-# else
-# warning "Stack trace not available for this compiler";
-# endif // ELPP_COMPILER_MSVC
-# define ELPP_STACKTRACE 0
-# endif // ELPP_COMPILER_GCC
-#else
-# define ELPP_STACKTRACE 0
-#endif // (defined(ELPP_FEATURE_ALL)) || (defined(ELPP_FEATURE_CRASH_LOG))
-// Miscellaneous macros
-#define ELPP_UNUSED(x) (void)x
-#if ELPP_OS_UNIX
-// Log file permissions for unix-based systems
-# define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH
-#endif // ELPP_OS_UNIX
-#if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
-# if defined(ELPP_EXPORT_SYMBOLS)
-# define ELPP_EXPORT __declspec(dllexport)
-# else
-# define ELPP_EXPORT __declspec(dllimport)
-# endif // defined(ELPP_EXPORT_SYMBOLS)
-#else
-# define ELPP_EXPORT
-#endif // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC
-// Some special functions that are VC++ specific
-#undef STRTOK
-#undef STRERROR
-#undef STRCAT
-#undef STRCPY
-#if ELPP_CRT_DBG_WARNINGS
-# define STRTOK(a, b, c) strtok_s(a, b, c)
-# define STRERROR(a, b, c) strerror_s(a, b, c)
-# define STRCAT(a, b, len) strcat_s(a, len, b)
-# define STRCPY(a, b, len) strcpy_s(a, len, b)
-#else
-# define STRTOK(a, b, c) strtok(a, b)
-# define STRERROR(a, b, c) strerror(c)
-# define STRCAT(a, b, len) strcat(a, b)
-# define STRCPY(a, b, len) strcpy(a, b)
-#endif
-// Compiler specific support evaluations
-#if (ELPP_MINGW && !defined(ELPP_FORCE_USE_STD_THREAD))
-# define ELPP_USE_STD_THREADING 0
-#else
-# if ((ELPP_COMPILER_CLANG && defined(ELPP_CLANG_SUPPORTS_THREAD)) || \
- (!ELPP_COMPILER_CLANG && defined(ELPP_CXX11)) || \
- defined(ELPP_FORCE_USE_STD_THREAD))
-# define ELPP_USE_STD_THREADING 1
-# else
-# define ELPP_USE_STD_THREADING 0
-# endif
-#endif
-#undef ELPP_FINAL
-#if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
-# define ELPP_FINAL
-#else
-# define ELPP_FINAL final
-#endif // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702)
-#if defined(ELPP_EXPERIMENTAL_ASYNC)
-# define ELPP_ASYNC_LOGGING 1
-#else
-# define ELPP_ASYNC_LOGGING 0
-#endif // defined(ELPP_EXPERIMENTAL_ASYNC)
-#if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
-# define ELPP_THREADING_ENABLED 1
-#else
-# define ELPP_THREADING_ENABLED 0
-#endif // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING
-// Function macro ELPP_FUNC
-#undef ELPP_FUNC
-#if ELPP_COMPILER_MSVC // Visual C++
-# define ELPP_FUNC __FUNCSIG__
-#elif ELPP_COMPILER_GCC // GCC
-# define ELPP_FUNC __PRETTY_FUNCTION__
-#elif ELPP_COMPILER_INTEL // Intel C++
-# define ELPP_FUNC __PRETTY_FUNCTION__
-#elif ELPP_COMPILER_CLANG // Clang++
-# define ELPP_FUNC __PRETTY_FUNCTION__
-#else
-# if defined(__func__)
-# define ELPP_FUNC __func__
-# else
-# define ELPP_FUNC ""
-# endif // defined(__func__)
-#endif // defined(_MSC_VER)
-#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED
-// Keep following line commented until features are fixed
-#define ELPP_VARIADIC_TEMPLATES_SUPPORTED \
-(ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800))
-// Logging Enable/Disable macros
-#if defined(ELPP_DISABLE_LOGS)
-#define ELPP_LOGGING_ENABLED 0
-#else
-#define ELPP_LOGGING_ENABLED 1
-#endif
-#if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_DEBUG_LOG 1
-#else
-# define ELPP_DEBUG_LOG 0
-#endif // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_INFO_LOG 1
-#else
-# define ELPP_INFO_LOG 0
-#endif // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_WARNING_LOG 1
-#else
-# define ELPP_WARNING_LOG 0
-#endif // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_ERROR_LOG 1
-#else
-# define ELPP_ERROR_LOG 0
-#endif // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_FATAL_LOG 1
-#else
-# define ELPP_FATAL_LOG 0
-#endif // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_TRACE_LOG 1
-#else
-# define ELPP_TRACE_LOG 0
-#endif // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
-# define ELPP_VERBOSE_LOG 1
-#else
-# define ELPP_VERBOSE_LOG 0
-#endif // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED))
-#if (!(ELPP_CXX0X || ELPP_CXX11))
-# error "C++0x (or higher) support not detected! (Is `-std=c++11' missing?)"
-#endif // (!(ELPP_CXX0X || ELPP_CXX11))
-// Headers
-#if defined(ELPP_SYSLOG)
-# include
-#endif // defined(ELPP_SYSLOG)
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#if defined(ELPP_UNICODE)
-# include
-# if ELPP_OS_WINDOWS
-# include
-# endif // ELPP_OS_WINDOWS
-#endif // defined(ELPP_UNICODE)
-#if ELPP_STACKTRACE
-# include
-# include
-#endif // ELPP_STACKTRACE
-#if ELPP_OS_ANDROID
-# include
-#endif // ELPP_OS_ANDROID
-#if ELPP_OS_UNIX
-# include
-# include
-#elif ELPP_OS_WINDOWS
-# include
-# include
-# if defined(WIN32_LEAN_AND_MEAN)
-# if defined(ELPP_WINSOCK2)
-# include
-# else
-# include
-# endif // defined(ELPP_WINSOCK2)
-# endif // defined(WIN32_LEAN_AND_MEAN)
-#endif // ELPP_OS_UNIX
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#if ELPP_THREADING_ENABLED
-# if ELPP_USE_STD_THREADING
-# include
-# include
-# else
-# if ELPP_OS_UNIX
-# include
-# endif // ELPP_OS_UNIX
-# endif // ELPP_USE_STD_THREADING
-#endif // ELPP_THREADING_ENABLED
-#if ELPP_ASYNC_LOGGING
-# if defined(ELPP_NO_SLEEP_FOR)
-# include
-# endif // defined(ELPP_NO_SLEEP_FOR)
-# include
-# include
-# include
-#endif // ELPP_ASYNC_LOGGING
-#if defined(ELPP_STL_LOGGING)
-// For logging STL based templates
-# include
-# include
-# include
-# include
-# include
-# include
-# if defined(ELPP_LOG_STD_ARRAY)
-# include
-# endif // defined(ELPP_LOG_STD_ARRAY)
-# if defined(ELPP_LOG_UNORDERED_SET)
-# include
-# endif // defined(ELPP_UNORDERED_SET)
-#endif // defined(ELPP_STL_LOGGING)
-#if defined(ELPP_QT_LOGGING)
-// For logging Qt based classes & templates
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-#endif // defined(ELPP_QT_LOGGING)
-#if defined(ELPP_BOOST_LOGGING)
-// For logging boost based classes & templates
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-# include
-#endif // defined(ELPP_BOOST_LOGGING)
-#if defined(ELPP_WXWIDGETS_LOGGING)
-// For logging wxWidgets based classes & templates
-# include
-#endif // defined(ELPP_WXWIDGETS_LOGGING)
-#if defined(ELPP_UTC_DATETIME)
-# define elpptime_r gmtime_r
-# define elpptime_s gmtime_s
-# define elpptime gmtime
-#else
-# define elpptime_r localtime_r
-# define elpptime_s localtime_s
-# define elpptime localtime
-#endif // defined(ELPP_UTC_DATETIME)
-// Forward declarations
-namespace el {
-class Logger;
-class LogMessage;
-class PerformanceTrackingData;
-class Loggers;
-class Helpers;
-template class Callback;
-class LogDispatchCallback;
-class PerformanceTrackingCallback;
-class LoggerRegistrationCallback;
-class LogDispatchData;
-namespace base {
-class Storage;
-class RegisteredLoggers;
-class PerformanceTracker;
-class MessageBuilder;
-class Writer;
-class PErrorWriter;
-class LogDispatcher;
-class DefaultLogBuilder;
-class DefaultLogDispatchCallback;
-#if ELPP_ASYNC_LOGGING
-class AsyncLogDispatchCallback;
-class AsyncDispatchWorker;
-#endif // ELPP_ASYNC_LOGGING
-class DefaultPerformanceTrackingCallback;
-} // namespace base
-} // namespace el
-/// @brief Easylogging++ entry namespace
-namespace el {
-/// @brief Namespace containing base/internal functionality used by Easylogging++
-namespace base {
-/// @brief Data types used by Easylogging++
-namespace type {
-#undef ELPP_LITERAL
-#undef ELPP_STRLEN
-#undef ELPP_COUT
-#if defined(ELPP_UNICODE)
-# define ELPP_LITERAL(txt) L##txt
-# define ELPP_STRLEN wcslen
-# if defined ELPP_CUSTOM_COUT
-# define ELPP_COUT ELPP_CUSTOM_COUT
-# else
-# define ELPP_COUT std::wcout
-# endif // defined ELPP_CUSTOM_COUT
-typedef wchar_t char_t;
-typedef std::wstring string_t;
-typedef std::wstringstream stringstream_t;
-typedef std::wfstream fstream_t;
-typedef std::wostream ostream_t;
-#else
-# define ELPP_LITERAL(txt) txt
-# define ELPP_STRLEN strlen
-# if defined ELPP_CUSTOM_COUT
-# define ELPP_COUT ELPP_CUSTOM_COUT
-# else
-# define ELPP_COUT std::cout
-# endif // defined ELPP_CUSTOM_COUT
-typedef char char_t;
-typedef std::string string_t;
-typedef std::stringstream stringstream_t;
-typedef std::fstream fstream_t;
-typedef std::ostream ostream_t;
-#endif // defined(ELPP_UNICODE)
-#if defined(ELPP_CUSTOM_COUT_LINE)
-# define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine)
-#else
-# define ELPP_COUT_LINE(logLine) logLine << std::flush
-#endif // defined(ELPP_CUSTOM_COUT_LINE)
-typedef unsigned int EnumType;
-typedef unsigned short VerboseLevel;
-typedef unsigned long int LineNumber;
-typedef std::shared_ptr StoragePointer;
-typedef std::shared_ptr LogDispatchCallbackPtr;
-typedef std::shared_ptr PerformanceTrackingCallbackPtr;
-typedef std::shared_ptr LoggerRegistrationCallbackPtr;
-typedef std::unique_ptr PerformanceTrackerPtr;
-} // namespace type
-/// @brief Internal helper class that prevent copy constructor for class
-///
-/// @detail When using this class simply inherit it privately
-class NoCopy {
- protected:
- NoCopy(void) {}
- private:
- NoCopy(const NoCopy&);
- NoCopy& operator=(const NoCopy&);
-};
-/// @brief Internal helper class that makes all default constructors private.
-///
-/// @detail This prevents initializing class making it static unless an explicit constructor is declared.
-/// When using this class simply inherit it privately
-class StaticClass {
- private:
- StaticClass(void);
- StaticClass(const StaticClass&);
- StaticClass& operator=(const StaticClass&);
-};
-} // namespace base
-/// @brief Represents enumeration for severity level used to determine level of logging
-///
-/// @detail With Easylogging++, developers may disable or enable any level regardless of
-/// what the severity is. Or they can choose to log using hierarchical logging flag
-enum class Level : base::type::EnumType {
- /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels
- Global = 1,
- /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs.
- Trace = 2,
- /// @brief Informational events most useful for developers to debug application
- Debug = 4,
- /// @brief Severe error information that will presumably abort application
- Fatal = 8,
- /// @brief Information representing errors in application but application will keep running
- Error = 16,
- /// @brief Useful when application has potentially harmful situtaions
- Warning = 32,
- /// @brief Information that can be highly useful and vary with verbose logging level.
- Verbose = 64,
- /// @brief Mainly useful to represent current progress of application
- Info = 128,
- /// @brief Represents unknown level
- Unknown = 1010
-};
-} // namespace el
-namespace std {
-template<> struct hash {
- public:
- std::size_t operator()(const el::Level& l) const {
- return hash {}(static_cast(l));
- }
-};
-}
-namespace el {
-/// @brief Static class that contains helper functions for el::Level
-class LevelHelper : base::StaticClass {
- public:
- /// @brief Represents minimum valid level. Useful when iterating through enum.
- static const base::type::EnumType kMinValid = static_cast(Level::Trace);
- /// @brief Represents maximum valid level. This is used internally and you should not need it.
- static const base::type::EnumType kMaxValid = static_cast(Level::Info);
- /// @brief Casts level to int, useful for iterating through enum.
- static base::type::EnumType castToInt(Level level) {
- return static_cast(level);
- }
- /// @brief Casts int(ushort) to level, useful for iterating through enum.
- static Level castFromInt(base::type::EnumType l) {
- return static_cast(l);
- }
- /// @brief Converts level to associated const char*
- /// @return Upper case string based level.
- static const char* convertToString(Level level);
- /// @brief Converts from levelStr to Level
- /// @param levelStr Upper case string based level.
- /// Lower case is also valid but providing upper case is recommended.
- static Level convertFromString(const char* levelStr);
- /// @brief Applies specified function to each level starting from startIndex
- /// @param startIndex initial value to start the iteration from. This is passed as pointer and
- /// is left-shifted so this can be used inside function (fn) to represent current level.
- /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through levels.
- static void forEachLevel(base::type::EnumType* startIndex, const std::function& fn);
-};
-/// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect
-/// of logging
-enum class ConfigurationType : base::type::EnumType {
- /// @brief Determines whether or not corresponding level and logger of logging is enabled
- /// You may disable all logs by using el::Level::Global
- Enabled = 1,
- /// @brief Whether or not to write corresponding log to log file
- ToFile = 2,
- /// @brief Whether or not to write corresponding level and logger log to standard output.
- /// By standard output meaning termnal, command prompt etc
- ToStandardOutput = 4,
- /// @brief Determines format of logging corresponding level and logger.
- Format = 8,
- /// @brief Determines log file (full path) to write logs to for correponding level and logger
- Filename = 16,
- /// @brief Specifies precision of the subsecond part. It should be within range (1-6).
- SubsecondPrecision = 32,
- /// @brief Alias of SubsecondPrecision (for backward compatibility)
- MillisecondsWidth = SubsecondPrecision,
- /// @brief Determines whether or not performance tracking is enabled.
- ///
- /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger
- PerformanceTracking = 64,
- /// @brief Specifies log file max size.
- ///
- /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will
- /// be truncated and re-initiated.
- MaxLogFileSize = 128,
- /// @brief Specifies number of log entries to hold until we flush pending log data
- LogFlushThreshold = 256,
- /// @brief Represents unknown configuration
- Unknown = 1010
-};
-/// @brief Static class that contains helper functions for el::ConfigurationType
-class ConfigurationTypeHelper : base::StaticClass {
- public:
- /// @brief Represents minimum valid configuration type. Useful when iterating through enum.
- static const base::type::EnumType kMinValid = static_cast(ConfigurationType::Enabled);
- /// @brief Represents maximum valid configuration type. This is used internally and you should not need it.
- static const base::type::EnumType kMaxValid = static_cast(ConfigurationType::MaxLogFileSize);
- /// @brief Casts configuration type to int, useful for iterating through enum.
- static base::type::EnumType castToInt(ConfigurationType configurationType) {
- return static_cast(configurationType);
- }
- /// @brief Casts int(ushort) to configurationt type, useful for iterating through enum.
- static ConfigurationType castFromInt(base::type::EnumType c) {
- return static_cast(c);
- }
- /// @brief Converts configuration type to associated const char*
- /// @returns Upper case string based configuration type.
- static const char* convertToString(ConfigurationType configurationType);
- /// @brief Converts from configStr to ConfigurationType
- /// @param configStr Upper case string based configuration type.
- /// Lower case is also valid but providing upper case is recommended.
- static ConfigurationType convertFromString(const char* configStr);
- /// @brief Applies specified function to each configuration type starting from startIndex
- /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted
- /// so this can be used inside function (fn) to represent current configuration type.
- /// @param fn function to apply with each configuration type.
- /// This bool represent whether or not to stop iterating through configurations.
- static inline void forEachConfigType(base::type::EnumType* startIndex, const std::function& fn);
-};
-/// @brief Flags used while writing logs. This flags are set by user
-enum class LoggingFlag : base::type::EnumType {
- /// @brief Makes sure we have new line for each container log entry
- NewLineForContainer = 1,
- /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose
- /// logging is allowed via that module.
- AllowVerboseIfModuleNotSpecified = 2,
- /// @brief When handling crashes by default, detailed crash reason will be logged as well
- LogDetailedCrashReason = 4,
- /// @brief Allows to disable application abortion when logged using FATAL level
- DisableApplicationAbortOnFatalLog = 8,
- /// @brief Flushes log with every log-entry (performance sensative) - Disabled by default
- ImmediateFlush = 16,
- /// @brief Enables strict file rolling
- StrictLogFileSizeCheck = 32,
- /// @brief Make terminal output colorful for supported terminals
- ColoredTerminalOutput = 64,
- /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network")
- MultiLoggerSupport = 128,
- /// @brief Disables comparing performance tracker's checkpoints
- DisablePerformanceTrackingCheckpointComparison = 256,
- /// @brief Disable VModules
- DisableVModules = 512,
- /// @brief Disable VModules extensions
- DisableVModulesExtensions = 1024,
- /// @brief Enables hierarchical logging
- HierarchicalLogging = 2048,
- /// @brief Creates logger automatically when not available
- CreateLoggerAutomatically = 4096,
- /// @brief Adds spaces b/w logs that separated by left-shift operator
- AutoSpacing = 8192,
- /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only)
- FixedTimeFormat = 16384,
- // @brief Ignore SIGINT or crash
- IgnoreSigInt = 32768,
-};
-namespace base {
-/// @brief Namespace containing constants used internally.
-namespace consts {
-static const char kFormatSpecifierCharValue = 'v';
-static const char kFormatSpecifierChar = '%';
-static const unsigned int kMaxLogPerCounter = 100000;
-static const unsigned int kMaxLogPerContainer = 100;
-static const unsigned int kDefaultSubsecondPrecision = 3;
-
-#ifdef ELPP_DEFAULT_LOGGER
-static const char* kDefaultLoggerId = ELPP_DEFAULT_LOGGER;
-#else
-static const char* kDefaultLoggerId = "default";
-#endif
-
-#if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING)
-#ifdef ELPP_DEFAULT_PERFORMANCE_LOGGER
-static const char* kPerformanceLoggerId = ELPP_DEFAULT_PERFORMANCE_LOGGER;
-#else
-static const char* kPerformanceLoggerId = "performance";
-#endif // ELPP_DEFAULT_PERFORMANCE_LOGGER
-#endif
-
-#if defined(ELPP_SYSLOG)
-static const char* kSysLogLoggerId = "syslog";
-#endif // defined(ELPP_SYSLOG)
-
-#if ELPP_OS_WINDOWS
-static const char* kFilePathSeperator = "\\";
-#else
-static const char* kFilePathSeperator = "/";
-#endif // ELPP_OS_WINDOWS
-
-static const std::size_t kSourceFilenameMaxLength = 100;
-static const std::size_t kSourceLineMaxLength = 10;
-static const Level kPerformanceTrackerDefaultLevel = Level::Info;
-const struct {
- double value;
- const base::type::char_t* unit;
-} kTimeFormats[] = {
- { 1000.0f, ELPP_LITERAL("us") },
- { 1000.0f, ELPP_LITERAL("ms") },
- { 60.0f, ELPP_LITERAL("seconds") },
- { 60.0f, ELPP_LITERAL("minutes") },
- { 24.0f, ELPP_LITERAL("hours") },
- { 7.0f, ELPP_LITERAL("days") }
-};
-static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]);
-const struct {
- int numb;
- const char* name;
- const char* brief;
- const char* detail;
-} kCrashSignals[] = {
- // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..)
- {
- SIGABRT, "SIGABRT", "Abnormal termination",
- "Program was abnormally terminated."
- },
- {
- SIGFPE, "SIGFPE", "Erroneous arithmetic operation",
- "Arithemetic operation issue such as division by zero or operation resulting in overflow."
- },
- {
- SIGILL, "SIGILL", "Illegal instruction",
- "Generally due to a corruption in the code or to an attempt to execute data."
- },
- {
- SIGSEGV, "SIGSEGV", "Invalid access to memory",
- "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory."
- },
- {
- SIGINT, "SIGINT", "Interactive attention signal",
- "Interruption generated (generally) by user or operating system."
- },
-};
-static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]);
-} // namespace consts
-} // namespace base
-typedef std::function PreRollOutCallback;
-namespace base {
-static inline void defaultPreRollOutCallback(const char*, std::size_t) {}
-/// @brief Enum to represent timestamp unit
-enum class TimestampUnit : base::type::EnumType {
- Microsecond = 0, Millisecond = 1, Second = 2, Minute = 3, Hour = 4, Day = 5
-};
-/// @brief Format flags used to determine specifiers that are active for performance improvements.
-enum class FormatFlags : base::type::EnumType {
- DateTime = 1 << 1,
- LoggerId = 1 << 2,
- File = 1 << 3,
- Line = 1 << 4,
- Location = 1 << 5,
- Function = 1 << 6,
- User = 1 << 7,
- Host = 1 << 8,
- LogMessage = 1 << 9,
- VerboseLevel = 1 << 10,
- AppName = 1 << 11,
- ThreadId = 1 << 12,
- Level = 1 << 13,
- FileBase = 1 << 14,
- LevelShort = 1 << 15
-};
-/// @brief A subsecond precision class containing actual width and offset of the subsecond part
-class SubsecondPrecision {
- public:
- SubsecondPrecision(void) {
- init(base::consts::kDefaultSubsecondPrecision);
- }
- explicit SubsecondPrecision(int width) {
- init(width);
- }
- bool operator==(const SubsecondPrecision& ssPrec) {
- return m_width == ssPrec.m_width && m_offset == ssPrec.m_offset;
- }
- int m_width;
- unsigned int m_offset;
- private:
- void init(int width);
-};
-/// @brief Type alias of SubsecondPrecision
-typedef SubsecondPrecision MillisecondsWidth;
-/// @brief Namespace containing utility functions/static classes used internally
-namespace utils {
-/// @brief Deletes memory safely and points to null
-template
-static
-typename std::enable_if::value, void>::type
-safeDelete(T*& pointer) {
- if (pointer == nullptr)
- return;
- delete pointer;
- pointer = nullptr;
-}
-/// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise operation
-/// Use these function as flag = bitwise::Or(MyEnum::val1, flag);
-namespace bitwise {
-template
-static inline base::type::EnumType And(Enum e, base::type::EnumType flag) {
- return static_cast(flag) & static_cast(e);
-}
-template
-static inline base::type::EnumType Not(Enum e, base::type::EnumType flag) {
- return static_cast(flag) & ~(static_cast(e));
-}
-template
-static inline base::type::EnumType Or(Enum e, base::type::EnumType flag) {
- return static_cast(flag) | static_cast(e);
-}
-} // namespace bitwise
-template
-static inline void addFlag(Enum e, base::type::EnumType* flag) {
- *flag = base::utils::bitwise::Or(e, *flag);
-}
-template
-static inline void removeFlag(Enum e, base::type::EnumType* flag) {
- *flag = base::utils::bitwise::Not(e, *flag);
-}
-template
-static inline bool hasFlag(Enum e, base::type::EnumType flag) {
- return base::utils::bitwise::And(e, flag) > 0x0;
-}
-} // namespace utils
-namespace threading {
-#if ELPP_THREADING_ENABLED
-# if !ELPP_USE_STD_THREADING
-namespace internal {
-/// @brief A mutex wrapper for compiler that dont yet support std::recursive_mutex
-class Mutex : base::NoCopy {
- public:
- Mutex(void) {
-# if ELPP_OS_UNIX
- pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
- pthread_mutex_init(&m_underlyingMutex, &attr);
- pthread_mutexattr_destroy(&attr);
-# elif ELPP_OS_WINDOWS
- InitializeCriticalSection(&m_underlyingMutex);
-# endif // ELPP_OS_UNIX
- }
-
- virtual ~Mutex(void) {
-# if ELPP_OS_UNIX
- pthread_mutex_destroy(&m_underlyingMutex);
-# elif ELPP_OS_WINDOWS
- DeleteCriticalSection(&m_underlyingMutex);
-# endif // ELPP_OS_UNIX
- }
-
- inline void lock(void) {
-# if ELPP_OS_UNIX
- pthread_mutex_lock(&m_underlyingMutex);
-# elif ELPP_OS_WINDOWS
- EnterCriticalSection(&m_underlyingMutex);
-# endif // ELPP_OS_UNIX
- }
-
- inline bool try_lock(void) {
-# if ELPP_OS_UNIX
- return (pthread_mutex_trylock(&m_underlyingMutex) == 0);
-# elif ELPP_OS_WINDOWS
- return TryEnterCriticalSection(&m_underlyingMutex);
-# endif // ELPP_OS_UNIX
- }
-
- inline void unlock(void) {
-# if ELPP_OS_UNIX
- pthread_mutex_unlock(&m_underlyingMutex);
-# elif ELPP_OS_WINDOWS
- LeaveCriticalSection(&m_underlyingMutex);
-# endif // ELPP_OS_UNIX
- }
-
- private:
-# if ELPP_OS_UNIX
- pthread_mutex_t m_underlyingMutex;
-# elif ELPP_OS_WINDOWS
- CRITICAL_SECTION m_underlyingMutex;
-# endif // ELPP_OS_UNIX
-};
-/// @brief Scoped lock for compiler that dont yet support std::lock_guard
-template
-class ScopedLock : base::NoCopy {
- public:
- explicit ScopedLock(M& mutex) {
- m_mutex = &mutex;
- m_mutex->lock();
- }
-
- virtual ~ScopedLock(void) {
- m_mutex->unlock();
- }
- private:
- M* m_mutex;
- ScopedLock(void);
-};
-} // namespace internal
-typedef base::threading::internal::Mutex Mutex;
-typedef base::threading::internal::ScopedLock ScopedLock;
-# else
-typedef std::recursive_mutex Mutex;
-typedef std::lock_guard ScopedLock;
-# endif // !ELPP_USE_STD_THREADING
-#else
-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
-class NoScopedLock : base::NoCopy {
- public:
- explicit NoScopedLock(Mutex&) {
- }
- virtual ~NoScopedLock(void) {
- }
- private:
- NoScopedLock(void);
-};
-} // namespace internal
-typedef base::threading::internal::NoMutex Mutex;
-typedef base::threading::internal::NoScopedLock 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;
-};
-
-#if ELPP_THREADING_ENABLED
-# if !ELPP_USE_STD_THREADING
-/// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned.
-static std::string getCurrentThreadId(void) {
- std::stringstream ss;
-# if (ELPP_OS_WINDOWS)
- ss << GetCurrentThreadId();
-# endif // (ELPP_OS_WINDOWS)
- return ss.str();
-}
-# else
-/// @brief Gets ID of currently running threading using std::this_thread::get_id()
-static std::string getCurrentThreadId(void) {
- std::stringstream ss;
- ss << std::this_thread::get_id();
- return ss.str();
-}
-# endif // !ELPP_USE_STD_THREADING
-#else
-static inline std::string getCurrentThreadId(void) {
- return std::string();
-}
-#endif // ELPP_THREADING_ENABLED
-} // 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);
-
- /// @brief Gets size of file provided in stream
- static std::size_t getSizeOfFile(base::type::fstream_t* fs);
-
- /// @brief Determines whether or not provided path exist in current file system
- static bool pathExists(const char* path, bool considerFile = false);
-
- /// @brief Creates specified path on file system
- /// @param path Path to create.
- static bool createPath(const std::string& path);
- /// @brief Extracts path of filename with leading slash
- static std::string extractPathFromFilename(const std::string& fullPath,
- const char* seperator = base::consts::kFilePathSeperator);
- /// @brief builds stripped filename and puts it in buff
- static void buildStrippedFilename(const char* filename, char buff[],
- std::size_t limit = base::consts::kSourceFilenameMaxLength);
- /// @brief builds base filename and puts it in buff
- static void buildBaseFilename(const std::string& fullPath, char buff[],
- std::size_t limit = base::consts::kSourceFilenameMaxLength,
- const char* seperator = base::consts::kFilePathSeperator);
-};
-/// @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);
-
- static std::string& ltrim(std::string& str);
- static std::string& rtrim(std::string& str);
- static std::string& trim(std::string& str);
-
- /// @brief Determines whether or not str starts with specified string
- /// @param str String to check
- /// @param start String to check against
- /// @return Returns true if starts with specified string, false otherwise
- static bool startsWith(const std::string& str, const std::string& start);
-
- /// @brief Determines whether or not str ends with specified string
- /// @param str String to check
- /// @param end String to check against
- /// @return Returns true if ends with specified string, false otherwise
- static bool endsWith(const std::string& str, const std::string& end);
-
- /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance.
- /// @param [in,out] str String to replace from
- /// @param replaceWhat Character to replace
- /// @param replaceWith Character to replace with
- /// @return Modified version of str
- static std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith);
-
- /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place
- /// @param str String to replace from
- /// @param replaceWhat Character to replace
- /// @param replaceWith Character to replace with
- /// @return Modified (original) str
- static std::string& replaceAll(std::string& str, const std::string& replaceWhat,
- const std::string& replaceWith);
-
- static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
- const base::type::string_t& replaceWith);
-#if defined(ELPP_UNICODE)
- static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat,
- const std::string& replaceWith);
-#endif // defined(ELPP_UNICODE)
- /// @brief Converts string to uppercase
- /// @param str String to convert
- /// @return Uppercase string
- static std::string& toUpper(std::string& str);
-
- /// @brief Compares cstring equality - uses strcmp
- static bool cStringEq(const char* s1, const char* s2);
-
- /// @brief Compares cstring equality (case-insensitive) - uses toupper(char)
- /// Dont use strcasecmp because of CRT (VC++)
- static bool cStringCaseEq(const char* s1, const char* s2);
-
- /// @brief Returns true if c exist in str
- static bool contains(const char* str, char c);
-
- static char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true);
- static char* addToBuff(const char* str, char* buf, const char* bufLim);
- static char* clearBuff(char buff[], std::size_t lim);
-
- /// @brief Converst wchar* to char*
- /// NOTE: Need to free return value after use!
- static char* wcharPtrToCharPtr(const wchar_t* line);
-};
-/// @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 getenv(const char*)
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);
-#endif // ELPP_OS_WINDOWS
-#if ELPP_OS_ANDROID
- /// @brief Reads android property value
- static std::string getProperty(const char* prop);
-
- /// @brief Reads android device name
- static std::string getDeviceName(void);
-#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);
-
- /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++)
- /// @param variableName Environment variable name
- /// @param defaultVal If no environment variable or value found the value to return by default
- /// @param alternativeBashCommand If environment variable not found what would be alternative bash command
- /// in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami'
- static std::string getEnvironmentVariable(const char* variableName, const char* defaultVal,
- const char* alternativeBashCommand = nullptr);
- /// @brief Gets current username.
- static std::string currentUser(void);
-
- /// @brief Gets current host name or computer name.
- ///
- /// @detail For android systems this is device name with its manufacturer and model seperated by hyphen
- static std::string currentHost(void);
- /// @brief Whether or not terminal supports colors
- static bool termSupportsColor(void);
-};
-/// @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 microsecond.
- ///
- /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a seperate implementation is provided
- /// @param [in,out] tv Pointer that gets updated
- static void gettimeofday(struct timeval* tv);
-
- /// @brief Gets current date and time with a subsecond part.
- /// @param format User provided date/time format
- /// @param ssPrec A pointer to base::SubsecondPrecision from configuration (non-null)
- /// @returns string based date time in specified format.
- static std::string getDateTime(const char* format, const base::SubsecondPrecision* ssPrec);
-
- /// @brief Converts timeval (struct from ctime) to string using specified format and subsecond precision
- static std::string timevalToString(struct timeval tval, const char* format,
- const el::base::SubsecondPrecision* ssPrec);
-
- /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc
- static base::type::string_t formatTime(unsigned long long time, base::TimestampUnit timestampUnit);
-
- /// @brief Gets time difference in milli/micro second depending on timestampUnit
- static unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime,
- base::TimestampUnit timestampUnit);
-
-
- static struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo);
- private:
- static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo,
- std::size_t msec, const base::SubsecondPrecision* ssPrec);
-};
-/// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..)
-class CommandLineArgs {
- public:
- CommandLineArgs(void) {
- setArgs(0, static_cast(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(argv));
- }
- /// @brief Sets arguments and parses them
- void setArgs(int argc, char** argv);
- /// @brief Returns true if arguments contain paramKey with a value (seperated by '=')
- bool hasParamWithValue(const char* paramKey) const;
- /// @brief Returns value of arguments
- /// @see hasParamWithValue(const char*)
- const char* getParamValue(const char* paramKey) const;
- /// @brief Return true if arguments has a param (not having a value) i,e without '='
- bool hasParam(const char* paramKey) const;
- /// @brief Returns true if no params available. This exclude argv[0]
- bool empty(void) const;
- /// @brief Returns total number of arguments. This exclude argv[0]
- std::size_t size(void) const;
- friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c);
-
- private:
- int m_argc;
- char** m_argv;
- std::unordered_map m_paramsWithValue;
- std::vector 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&) 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
-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& 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& 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&) = 0;
- void reinitDeepCopy(const AbstractRegistry& 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. Any implementation of this class should be
-/// explicitly (by using lock functions)
-template
-class Registry : public AbstractRegistry> {
- public:
- typedef typename Registry::iterator iterator;
- typedef typename Registry::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>() {
- 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 void unregisterAll(void) ELPP_FINAL {
- if (!this->empty()) {
- for (auto&& curr : this->list()) {
- base::utils::safeDelete(curr.second);
- }
- this->list().clear();
- }
- }
-
-/// @brief Registers new registry to repository.
- virtual void registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL {
- unregister(uniqKey);
- this->list().insert(std::make_pair(uniqKey, ptr));
- }
-
-/// @brief Unregisters single entry mapped to specified unique key
- void unregister(const T_Key& uniqKey) {
- T_Ptr* existing = get(uniqKey);
- if (existing != nullptr) {
- this->list().erase(uniqKey);
- base::utils::safeDelete(existing);
- }
- }
-
-/// @brief Gets pointer from repository. If none found, nullptr is returned.
- T_Ptr* get(const T_Key& uniqKey) {
- iterator it = this->list().find(uniqKey);
- return it == this->list().end()
- ? nullptr
- : it->second;
- }
-
- private:
- virtual void deepCopy(const AbstractRegistry>& 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. Any implementation of this class
-/// should be made thread-safe explicitly
-template
-class RegistryWithPred : public AbstractRegistry> {
- public:
- typedef typename RegistryWithPred::iterator iterator;
- typedef typename RegistryWithPred::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>() {
- 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 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 void unregisterAll(void) ELPP_FINAL {
- if (!this->empty()) {
- for (auto&& curr : this->list()) {
- base::utils::safeDelete(curr);
- }
- this->list().clear();
- }
- }
-
- virtual void unregister(T_Ptr*& ptr) ELPP_FINAL {
- if (ptr) {
- iterator iter = this->begin();
- for (; iter != this->end(); ++iter) {
- if (ptr == *iter) {
- break;
- }
- }
- if (iter != this->end() && *iter != nullptr) {
- this->list().erase(iter);
- base::utils::safeDelete(*iter);
- }
- }
- }
-
- virtual inline void registerNew(T_Ptr* ptr) ELPP_FINAL {
- this->list().push_back(ptr);
- }
-
-/// @brief Gets pointer from repository with speicifed arguments. Arguments are passed to predicate
-/// in order to validate pointer.
- template
- T_Ptr* get(const T& arg1, const T2 arg2) {
- iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2));
- if (iter != this->list().end() && *iter != nullptr) {
- return *iter;
- }
- return nullptr;
- }
-
- private:
- virtual void deepCopy(const AbstractRegistry>& sr) {
- for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) {
- registerNew(new T_Ptr(**it));
- }
- }
-};
-class Utils {
- public:
- template
- static bool installCallback(const std::string& id, std::unordered_map* mapT) {
- if (mapT->find(id) == mapT->end()) {
- mapT->insert(std::make_pair(id, TPtr(new T())));
- return true;
- }
- return false;
- }
-
- template
- static void uninstallCallback(const std::string& id, std::unordered_map* mapT) {
- if (mapT->find(id) != mapT->end()) {
- mapT->erase(id);
- }
- }
-
- template
- static T* callback(const std::string& id, std::unordered_map* mapT) {
- typename std::unordered_map::iterator iter = mapT->find(id);
- if (iter != mapT->end()) {
- return static_cast(iter->second.get());
- }
- return nullptr;
- }
-};
-} // namespace utils
-} // namespace base
-/// @brief Base of Easylogging++ friendly class
-///
-/// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const`
-class Loggable {
- public:
- virtual ~Loggable(void) {}
- virtual void log(el::base::type::ostream_t&) const = 0;
- private:
- friend inline el::base::type::ostream_t& operator<<(el::base::type::ostream_t& os, const Loggable& loggable) {
- loggable.log(os);
- return os;
- }
-};
-namespace base {
-/// @brief Represents log format containing flags and date format. This is used internally to start initial log
-class LogFormat : public Loggable {
- public:
- LogFormat(void);
- LogFormat(Level level, const base::type::string_t& format);
- LogFormat(const LogFormat& logFormat);
- LogFormat(LogFormat&& logFormat);
- LogFormat& operator=(const LogFormat& logFormat);
- virtual ~LogFormat(void) {}
- bool operator==(const LogFormat& other);
-
- /// @brief Updates format to be used while logging.
- /// @param userFormat User provided format
- void parseFromFormat(const base::type::string_t& userFormat);
-
- inline Level level(void) const {
- return m_level;
- }
-
- inline const base::type::string_t& userFormat(void) const {
- return m_userFormat;
- }
-
- inline const base::type::string_t& format(void) const {
- return m_format;
- }
-
- inline const std::string& dateTimeFormat(void) const {
- return m_dateTimeFormat;
- }
-
- inline base::type::EnumType flags(void) const {
- return m_flags;
- }
-
- inline bool hasFlag(base::FormatFlags flag) const {
- return base::utils::hasFlag(flag, m_flags);
- }
-
- virtual void log(el::base::type::ostream_t& os) const {
- os << m_format;
- }
-
- protected:
- /// @brief Updates date time format if available in currFormat.
- /// @param index Index where %datetime, %date or %time was found
- /// @param [in,out] currFormat current format that is being used to format
- virtual void updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL;
-
- /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format and m_level
- virtual void updateFormatSpec(void) ELPP_FINAL;
-
- inline void addFlag(base::FormatFlags flag) {
- base::utils::addFlag(flag, &m_flags);
- }
-
- private:
- Level m_level;
- base::type::string_t m_userFormat;
- base::type::string_t m_format;
- std::string m_dateTimeFormat;
- base::type::EnumType m_flags;
- std::string m_currentUser;
- std::string m_currentHost;
- friend class el::Logger; // To resolve loggerId format specifier easily
-};
-} // namespace base
-/// @brief Resolving function for format specifier
-typedef std::function FormatSpecifierValueResolver;
-/// @brief User-provided custom format specifier
-/// @see el::Helpers::installCustomFormatSpecifier
-/// @see FormatSpecifierValueResolver
-class CustomFormatSpecifier {
- public:
- CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver) :
- m_formatSpecifier(formatSpecifier), m_resolver(resolver) {}
- inline const char* formatSpecifier(void) const {
- return m_formatSpecifier;
- }
- inline const FormatSpecifierValueResolver& resolver(void) const {
- return m_resolver;
- }
- inline bool operator==(const char* formatSpecifier) {
- return strcmp(m_formatSpecifier, formatSpecifier) == 0;
- }
-
- private:
- const char* m_formatSpecifier;
- FormatSpecifierValueResolver m_resolver;
-};
-/// @brief Represents single configuration that has representing level, configuration type and a string based value.
-///
-/// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside quotes
-/// and will be parsed later.
-///
-/// Consider some examples below:
-/// * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true");
-/// * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048");
-/// * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log");
-class Configuration : public Loggable {
- public:
- Configuration(const Configuration& c);
- Configuration& operator=(const Configuration& c);
-
- virtual ~Configuration(void) {
- }
-
- /// @brief Full constructor used to sets value of configuration
- Configuration(Level level, ConfigurationType configurationType, const std::string& value);
-
- /// @brief Gets level of current configuration
- inline Level level(void) const {
- return m_level;
- }
-
- /// @brief Gets configuration type of current configuration
- inline ConfigurationType configurationType(void) const {
- return m_configurationType;
- }
-
- /// @brief Gets string based configuration value
- inline const std::string& value(void) const {
- return m_value;
- }
-
- /// @brief Set string based configuration value
- /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any integral values
- /// use them in quotes. They will be parsed when configuring
- inline void setValue(const std::string& value) {
- m_value = value;
- }
-
- virtual void log(el::base::type::ostream_t& os) const;
-
- /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it.
- class Predicate {
- public:
- Predicate(Level level, ConfigurationType configurationType);
-
- bool operator()(const Configuration* conf) const;
-
- private:
- Level m_level;
- ConfigurationType m_configurationType;
- };
-
- private:
- Level m_level;
- ConfigurationType m_configurationType;
- std::string m_value;
-};
-
-/// @brief Thread-safe Configuration repository
-///
-/// @detail This repository represents configurations for all the levels and configuration type mapped to a value.
-class Configurations : public base::utils::RegistryWithPred {
- public:
- /// @brief Default constructor with empty repository
- Configurations(void);
-
- /// @brief Constructor used to set configurations using configuration file.
- /// @param configurationFile Full path to configuration file
- /// @param useDefaultsForRemaining Lets you set the remaining configurations to default.
- /// @param base If provided, this configuration will be based off existing repository that this argument is pointing to.
- /// @see parseFromFile(const std::string&, Configurations* base)
- /// @see setRemainingToDefault()
- Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true,
- Configurations* base = nullptr);
-
- virtual ~Configurations(void) {
- }
-
- /// @brief Parses configuration from file.
- /// @param configurationFile Full path to configuration file
- /// @param base Configurations to base new configuration repository off. This value is used when you want to use
- /// existing Configurations to base all the values and then set rest of configuration via configuration file.
- /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you
- /// do not proceed without successful parse.
- bool parseFromFile(const std::string& configurationFile, Configurations* base = nullptr);
-
- /// @brief Parse configurations from configuration string.
- ///
- /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary
- /// new line characters are provided.
- /// @param base Configurations to base new configuration repository off. This value is used when you want to use
- /// existing Configurations to base all the values and then set rest of configuration via configuration text.
- /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you
- /// do not proceed without successful parse.
- bool parseFromText(const std::string& configurationsString, Configurations* base = nullptr);
-
- /// @brief Sets configuration based-off an existing configurations.
- /// @param base Pointer to existing configurations.
- void setFromBase(Configurations* base);
-
- /// @brief Determines whether or not specified configuration type exists in the repository.
- ///
- /// @detail Returns as soon as first level is found.
- /// @param configurationType Type of configuration to check existence for.
- bool hasConfiguration(ConfigurationType configurationType);
-
- /// @brief Determines whether or not specified configuration type exists for specified level
- /// @param level Level to check
- /// @param configurationType Type of configuration to check existence for.
- bool hasConfiguration(Level level, ConfigurationType configurationType);
-
- /// @brief Sets value of configuration for specified level.
- ///
- /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types
- /// ConfigurationType::SubsecondPrecision and ConfigurationType::PerformanceTracking will be ignored if not set for
- /// Level::Global because these configurations are not dependant on level.
- /// @param level Level to set configuration for (el::Level).
- /// @param configurationType Type of configuration (el::ConfigurationType)
- /// @param value A string based value. Regardless of what the data type of configuration is, it will always be string
- /// from users' point of view. This is then parsed later to be used internally.
- /// @see Configuration::setValue(const std::string& value)
- /// @see el::Level
- /// @see el::ConfigurationType
- void set(Level level, ConfigurationType configurationType, const std::string& value);
-
- /// @brief Sets single configuration based on other single configuration.
- /// @see set(Level level, ConfigurationType configurationType, const std::string& value)
- void set(Configuration* conf);
-
- inline Configuration* get(Level level, ConfigurationType configurationType) {
- base::threading::ScopedLock scopedLock(lock());
- return RegistryWithPred::get(level, configurationType);
- }
-
- /// @brief Sets configuration for all levels.
- /// @param configurationType Type of configuration
- /// @param value String based value
- /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value)
- inline void setGlobally(ConfigurationType configurationType, const std::string& value) {
- setGlobally(configurationType, value, false);
- }
-
- /// @brief Clears repository so that all the configurations are unset
- inline void clear(void) {
- base::threading::ScopedLock scopedLock(lock());
- unregisterAll();
- }
-
- /// @brief Gets configuration file used in parsing this configurations.
- ///
- /// @detail If this repository was set manually or by text this returns empty string.
- inline const std::string& configurationFile(void) const {
- return m_configurationFile;
- }
-
- /// @brief Sets configurations to "factory based" configurations.
- void setToDefault(void);
-
- /// @brief Lets you set the remaining configurations to default.
- ///
- /// @detail By remaining, it means that the level/type a configuration does not exist for.
- /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file that sets
- /// configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set to default i.e,
- /// true. If you dont do this explicitly (either by calling this function or by using second param in Constructor
- /// and try to access a value, an error is thrown
- void setRemainingToDefault(void);
-
- /// @brief Parser used internally to parse configurations from file or text.
- ///
- /// @detail This class makes use of base::utils::Str.
- /// You should not need this unless you are working on some tool for Easylogging++
- class Parser : base::StaticClass {
- public:
- /// @brief Parses configuration from file.
- /// @param configurationFile Full path to configuration file
- /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
- /// @param base Configurations to base new configuration repository off. This value is used when you want to use
- /// existing Configurations to base all the values and then set rest of configuration via configuration file.
- /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you
- /// do not proceed without successful parse.
- static bool parseFromFile(const std::string& configurationFile, Configurations* sender,
- Configurations* base = nullptr);
-
- /// @brief Parse configurations from configuration string.
- ///
- /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary
- /// new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you
- /// do not proceed without successful parse (This is recommended)
- /// @param configurationsString the configuration in plain text format
- /// @param sender Sender configurations pointer. Usually 'this' is used from calling class
- /// @param base Configurations to base new configuration repository off. This value is used when you want to use
- /// existing Configurations to base all the values and then set rest of configuration via configuration text.
- /// @return True if successfully parsed, false otherwise.
- static bool parseFromText(const std::string& configurationsString, Configurations* sender,
- Configurations* base = nullptr);
-
- private:
- friend class el::Loggers;
- static void ignoreComments(std::string* line);
- static bool isLevel(const std::string& line);
- static bool isComment(const std::string& line);
- static inline bool isConfig(const std::string& line);
- static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel,
- Configurations* conf);
- };
-
- private:
- std::string m_configurationFile;
- bool m_isFromFile;
- friend class el::Loggers;
-
- /// @brief Unsafely sets configuration if does not already exist
- void unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value);
-
- /// @brief Thread unsafe set
- void unsafeSet(Level level, ConfigurationType configurationType, const std::string& value);
-
- /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true
- /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
- void setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
-
- /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true
- /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value)
- void unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel);
-};
-
-namespace base {
-typedef std::shared_ptr FileStreamPtr;
-typedef std::unordered_map LogStreamsReferenceMap;
-/// @brief Configurations with data types.
-///
-/// @detail el::Configurations have string based values. This is whats used internally in order to read correct configurations.
-/// This is to perform faster while writing logs using correct configurations.
-///
-/// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class)
-class TypedConfigurations : public base::threading::ThreadSafe {
- public:
- /// @brief Constructor to initialize (construct) the object off el::Configurations
- /// @param configurations Configurations pointer/reference to base this typed configurations off.
- /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference()
- TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference);
-
- TypedConfigurations(const TypedConfigurations& other);
-
- virtual ~TypedConfigurations(void) {
- }
-
- const Configurations* configurations(void) const {
- return m_configurations;
- }
-
- bool enabled(Level level);
- bool toFile(Level level);
- const std::string& filename(Level level);
- bool toStandardOutput(Level level);
- const base::LogFormat& logFormat(Level level);
- const base::SubsecondPrecision& subsecondPrecision(Level level = Level::Global);
- const base::MillisecondsWidth& millisecondsWidth(Level level = Level::Global);
- bool performanceTracking(Level level = Level::Global);
- base::type::fstream_t* fileStream(Level level);
- std::size_t maxLogFileSize(Level level);
- std::size_t logFlushThreshold(Level level);
-
- private:
- Configurations* m_configurations;
- std::unordered_map m_enabledMap;
- std::unordered_map m_toFileMap;
- std::unordered_map m_filenameMap;
- std::unordered_map m_toStandardOutputMap;
- std::unordered_map m_logFormatMap;
- std::unordered_map m_subsecondPrecisionMap;
- std::unordered_map m_performanceTrackingMap;
- std::unordered_map m_fileStreamMap;
- std::unordered_map m_maxLogFileSizeMap;
- std::unordered_map m_logFlushThresholdMap;
- base::LogStreamsReferenceMap* m_logStreamsReference;
-
- friend class el::Helpers;
- friend class el::base::MessageBuilder;
- friend class el::base::Writer;
- friend class el::base::DefaultLogDispatchCallback;
- friend class el::base::LogDispatcher;
-
- template
- inline Conf_T getConfigByVal(Level level, const std::unordered_map* confMap, const char* confName) {
- base::threading::ScopedLock scopedLock(lock());
- return unsafeGetConfigByVal(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope
- }
-
- template