• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H25-Dec-2020-1510

cmake/H25-Dec-2020-206188

doc/H25-Dec-2020-2,1711,545

samples/H25-Dec-2020-7,0895,216

src/H25-Dec-2020-7,6986,387

test/H25-Dec-2020-1,9561,551

tools/H25-Dec-2020-4,8213,151

.gitignoreH A D25-Dec-202098 109

.travis.ymlH A D25-Dec-20202.3 KiB9794

ACKNOWLEDGEMENTS.mdH A D25-Dec-20201.6 KiB1613

CHANGELOG.mdH A D25-Dec-20204.3 KiB11589

LICENSEH A D25-Dec-20201.2 KiB2620

README.mdH A D25-Dec-202096.9 KiB1,5521,196

easyloggingpp.priH A D25-Dec-2020371 1812

README.md

1<p align="center">
23</p>
4
5![banner]
6
7> **Manual For v9.96.7**
8
9[![Build Status (Master)](https://img.shields.io/travis/amrayn/easyloggingpp/master.svg)](#build-matrix)
10[![Build Status (Develop)](https://img.shields.io/travis/amrayn/easyloggingpp/develop.svg)](#build-matrix)
11[![Build status](https://ci.appveyor.com/api/projects/status/sfcgrehu8ypkrun3?svg=true)](https://ci.appveyor.com/project/abumusamq/easyloggingpp-node)
12
13[![Node Binding Version](https://img.shields.io/github/release/amrayn/easyloggingpp.svg)](https://github.com/amrayn/easyloggingpp-node/releases/latest)
14[![Version](https://img.shields.io/npm/v/easyloggingpp.svg)](https://www.npmjs.com/package/easyloggingpp)
15
16[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/amrayn/easyloggingpp/blob/master/LICENCE)
17[![Downloads](https://img.shields.io/github/downloads/amrayn/easyloggingpp/total.svg)](https://github.com/amrayn/easyloggingpp/releases/latest)
18
19[![Donate](https://amrayn.github.io/donate.png?v2)](https://amrayn.com/donate)
20
21#### Looking for maintainers!!
22
23### Quick Links
24
25  [![download] Latest Release](https://github.com/amrayn/easyloggingpp/releases/latest)
26
27  [![notes] Changelog](/CHANGELOG.md)
28
29  [![samples] Samples](/samples)
30
31---
32
33### Table of Contents
34<pre>
35<a href="#overview">Overview</a>
36    <a href="#why-yet-another-library">Why yet another library</a>
37    <a href="#features-at-a-glance">Features at a glance</a>
38<a href="#getting-started">Getting Started</a>
39    <a href="#download">Download</a>
40    <a href="#quick-start">Quick Start</a>
41    <a href="#install-optional">Install (Optional)</a>
42    <a href="#setting-application-arguments">Setting Application Arguments</a>
43<a href="#configuration">Configuration</a>
44    <a href="#level">Level</a>
45    <a href="#configure">Configure</a>
46        <a href="#using-configuration-file">Using Configuration File</a>
47        <a href="#using-elconfigurations-class">Using el::Configurations Class</a>
48        <a href="#using-in-line-configurations">Using In line Configurations</a>
49    <a href="#default-configurations">Default Configurations</a>
50    <a href="#global-configurations">Global Configurations</a>
51    <a href="#logging-format-specifiers">Logging Format Specifiers</a>
52    <a href="#datetime-format-specifiers">Date/Time Format Specifiers</a>
53    <a href="#custom-format-specifiers">Custom Format Specifiers</a>
54    <a href="#logging-flags">Logging Flags</a>
55    <a href="#application-arguments">Application Arguments</a>
56    <a href="#configuration-macros">Configuration Macros</a>
57    <a href="#reading-configurations">Reading Configurations</a>
58<a href="#logging">Logging</a>
59    <a href="#basic">Basic</a>
60    <a href="#conditional-logging">Conditional Logging</a>
61    <a href="#occasional-logging">Occasional Logging</a>
62    <a href="#printf-like-logging">printf Like Logging</a>
63    <a href="#network-logging">Network Logging</a>
64    <a href="#verbose-logging">Verbose Logging</a>
65        <a href="#basic-1">Basic</a>
66        <a href="#conditional-and-occasional-logging">Conditional and Occasional</a>
67        <a href="#verbose-level">Verbose Level</a>
68        <a href="#check-if-verbose-logging-is-on">Check If Verbose Logging Is On</a>
69        <a href="#vmodule">VModule</a>
70    <a href="#registering-new-loggers">Registering New Loggers</a>
71    <a href="#unregister-loggers">Unregister Loggers</a>
72    <a href="#populating-existing-logger-ids">Populating Existing Logger IDs</a>
73    <a href="#sharing-logging-repository">Sharing Logging Repository</a>
74<a href="#extra-features">Extra Features</a>
75    <a href="#performance-tracking">Performance Tracking</a>
76        <a href="#conditional-performance-tracking">Conditional Performance Tracking</a>
77        <a href="#make-use-of-performance-tracking-data">Make Use of Performance Tracking Data</a>
78    <a href="#log-file-rotating">Log File Rotating</a>
79    <a href="#crash-handling">Crash Handling</a>
80        <a href="#installing-custom-crash-handlers">Installing Custom Crash Handlers</a>
81    <a href="#stacktrace">Stacktrace</a>
82    <a href="#multi-threading">Multi-threading</a>
83    <a href="#check-macros">CHECK Macros</a>
84    <a href="#logging-perror">Logging perror()</a>
85    <a href="#syslog">Using Syslog</a>
86    <a href="#stl-logging">STL Logging</a>
87        <a href="#supported-templates">Supported Templates</a>
88    <a href="#qt-logging">Qt Logging</a>
89    <a href="#boost-logging">Boost Logging</a>
90    <a href="#wxwidgets-logging">wxWidgets Logging</a>
91    <a href="#extending-library">Extending Library</a>
92        <a href="#logging-your-own-class">Logging Your Own Class</a>
93        <a href="#logging-third-party-class">Logging Third-party Class</a>
94    <a href="#manually-flushing-and-rolling-log-files">Manually Flushing and Rolling Log Files</a>
95    <a href="#log-dispatch-callback">Log Dispatch Callback</a>
96    <a href="#logger-registration-callback">Logger Registration Callback</a>
97    <a href="#asynchronous-logging">Asynchronous Logging</a>
98    <a href="#helper-classes">Helper Classes</a>
99<a href="#contribution">Contribution</a>
100    <a href="#submitting-patches">Submitting Patches</a>
101    <a href="#reporting-a-bug">Reporting a Bug</a>
102<a href="#compatibility">Compatibility</a>
103    <a href="#build-matrix">Build Matrix</a>
104<a href="#licence">Licence</a>
105<a href="#disclaimer">Disclaimer</a>
106</pre>
107
108# Overview
109Easylogging++ 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.
110
111This manual is for Easylogging++ v9.96.7. For other versions please refer to corresponding [release](https://github.com/amrayn/easyloggingpp/releases) on github.
112
113> You may also be interested in [Residue](https://github.com/amrayn/residue/) logging server.
114
115 [![top] Goto Top](#table-of-contents)
116
117### Why yet another library
118If 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/amrayn/easyloggingpp/issues/445). You can still use header-only in [v9.89](https://github.com/amrayn/easyloggingpp/releases/tag/9.89)).
119
120This library has been designed with various thoughts in mind (i.e, portability, performance, usability, features and easy to setup).
121
122Why 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.
123
124 [![top] Goto Top](#table-of-contents)
125
126### Features at a glance
127Easylogging++ is feature-rich containing many features that both typical and advanced developer will require while writing a software;
128 * [Highly configurable](#configuration)
129 * [Extendable](#extending-library)
130 * Extremely fast
131 * [Thread](#multi-threading) and type safe
132 * [Cross-platform](#compatibility)
133 * [Custom log patterns](#logging-format-specifiers)
134 * [Conditional and occasional logging](#conditional-logging)
135 * [Performance tracking](#performance-tracking)
136 * [Verbose logging](#verbose-logging)
137 * [Crash handling](#crash-handling)
138 * [Helper CHECK macros](#check-macros)
139 * [STL logging](#stl-logging)
140 * [Send to Syslog](#syslog)
141 * [Third-party library logging (Qt, boost, wxWidgets etc)](#logging-third-party-class)
142 * [Extensible (Logging your own class or third-party class)](#logging-your-own-class)
143 * [And many more...](#extra-features)
144
145 [![top] Goto Top](#table-of-contents)
146
147# Getting Started
148### Download
149Download latest version from [Latest Release](https://github.com/amrayn/easyloggingpp/releases/latest)
150
151For other releases, please visit [releases page](https://github.com/amrayn/easyloggingpp/releases). If you application does not support C++11, please consider using [v8.91](https://github.com/amrayn/easyloggingpp/tree/v8.91). This is stable version for C++98 and C++03, just lack some features.
152
153 [![top] Goto Top](#table-of-contents)
154
155### Quick Start
156In order to get started with Easylogging++, you can follow three easy steps:
157* Download latest version
158* Include into your project (`easylogging++.h` and `easylogging++.cc`)
159* Initialize using single macro... and off you go!
160
161```c++
162#include "easylogging++.h"
163
164INITIALIZE_EASYLOGGINGPP
165
166int main(int argc, char* argv[]) {
167   LOG(INFO) << "My first info log using default logger";
168   return 0;
169}
170```
171
172Now compile using
173
174```
175g++ main.cc easylogging++.cc -o prog -std=c++11
176```
177
178That simple! Please note that `INITIALIZE_EASYLOGGINGPP` should be used once and once-only otherwise you will end up getting compilation errors. This is the definition of 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.
179
180### Install (Optional)
181If you want to install this header system-wide, you can do so via:
182```
183mkdir build
184cd build
185cmake -Dtest=ON ../
186make
187make test
188make install
189```
190
191Following options are supported by Easylogging++ cmake and you can turn these options on using `-D<option>=ON`
192
193 * `lib_utc_datetime` - Defines `ELPP_UTC_DATETIME`
194 * `build_static_lib` - Builds static library for Easylogging++
195
196With that said, you will still need `easylogging++.cc` file in order to compile. For header only, please check [v9.89](https://github.com/amrayn/easyloggingpp/releases/tag/9.89) and lower.
197
198Alternatively, you can download and install easyloggingpp using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
199
200    git clone https://github.com/Microsoft/vcpkg.git
201    cd vcpkg
202    ./bootstrap-vcpkg.sh
203    ./vcpkg integrate install
204    ./vcpkg install easyloggingpp
205
206The easyloggingpp port in vcpkg is kept up to date by Microsoft team members and community contributors.
207If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
208
209 [![top] Goto Top](#table-of-contents)
210
211### Setting Application Arguments
212It 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;
213
214```c++
215int main(int argc, char* argv[]) {
216   START_EASYLOGGINGPP(argc, argv);
217   ...
218}
219```
220 [![top] Goto Top](#table-of-contents)
221
222# Configuration
223### Level
224In 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)
225
226|   Level  |                 Description                                                                                                                                   |
227|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
228| Global   | Generic level that represents all levels. Useful when setting global configuration for all levels.                                                            |
229| Trace    | Information that can be useful to back-trace certain events - mostly useful than debug logs.                                                                  |
230| 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++).|
231| Fatal    | Very severe error event that will presumably lead the application to abort.                                                                                   |
232| Error    | Error information but will continue application to keep running.                                                                                              |
233| Warning  | Information representing errors in application but application will keep running.                                                                             |
234| Info     | Mainly useful to represent current progress of application.                                                                                                   |
235| Verbose  | Information that can be highly useful and vary with verbose logging level. Verbose logging is not applicable to hierarchical logging.                         |
236| Unknown  | Only applicable to hierarchical logging and is used to turn off logging completely.                                                                           |
237
238 [![top] Goto Top](#table-of-contents)
239
240### Configure
241Easylogging++ is easy to configure. There are three possible ways to do so,
242* Using configuration file
243* Using el::Configurations class
244* Using inline configuration
245
246#### Using Configuration File
247Configuration can be done by file that is loaded at runtime by `Configurations` class. This file has following format;
248```
249* LEVEL:
250  CONFIGURATION NAME  = "VALUE" ## Comment
251  ANOTHER CONFIG NAME = "VALUE"
252```
253
254Level 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.
255Following table contains configurations supported by configuration file.
256
257|   Configuration Name  |   Type   |                 Description                                                                                                                                                 |
258|-----------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
259| `Enabled`               |   bool   | Determines whether or not corresponding level for logger is enabled. You may disable all logs by using `el::Level::Global`                                                |
260| `To_File`               |   bool   | Whether or not to write corresponding log to log file                                                                                                                     |
261| `To_Standard_Output`    |   bool   | Whether or not to write logs to standard output e.g, terminal or command prompt                                                                                           |
262| `Format`                |   char*  | Determines format/pattern of logging for corresponding level and logger.                                                                                                  |
263| `Filename`              |   char*  | Determines log file (full path) to write logs to for corresponding level and logger                                                                                       |
264| `Subsecond_Precision`   |   uint   | Specifies subsecond precision (previously called 'milliseconds width'). Width can be within range (1-6)                                                                   |
265| `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|
266| `Max_Log_File_Size`     |   size_t | If log file size of corresponding level is >= specified size, log file will be truncated.                                                                                 |
267| `Log_Flush_Threshold`   |  size_t  | Specifies number of log entries to hold until we flush pending log data                                                                                                   |
268
269
270Please do not use double-quotes anywhere in comment, you might end up in unexpected behaviour.
271
272Sample Configuration File
273```
274* GLOBAL:
275   FORMAT               =  "%datetime %msg"
276   FILENAME             =  "/tmp/logs/my.log"
277   ENABLED              =  true
278   TO_FILE              =  true
279   TO_STANDARD_OUTPUT   =  true
280   SUBSECOND_PRECISION  =  6
281   PERFORMANCE_TRACKING =  true
282   MAX_LOG_FILE_SIZE    =  2097152 ## 2MB - Comment starts with two hashes (##)
283   LOG_FLUSH_THRESHOLD  =  100 ## Flush after every 100 logs
284* DEBUG:
285   FORMAT               = "%datetime{%d/%M} %func %msg"
286```
287
288##### Explanation
289Configuration 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
290
291##### Usage
292```c++
293#include "easylogging++.h"
294
295INITIALIZE_EASYLOGGINGPP
296
297int main(int argc, const char** argv) {
298    // Load configuration from file
299    el::Configurations conf("/path/to/my-conf.conf");
300    // Reconfigure single logger
301    el::Loggers::reconfigureLogger("default", conf);
302    // Actually reconfigure all loggers instead
303    el::Loggers::reconfigureAllLoggers(conf);
304    // Now all the loggers will use configuration from file
305}
306```
307
308 > 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).
309
310 [![top] Goto Top](#table-of-contents)
311
312#### Using el::Configurations Class
313You can set configurations or reset configurations;
314```c++
315#include "easylogging++.h"
316
317INITIALIZE_EASYLOGGINGPP
318
319int main(int argc, const char** argv) {
320   el::Configurations defaultConf;
321   defaultConf.setToDefault();
322    // Values are always std::string
323   defaultConf.set(el::Level::Info,
324            el::ConfigurationType::Format, "%datetime %level %msg");
325    // default logger uses default configurations
326    el::Loggers::reconfigureLogger("default", defaultConf);
327    LOG(INFO) << "Log using default file";
328    // To set GLOBAL configurations you may use
329   defaultConf.setGlobally(
330            el::ConfigurationType::Format, "%date %msg");
331   el::Loggers::reconfigureLogger("default", defaultConf);
332    return 0;
333}
334```
335
336 > Configuration just needs to be set once. If you are happy with default configuration, you may use it as well.
337
338 [![top] Goto Top](#table-of-contents)
339
340#### Using In line Configurations
341Inline 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.
342```c++
343el::Configurations c;
344c.setToDefault();
345c.parseFromText("*GLOBAL:\n FORMAT = %level %msg");
346```
347
348 > Above code only sets Configurations object, you still need to re-configure logger/s using this configurations.
349
350 [![top] Goto Top](#table-of-contents)
351
352### Default Configurations
353If 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`).
354
355 [![top] Goto Top](#table-of-contents)
356
357### Global Configurations
358`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:
359```
360-- LOGGER ID ## Case sensitive
361  ## Everything else is same as configuration file
362
363
364-- ANOTHER LOGGER ID
365  ## Configuration for this logger
366```
367
368Logger 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;
369```c++
370int main(void) {
371   // Registers new and configures it or
372   // configures existing logger - everything in global.conf
373   el::Loggers::configureFromGlobal("global.conf");
374   // .. Your prog
375   return 0;
376}
377```
378Please 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.
379
380 [![top] Goto Top](#table-of-contents)
381
382### Logging Format Specifiers
383You can customize format of logging using following specifiers:
384
385|     Specifier   |                 Replaced By                                                                 |
386|-----------------|---------------------------------------------------------------------------------------------|
387| `%logger`       | Logger ID                                                                                   |
388| `%thread`       | Thread ID - Uses std::thread if available, otherwise GetCurrentThreadId() on windows        |
389| `%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)|
390| `%level`        | Severity level (Info, Debug, Error, Warning, Fatal, Verbose, Trace)                         |
391| `%levshort`     | Severity level (Short version i.e, I for Info and respectively D, E, W, F, V, T)            |
392| `%vlevel`       | Verbosity level (Applicable to verbose logging)                                             |
393| `%datetime`     | Date and/or time - Pattern is customizable - see Date/Time Format Specifiers below          |
394| `%user`         | User currently running application                                                          |
395| `%host`         | Computer name application is running on                                                     |
396| `%file`*         | File name of source file (Full path) - This feature is subject to availability of `__FILE__` macro of compiler                                                        |
397| `%fbase`*        | File name of source file (Only base name)                                                   |
398| `%line`*         | Source line number - This feature is subject to availability of `__LINE__` macro of compile |
399| `%func`*         | Logging function                                                                            |
400| `%loc`*          | Source filename and line number of logging (separated by colon)                             |
401| `%msg`          | Actual log message                                                                          |
402| `%`             | Escape character (e.g, %%level will write %level)                                           |
403
404* Subject to compiler's availability of certain macros, e.g, `__LINE__`, `__FILE__` etc
405
406 [![top] Goto Top](#table-of-contents)
407
408### Date/Time Format Specifiers
409You can customize date/time format using following specifiers
410
411|    Specifier    |                 Replaced By                                                                                      |
412|-----------------|------------------------------------------------------------------------------------------------------------------|
413| `%d`            | Day of month (zero-padded)                                                                                       |
414| `%a`            | Day of the week - short (Mon, Tue, Wed, Thu, Fri, Sat, Sun)                                                      |
415| `%A`            | Day of the week - long (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)                          |
416| `%M`            | Month (zero-padded)                                                                                              |
417| `%b`            | Month - short (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)                                       |
418| `%B`            | Month - Long (January, February, March, April, May, June, July, August, September, October, November, December)  |
419| `%y`            | Year - Two digit (13, 14 etc)                                                                                    |
420| `%Y`            | Year - Four digit (2013, 2014 etc)                                                                               |
421| `%h`            | Hour (12-hour format)                                                                                            |
422| `%H`            | Hour (24-hour format)                                                                                            |
423| `%m`            | Minute (zero-padded)                                                                                             |
424| `%s`            | Second (zero-padded)                                                                                             |
425| `%g`            | Subsecond part (precision is configured by ConfigurationType::SubsecondPrecision)                               |
426| `%F`            | AM/PM designation                                                                                                |
427| `%`             | Escape character                                                                                                 |
428
429Please note, date/time is limited to `30` characters at most.
430
431 [![top] Goto Top](#table-of-contents)
432
433### Custom Format Specifiers
434
435You 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;
436
437```C++
438const char* getIp(const el::LogMessage*) {
439    return "192.168.1.1";
440}
441
442int main(void) {
443    el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%ip_addr", getIp));
444    el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, "%datetime %level %ip_addr : %msg");
445    LOG(INFO) << "This is request from client";
446    return 0;
447}
448```
449
450 [![top] Goto Top](#table-of-contents)
451
452### Logging Flags
453Form some parts of logging you can set logging flags; here are flags supported:
454
455|     Flag                                               |                 Description                                                                                                                   |
456|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
457| `NewLineForContainer (1)`                              | Makes sure we have new line for each container log entry                                                                                      |
458| `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                                 |
459| `LogDetailedCrashReason (4)`                           | When handling crashes by default, detailed crash reason will be logged as well (Disabled by default) ([issue #90](https://github.com/amrayn/easyloggingpp/issues/90))                                                                                                                                                                                |
460| `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/amrayn/easyloggingpp/issues/119))                                                                                                                                                                               |
461| `ImmediateFlush (16)`                                  | Flushes log with every log-entry (performance sensitive) - Disabled by default                                                                |
462| `StrictLogFileSizeCheck (32)`                          | Makes sure log file size is checked with every log                                                                                            |
463| `ColoredTerminalOutput (64)`                           | Terminal output will be colorful if supported by terminal.                                                                                            |
464| `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;`) |
465| `DisablePerformanceTrackingCheckpointComparison (256)` | Disables checkpoint comparison |
466| `DisableVModules (512)`                               | Disables usage of vmodules
467| `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 |
468| `HierarchicalLogging (2048)`                          | Enables hierarchical logging. This is not applicable to verbose logging.|
469| `CreateLoggerAutomatically (4096)`                          | Creates logger automatically when not available. |
470| `AutoSpacing (8192)`                          | Automatically adds spaces. E.g, `LOG(INFO) << "DODGE" << "THIS!";` will output "DODGE THIS!"|
471| `FixedTimeFormat (16384)`                          | Applicable to performance tracking only - this prevents formatting time. E.g, `1001 ms` will be logged as is, instead of formatting it as `1.01 sec`|
472| `IgnoreSigInt (32768)`                          | When application crashes ignore Interruption signal |
473
474You 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`
475
476 > 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).
477
478 > You can also set default (initial) flags using `ELPP_DEFAULT_LOGGING_FLAGS` and set numerical value for initial flags
479
480 [![top] Goto Top](#table-of-contents)
481
482### Application Arguments
483Following 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.
484
485|        Argument            |                                      Description                                        |
486|----------------------------|-----------------------------------------------------------------------------------------|
487| `-v`                       | Activates maximum verbosity                                                             |
488| `--v=2`                    | Activates verbosity upto verbose level 2 (valid range: 0-9)                             |
489| `--verbose`                | Activates maximum verbosity                                                             |
490| `-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.                                                                                                               |
491| `--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.                                                                   |
492| `--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.                                                                           |
493
494 [![top] Goto Top](#table-of-contents)
495
496### Configuration Macros
497Some 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_`
498
499**NOTE:** All the macros can be defined in one of the following ways:
500
501 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**)
502
503 2. Define macros inside `"easylogging++.h"` ([defining macros in other files won't work](https://github.com/amrayn/easyloggingpp/issues/590#issuecomment-346753951))
504
505|   Macro Name                             |                 Description                                                                                                                        |
506|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
507| `ELPP_DEBUG_ASSERT_FAILURE`             | Aborts application on first assertion failure. This assertion is due to invalid input e.g, invalid configuration file etc.                         |
508| `ELPP_UNICODE`                          | Enables Unicode support when logging. Requires `START_EASYLOGGINGPP`                 |
509| `ELPP_THREAD_SAFE`                      | Enables thread-safety - make sure -lpthread linking for linux.                                                                                     |
510| `ELPP_FORCE_USE_STD_THREAD`             | Forces to use C++ standard library for threading (Only useful when using `ELPP_THREAD_SAFE`            |
511| `ELPP_FEATURE_CRASH_LOG`              | Applicable to GCC only. Enables stacktrace on application crash                                                                                    |
512| `ELPP_DISABLE_DEFAULT_CRASH_HANDLING`   | Disables default crash handling. You can use el::Helpers::setCrashHandler to use your own handler.                                                 |
513| `ELPP_DISABLE_LOGS`                     | Disables all logs - (preprocessing)                                                                                                                |
514| `ELPP_DISABLE_DEBUG_LOGS`               | Disables debug logs - (preprocessing)                                                                                                              |
515| `ELPP_DISABLE_INFO_LOGS`                | Disables info logs - (preprocessing)                                                                                                               |
516| `ELPP_DISABLE_WARNING_LOGS`             | Disables warning logs - (preprocessing)                                                                                                            |
517| `ELPP_DISABLE_ERROR_LOGS`               | Disables error logs - (preprocessing)                                                                                                              |
518| `ELPP_DISABLE_FATAL_LOGS`               | Disables fatal logs - (preprocessing)                                                                                                              |
519| `ELPP_DISABLE_VERBOSE_LOGS`             | Disables verbose logs - (preprocessing)                                                                                                            |
520| `ELPP_DISABLE_TRACE_LOGS`               | Disables trace logs - (preprocessing)                                                                                                              |
521| `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/amrayn/easyloggingpp/issues/87) for details))                                                                                                                                                                                       |
522| `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                                                                                 |
523| `ELPP_NO_LOG_TO_FILE`                 | Disable logging to file initially|
524| `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) |
525| `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)                                                  |
526| `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.                                                                                                                                             |
527| `ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS` | Forcefully disables custom format specifiers                                                                                                       |
528| `ELPP_DISABLE_LOGGING_FLAGS_FROM_ARG`   | Forcefully disables ability to set logging flags using command-line arguments                                                                      |
529| `ELPP_DISABLE_LOG_FILE_FROM_ARG`        | Forcefully disables ability to set default log file from command-line arguments                                                                    |
530| `ELPP_WINSOCK2`        | On windows system force to use `winsock2.h` instead of `winsock.h` when `WIN32_LEAN_AND_MEAN` is defined                                                                    |
531| `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`|
532| `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()` |
533| `ELPP_NO_CHECK_MACROS`             | Do not define the *CHECK* macros                                                                                                                  |
534| `ELPP_NO_DEBUG_MACROS`             | Do not define the *DEBUG* macros                                                                                                                  |
535| `ELPP_UTC_DATETIME`                | Uses UTC time instead of local time (essentially uses `gmtime` instead of `localtime` and family functions)
536| `ELPP_NO_GLOBAL_LOCK`  | Do not lock the whole storage on dispatch. This should be used with care. See [issue #580](https://github.com/amrayn/easyloggingpp/issues/580)|
537
538 [![top] Goto Top](#table-of-contents)
539
540### Reading Configurations
541If you wish to read configurations of certain logger, you can do so by using `typedConfigurations()` function in Logger class.
542```c++
543el::Logger* l = el::Loggers::getLogger("default");
544bool enabled = l->typedConfigurations()->enabled(el::Level::Info);
545// Or to read log format/pattern
546std::string format =
547        l->typedConfigurations()->logFormat(el::Level::Info).format();
548```
549
550 [![top] Goto Top](#table-of-contents)
551
552# Logging
553Logging 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.
554
555### Basic
556You are provided with two basic macros that you can use in order to write logs:
557* `LOG(LEVEL)`
558* `CLOG(LEVEL, logger ID)`
559
560`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.
561Here is very simple example of using these macros after you have initialized easylogging++.
562```c++
563LOG(INFO) << "This is info log";
564CLOG(ERROR, "performance") << "This is info log using performance logger";
565```
566
567There 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.
568
569A quick example is here
570```c++
571#ifndef ELPP_DEFAULT_LOGGER
572#   define ELPP_DEFAULT_LOGGER "update_manager"
573#endif
574#ifndef ELPP_DEFAULT_PERFORMANCE_LOGGER
575#   define ELPP_DEFAULT_PERFORMANCE_LOGGER ELPP_DEFAULT_LOGGER
576#endif
577#include "easylogging++.h"
578UpdateManager::UpdateManager {
579    _TRACE; // Logs using LOG(TRACE) provided logger is already registered - i.e, update_manager
580    LOG(INFO) << "This will log using update_manager logger as well";
581}
582```
583
584```c++
585#include "easylogging++.h"
586UpdateManager::UpdateManager {
587    _TRACE; // Logs using LOG(TRACE) using default logger because no `ELPP_DEFAULT_LOGGER` is defined unless you have it in makefile
588}
589```
590
591 > 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`.
592
593 [![top] Goto Top](#table-of-contents)
594
595### Conditional Logging
596Easylogging++ 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.
597Helper macros end with _IF;
598* `LOG_IF(condition, LEVEL)`
599* `CLOG_IF(condition, LEVEL, logger ID)`
600
601
602#### Some examples:
603```c++
604LOG_IF(condition, INFO) << "Logged if condition is true";
605
606LOG_IF(false, WARNING) << "Never logged";
607CLOG_IF(true, INFO, "performance") << "Always logged (performance logger)"
608```
609
610Same 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.
611
612 [![top] Goto Top](#table-of-contents)
613
614### Occasional Logging
615Occasional 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.
616Helper macros end with `_EVERY_N`;
617* `LOG_EVERY_N(n, LEVEL)`
618* `CLOG_EVERY_N(n, LEVEL, logger ID)`
619
620#### Other Hit Counts Based Logging
621There are some other ways of logging as well based on hit counts. These useful macros are
622* `LOG_AFTER_N(n, LEVEL)`; Only logs when we have reached hit counts of `n`
623* `LOG_N_TIMES(n, LEVEL)`; Logs n times
624
625#### Some examples:
626```c++
627for (int i = 1; i <= 10; ++i) {
628   LOG_EVERY_N(2, INFO) << "Logged every second iter";
629}
630// 5 logs written; 2, 4, 6, 7, 10
631
632for (int i = 1; i <= 10; ++i) {
633   LOG_AFTER_N(2, INFO) << "Log after 2 hits; " << i;
634}
635// 8 logs written; 3, 4, 5, 6, 7, 8, 9, 10
636
637for (int i = 1; i <= 100; ++i) {
638   LOG_N_TIMES(3, INFO) << "Log only 3 times; " << i;
639}
640// 3 logs writter; 1, 2, 3
641```
642
643 > 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)
644
645 [![top] Goto Top](#table-of-contents)
646
647### `printf` Like Logging
648For 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)
649
650This is done in two steps:
651 1. Pulling registered logger using `el::Loggers::getLogger(<logger_id>);`
652 2. Using one of logging functions
653
654The 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`
655
656Following are various function signatures:
657 * `info(const char*, const T&, const Args&...)`
658 * `warn(const char*, const T&, const Args&...)`
659 * `error(const char*, const T&, const Args&...)`
660 * `debug(const char*, const T&, const Args&...)`
661 * `fatal(const char*, const T&, const Args&...)`
662 * `trace(const char*, const T&, const Args&...)`
663 * `verbose(int vlevel, const char*, const T&, const Args&...)`
664
665#### Simple example:
666
667```c++
668// Use default logger
669el::Logger* defaultLogger = el::Loggers::getLogger("default");
670
671// STL logging (`ELPP_STL_LOGGING` should be defined)
672std::vector<int> i;
673i.push_back(1);
674defaultLogger->warn("My first ultimate log message %v %v %v", 123, 222, i);
675
676// Escaping
677defaultLogger->info("My first ultimate log message %% %%v %v %v", 123, 222);
678
679```
680
681 > `%file`, `%func` `%line` and `%loc` format specifiers will not work with `printf` like logging.
682
683 [![top] Goto Top](#table-of-contents)
684
685### Network Logging
686
687You 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)
688
689 [![top] Goto Top](#table-of-contents)
690
691### Verbose Logging
692#### Basic
693Verbose logging is useful in every software to record more information than usual. Very useful for troubleshooting. Following are verbose logging specific macros;
694* `VLOG(verbose-level)`
695* `CVLOG(verbose-level, logger ID)`
696
697 [![top] Goto Top](#table-of-contents)
698
699#### Conditional and Occasional Logging
700Verbose logging also has conditional and occasional logging aspects i.e,
701* `VLOG_IF(condition, verbose-level)`
702* `CVLOG_IF(condition, verbose-level, loggerID)`
703* `VLOG_EVERY_N(n, verbose-level)`
704* `CVLOG_EVERY_N(n, verbose-level, loggerID)`
705* `VLOG_AFTER_N(n, verbose-level)`
706* `CVLOG_AFTER_N(n, verbose-level, loggerID)`
707* `VLOG_N_TIMES(n, verbose-level)`
708* `CVLOG_N_TIMES(n, verbose-level, loggerID)`
709
710 [![top] Goto Top](#table-of-contents)
711
712
713#### Verbose-Level
714Verbose 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.
715
716In 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()`
717
718 [![top] Goto Top](#table-of-contents)
719
720#### Check If Verbose Logging Is On
721You 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.
722```c++
723if (VLOG_IS_ON(2)) {
724   // Verbosity level 2 is on for this file
725}
726```
727
728 [![top] Goto Top](#table-of-contents)
729
730#### VModule
731VModule 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`
732
733Example with `LoggingFlag::AllowVerboseIfModuleNotSpecified` flag;
734
735`main=3,parser*=4`:
736 * A bad example but good enough for explanation;
737 * Verbosity for any following file will be allowed;
738    `main{.h, .c, .cpp, .cc, .cxx, -inl.h, .hxx, .hpp}`
739    `parser{.h, .c, .cpp, .cc, .cxx, -inl.h, .hxx, .hpp}`
740 * No other file will be logged for verbose level
741
742Example with no `LoggingFlag::AllowVerboseIfModuleNotSpecified` flag;
743
744`main=3,parser*=4`:
745 Same explanation but any other file that does not fall under specified modules will have verbose logging enabled.
746
747In 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)
748
749 [![top] Goto Top](#table-of-contents)
750
751### Registering New Loggers
752Loggers 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.
753
754By default, Easylogging++ registers three loggers (+ an internal logger);
755* Default logger (ID: `default`)
756* Performance logger (ID: `performance`)
757* Syslog logger (if `ELPP_SYSLOG` macro is defined) (ID: `syslog`)
758
759If you wish to register a new logger, say e.g, with ID `business`
760```c++
761el::Logger* businessLogger = el::Loggers::getLogger("business");
762```
763
764This 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.
765
766When you register a new logger, default configurations are used (see Default Configurations section above). Also worth noticing, logger IDs are case sensitive.
767
768 [![top] Goto Top](#table-of-contents)
769
770### Unregister Loggers
771You 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.
772
773To unregister logger, use `el::Loggers::unregisterLogger("logger-id")`
774
775 [![top] Goto Top](#table-of-contents)
776
777### Populating Existing Logger IDs
778Although 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<std::string>&)` function to do that. The list passed in is cleared and filled up with all existing logger IDs.
779
780 [![top] Goto Top](#table-of-contents)
781
782### Sharing Logging Repository
783For 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;
784
785Let'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;
786
787 * Instead of using `INITIALIZE_EASYLOGGINGPP` you use `SHARE_EASYLOGGINGPP(access-function-to-repository)`
788 * Instead of using `INITIALIZE_EASYLOGGINGPP` you use `INITIALIZE_NULL_EASYLOGGINGPP` and then `el::Helpers::setStorage(el::base::type::StoragePointer)`
789
790After 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.
791
792 [![top] Goto Top](#table-of-contents)
793
794# Extra Features
795Easylogging++ 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.
796
797Some 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`.
798
799### Performance Tracking
800Prerequisite: Define macro `ELPP_FEATURE_PERFORMANCE_TRACKING`
801
802One of the most notable features of Easylogging++ is its ability to track performance of your function or block of function.
803Please 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)
804The 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.
805* `TIMED_FUNC(obj-name)`
806* `TIMED_SCOPE(obj-name, block-name)`
807* `TIMED_BLOCK(obj-name, block-name)`
808
809An example that just uses usleep
810```c++
811void performHeavyTask(int iter) {
812   TIMED_FUNC(timerObj);
813   // Some initializations
814   // Some more heavy tasks
815   usleep(5000);
816   while (iter-- > 0) {
817       TIMED_SCOPE(timerBlkObj, "heavy-iter");
818       // Perform some heavy task in each iter
819       usleep(10000);
820   }
821}
822```
823
824The result of above execution for iter = 10, is as following
825```
82606:22:31,368 INFO Executed [heavy-iter] in [10 ms]
82706:22:31,379 INFO Executed [heavy-iter] in [10 ms]
82806:22:31,389 INFO Executed [heavy-iter] in [10 ms]
82906:22:31,399 INFO Executed [heavy-iter] in [10 ms]
83006:22:31,409 INFO Executed [heavy-iter] in [10 ms]
83106:22:31,419 INFO Executed [heavy-iter] in [10 ms]
83206:22:31,429 INFO Executed [heavy-iter] in [10 ms]
83306:22:31,440 INFO Executed [heavy-iter] in [10 ms]
83406:22:31,450 INFO Executed [heavy-iter] in [10 ms]
83506:22:31,460 INFO Executed [heavy-iter] in [10 ms]
83606:22:31,460 INFO Executed [void performHeavyTask(int)] in [106 ms]
837```
838
839In 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)
840
841You 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.
842Checkpoints have two macros:
843* `PERFORMANCE_CHECKPOINT(timed-block-obj-name)`
844* `PERFORMANCE_CHECKPOINT_WITH_ID(timed-block-obj-name, id)`
845
846Take a look at following example
847```c++
848void performHeavyTask(int iter) {
849   TIMED_FUNC(timerObj);
850   // Some initializations
851   // Some more heavy tasks
852   usleep(5000);
853   while (iter-- > 0) {
854       TIMED_SCOPE(timerBlkObj, "heavy-iter");
855       // Perform some heavy task in each iter
856       // Notice following sleep varies with each iter
857       usleep(iter * 1000);
858       if (iter % 3) {
859           PERFORMANCE_CHECKPOINT(timerBlkObj);
860       }
861   }
862}
863```
864
865Notice macro on line-11 (also note comment on line-8). It's checkpoint for heavy-iter block. Now notice following output
866```
86706:33:07,558 INFO Executed [heavy-iter] in [9 ms]
86806:33:07,566 INFO Performance checkpoint for block [heavy-iter] : [8 ms]
86906:33:07,566 INFO Executed [heavy-iter] in [8 ms]
87006:33:07,573 INFO Performance checkpoint for block [heavy-iter] : [7 ms]
87106:33:07,573 INFO Executed [heavy-iter] in [7 ms]
87206:33:07,579 INFO Executed [heavy-iter] in [6 ms]
87306:33:07,584 INFO Performance checkpoint for block [heavy-iter] : [5 ms]
87406:33:07,584 INFO Executed [heavy-iter] in [5 ms]
87506:33:07,589 INFO Performance checkpoint for block [heavy-iter] : [4 ms]
87606:33:07,589 INFO Executed [heavy-iter] in [4 ms]
87706:33:07,592 INFO Executed [heavy-iter] in [3 ms]
87806:33:07,594 INFO Performance checkpoint for block [heavy-iter] : [2 ms]
87906:33:07,594 INFO Executed [heavy-iter] in [2 ms]
88006:33:07,595 INFO Performance checkpoint for block [heavy-iter] : [1 ms]
88106:33:07,595 INFO Executed [heavy-iter] in [1 ms]
88206:33:07,595 INFO Executed [heavy-iter] in [0 ms]
88306:33:07,595 INFO Executed [void performHeavyTask(int)] in [51 ms]
884```
885
886You 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
887```
88806:40:35,522 INFO Performance checkpoint for block [void performHeavyTask(int)] : [51 ms ([1 ms] from last checkpoint)]
889```
890
891If you had used `PERFORMANCE_CHECKPOINT_WITH_ID(timerObj, "mychkpnt");` instead, you will get
892```
89306:44:37,979 INFO Performance checkpoint [mychkpnt] for block [void performHeavyTask(int)] : [51 ms ([1 ms] from checkpoint 'mychkpnt')]
894```
895
896Following are some useful macros that you can define to change the behaviour
897
898|   Macro Name                                        |                 Description                                                                                                    |
899|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
900| `ELPP_DISABLE_PERFORMANCE_TRACKING`                | Disables performance tracking                                                                                                  |
901| `ELPP_PERFORMANCE_MICROSECONDS`                    | Track up-to microseconds (this includes initializing of el::base::PerformanceTracker as well so might time not be 100% accurate)        |
902
903Notes:
904
9051. 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.
906
9072. 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.
908
9093. In order to access `el::base::type::PerformanceTrackerPtr` while in `TIMED_BLOCK`, you can use `timerObj.timer`
910
9114. `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.
912
913 > You may be interested in [python script to parse performance logs](https://github.com/amrayn/easyloggingpp/issues/206)
914
915 [![top] Goto Top](#table-of-contents)
916
917#### Conditional Performance Tracking
918If 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`.
919
920 A verbosity level example is given below
921
922```c++
923 void performHeavyTask(int iter) {
924    // enable performance tracking for verbosity level 4 or higher
925    TIMED_FUNC_IF( timerObj, VLOG_IS_ON(4) );
926    // Some more heavy tasks
927 }
928```
929
930 [![top] Goto Top](#table-of-contents)
931
932#### Make Use of Performance Tracking Data
933If you wish to capture performance tracking data right after it is finished, you can do so by extending `el::PerformanceTrackingCallback`.
934
935In order to install this handler, use `void Helpers::installPerformanceTrackingCallback<T>(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<T>(const std::string& id)`. See samples for details
936
937 > DO NOT TRACK PERFORMANCE IN THIS HANDLER OR YOU WILL END UP IN INFINITE-LOOP
938
939 [![top] Goto Top](#table-of-contents)
940
941### Log File Rotating
942Easylogging++ 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.
943
944Rollout checking happens when Easylogging++ flushes the log file, or, if you have added the flag `el::LoggingFlags::StrictLogFileSizeCheck`, at each log output.
945
946This 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.
947This can be done by using `el::Helpers::installPreRollOutCallback(const PreRollOutCallback& handler)` where `PreRollOutCallback` is typedef of type `std::function<void(const char*, std::size_t)>`. Please note following if you are using this feature
948
949There is a [sample](/samples/STL/logrotate.cpp) available that you can use as basis.
950
951> 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.
952
953 [![top] Goto Top](#table-of-contents)
954
955### Crash Handling
956Prerequisite: Define macro `ELPP_FEATURE_CRASH_LOG`
957
958Easylogging++ 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.
959
960Following signals are handled;
961* SIGABRT (If `ELPP_HANDLE_SIGABRT` macro is defined)
962* SIGFPE
963* SIGILL
964* SIGSEGV
965* SIGINT
966
967Stacktraces 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.
968
969> Default handler and stack trace uses `default` logger.
970
971Following are some useful macros that you can define to change the behaviour
972
973|   Macro Name                                        |                 Description                                                                                                    |
974|-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
975| `ELPP_DISABLE_DEFAULT_CRASH_HANDLING`              | Disables default crash handling.                                                                                               |
976| `ELPP_HANDLE_SIGABRT`                              | Enables handling `SIGABRT`. This is disabled by default to prevent annoying `CTRL + C` behaviour when you wish to abort.       |
977
978 [![top] Goto Top](#table-of-contents)
979
980#### Installing Custom Crash Handlers
981You can use your own crash handler by using `el::Helpers::setCrashHandler(const el::base::debug::CrashHandler::Handler&);`.
982
983> 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.
984
985Here is a good example of your own handler
986```c++
987#include "easylogging++.h"
988
989INITIALIZE_EASYLOGGINGPP
990
991void myCrashHandler(int sig) {
992    LOG(ERROR) << "Woops! Crashed!";
993    // FOLLOWING LINE IS ABSOLUTELY NEEDED AT THE END IN ORDER TO ABORT APPLICATION
994    el::Helpers::crashAbort(sig);
995}
996int main(void) {
997    el::Helpers::setCrashHandler(myCrashHandler);
998
999    LOG(INFO) << "My crash handler!";
1000
1001    int* i;
1002    *i = 0; // Crash!
1003
1004    return 0;
1005}
1006```
1007
1008> 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:
1009```c++
1010>  bool stackTraceIfAvailable = false
1011>  const el::Level& level = el::Level::Fatal
1012>  const char* logger = "default"
1013```
1014
1015 [![top] Goto Top](#table-of-contents)
1016
1017### Stacktrace
1018Prerequisite: Define macro `ELPP_FEATURE_CRASH_LOG`
1019
1020Easylogging++ 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.
1021
1022 [![top] Goto Top](#table-of-contents)
1023
1024### Multi-threading
1025Prerequisite: Define macro `ELPP_THREAD_SAFE`
1026
1027Easylogging++ 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.
1028
1029 [![top] Goto Top](#table-of-contents)
1030
1031### CHECK Macros
1032Easylogging++ 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).
1033
1034|                     CHECK Name              |                 Notes + Example                                                                                                 |
1035|---------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
1036| `CHECK(condition)`                          | Checks for condition e.g, `CHECK(isLoggedIn()) << "Not logged in";`                                                             |
1037| `CHECK_EQ(a, b)`                            | Equality check e.g, `CHECK_EQ(getId(), getLoggedOnId()) << "Invalid user logged in";`                                           |
1038| `CHECK_NE(a, b)`                            | Inequality check e.g, `CHECK_NE(isUserBlocked(userId), false) << "User is blocked";`                                            |
1039| `CHECK_LT(a, b)`                            | Less than e.g, `CHECK_LT(1, 2) << "How 1 is not less than 2";`                                                                  |
1040| `CHECK_GT(a, b)`                            | Greater than e.g, `CHECK_GT(2, 1) << "How 2 is not greater than 1?";`                                                           |
1041| `CHECK_LE(a, b)`                            | Less than or equal e.g, `CHECK_LE(1, 1) << "1 is not equal or less than 1";`                                                    |
1042| `CHECK_GE(a, b)`                            | Greater than or equal e.g, `CHECK_GE(1, 1) << "1 is not equal or greater than 1";`                                              |
1043| `CHECK_NOTNULL(pointer)`                    | Ensures pointer is not null. This function does not return anything           |
1044| `CHECK_STREQ(str1, str2)`                   | C-string equality (case-sensitive) e.g, `CHECK_STREQ(argv[1], "0") << "First arg cannot be 0";`                                 |
1045| `CHECK_STRNE(str1, str2)`                   | C-string inequality (case-sensitive) e.g, `CHECK_STRNE(username1, username2) << "Usernames cannot be same";`                    |
1046| `CHECK_STRCASEEQ(str1, str2)`               | C-string inequality (*case-insensitive*) e.g, `CHECK_CASESTREQ(argv[1], "Z") << "First arg cannot be 'z' or 'Z'";`              |
1047| `CHECK_STRCASENE(str1, str2)`               | C-string inequality (*case-insensitive*) e.g, `CHECK_STRCASENE(username1, username2) << "Same username not allowed";`           |
1048| `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";`    |
1049
1050> 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)
1051
1052 [![top] Goto Top](#table-of-contents)
1053
1054### Logging perror()
1055Easylogging++ 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.
1056
1057 [![top] Goto Top](#table-of-contents)
1058
1059### Syslog
1060Prerequisite: Define macro `ELPP_SYSLOG`
1061
1062Easylogging++ 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)`
1063
1064Syslog in Easylogging++ supports C++ styled streams logging, following example;
1065```c++
1066#include "easylogging++.h"
1067
1068INITIALIZE_EASYLOGGINGPP
1069int main(void) {
1070    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
1071    // Alternatively you may do
1072    // el::SysLogInitializer elSyslogInit("my_proc", LOG_PID | LOG_CONS | LOG_PERROR, LOG_USER);
1073    SYSLOG(INFO) << "This is syslog - read it from /var/log/syslog"
1074    return 0;
1075}
1076```
1077
1078Syslog support for Easylogging++ only supports following levels; each level is corresponded with syslog priority as following
1079
1080 * INFO (LOG_INFO)
1081 * DEBUG (LOG_DEBUG)
1082 * WARNING (LOG_WARNING)
1083 * ERROR (LOG_ERR)
1084 * FATAL (LOG_EMERG)
1085
1086Following levels are not supported and correspond to `LOG_NOTICE`: TRACE, whereas VERBOSE level is completely not supported
1087
1088 [![top] Goto Top](#table-of-contents)
1089
1090### STL Logging
1091Prerequisite: Define macro `ELPP_STL_LOGGING`
1092
1093As 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.
1094For 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.
1095
1096 [![top] Goto Top](#table-of-contents)
1097
1098#### Supported Templates
1099Following 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.
1100
1101|     *       |          *              |       *          |       *          |
1102|-------------|-------------------------|------------------|------------------|
1103| std::vector |  std::list              |  std::deque      |    std::queue    |
1104| std::stack  |  std::priority_queue    |  std::set        |    std::multiset |
1105| std::pair   |  std::bitset            |  std::map        |    std::multimap |
1106
1107Some C++11 specific templates are supported by further explicit macro definitions; note these also need `ELPP_STL_LOGGING`
1108
1109|   Template              |     Macro Needed            |
1110|-------------------------|-----------------------------|
1111| std::array              | `ELPP_LOG_STD_ARRAY`       |
1112| std::unordered_map      | `ELPP_LOG_UNORDERED_MAP`   |
1113| std::unordered_multimap | `ELPP_LOG_UNORDERED_MAP`   |
1114| std::unordered_set      | `ELPP_LOG_UNORDERED_SET`   |
1115| std::unordered_multiset | `ELPP_LOG_UNORDERED_SET`   |
1116
1117Standard manipulators are also supported, in addition std::stringstream is also supported.
1118
1119[![top] Goto Top](#table-of-contents)
1120
1121### Qt Logging
1122Prerequisite: Define macro `ELPP_QT_LOGGING`
1123
1124Easylogging++ 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.
1125
1126Following Qt classes and containers are supported by Easylogging++ v9.0+
1127
1128|     *         |          *                |       *            |         *          |         *          |         *          |
1129|---------------|---------------------------|--------------------|--------------------|--------------------|--------------------|
1130| `QString`     |  `QByteArray`             |  `QLatin`          |    `QList`         |    `QVector`       |    `QQueue`        |
1131| `QSet`        |  `QPair`                  |  `QMap`            |    `QMultiMap`     |    `QHash`         |    `QMultiHash`    |
1132| `QLinkedList` |  `QStack`                 |  `QChar`           |    `q[u]int[64]`   |                    |                    |
1133
1134Similar 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.
1135
1136Also note, if you are logging a container that contains custom class, make sure you have read Extending Library section below.
1137
1138 [![top] Goto Top](#table-of-contents)
1139
1140### Boost Logging
1141Prerequisite: Define macro `ELPP_BOOST_LOGGING`
1142
1143Easylogging++ supports some of boost templates. Following table shows the templates supported.
1144
1145|     *                               |          *                               |
1146|-------------------------------------|------------------------------------------|
1147| `boost::container::vector`          |  `boost::container::stable_vector`       |
1148| `boost::container::map`             |  `boost::container::flat_map`            |
1149| `boost::container::set`             |  `boost::container::flat_set`            |
1150| `boost::container::deque`           |  `boost::container::list`                |
1151| `boost::container::string`          |                                          |
1152
1153 [![top] Goto Top](#table-of-contents)
1154
1155### wxWidgets Logging
1156Prerequisite: Define macro `ELPP_WXWIDGETS_LOGGING`
1157
1158Easylogging++ supports some of wxWidgets templates.
1159
1160Following table shows the templates supported.
1161
1162|     *               |          *        |      *                    |      *                    |      *              |      *               |
1163|---------------------|-------------------|---------------------------|---------------------------|---------------------|----------------------|
1164| `wxString`          |  `wxVector`       |  `wxList`                 |  `wxString`               | `wxHashSet`         |  `wxHashMap`         |
1165
1166wxWidgets has its own way of declaring and defining some templates e.g, `wxList` where  you use `WX_DECLARE_LIST` macro to declare a list.
1167
1168In 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.
1169
1170```c++
1171// wxList example
1172WX_DECLARE_LIST(int, MyList);
1173WX_DEFINE_LIST(MyList);
1174// Following line does the trick
1175ELPP_WX_PTR_ENABLED(MyList);
1176
1177// wxHashSet example
1178WX_DECLARE_HASH_SET(int, wxIntegerHash, wxIntegerEqual, IntHashSet);
1179// Following line does the trick!
1180ELPP_WX_ENABLED(IntHashSet)
1181
1182// wxHashMap example
1183WX_DECLARE_STRING_HASH_MAP(wxString, MyHashMap);
1184// Following line does the trick
1185ELPP_WX_HASH_MAP_ENABLED(MyHashMap)
1186```
1187You may also have a look at wxWidgets sample
1188
1189 [![top] Goto Top](#table-of-contents)
1190
1191### Extending Library
1192You can extend this library using various callback handlers and inheritable classes.
1193
1194A perfect example of using these features is the logging server built with this library. It's called [Residue](https://github.com/amrayn/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.
1195
1196#### Logging Your Own Class
1197
1198You 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.
1199```c++
1200#include "easylogging++.h"
1201
1202INITIALIZE_EASYLOGGINGPP
1203class Integer : public el::Loggable {
1204public:
1205    Integer(int i) : m_underlyingInt(i) {
1206    }
1207    Integer& operator=(const Integer& integer) {
1208        m_underlyingInt = integer.m_underlyingInt;
1209        return *this;
1210    }
1211    // Following line does the trick!
1212    // Note: el::base::type::ostream_t is either std::wostream or std::ostream depending on unicode enabled or not
1213    virtual void log(el::base::type::ostream_t& os) const {
1214        os << m_underlyingInt;
1215    }
1216private:
1217    int m_underlyingInt;
1218};
1219
1220int main(void) {
1221    Integer count = 5;
1222    LOG(INFO) << count;
1223    return 0;
1224}
1225```
1226
1227 [![top] Goto Top](#table-of-contents)
1228
1229#### Logging Third-party Class
1230Let'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.
1231
1232Following sample shows a good usage:
1233```c++
1234#include "easylogging++.h"
1235
1236INITIALIZE_EASYLOGGINGPP
1237
1238class Integer {
1239public:
1240    Integer(int i) : m_underlyingInt(i) {
1241    }
1242    Integer& operator=(const Integer& integer) {
1243        m_underlyingInt = integer.m_underlyingInt;
1244        return *this;
1245    }
1246    int getInt(void) const { return m_underlyingInt; }
1247private:
1248    int m_underlyingInt;
1249};
1250
1251// Following line does the trick!
1252inline MAKE_LOGGABLE(Integer, integer, os) {
1253    os << integer.getInt();
1254    return os;
1255}
1256int main(void) {
1257    Integer count = 5;
1258    LOG(INFO) << count;
1259    return 0;
1260}
1261```
1262
1263Another very nice example (to log `std::chrono::system_clock::time_point`)
1264
1265```c++
1266inline MAKE_LOGGABLE(std::chrono::system_clock::time_point, when, os) {
1267    time_t t = std::chrono::system_clock::to_time_t(when);
1268    auto tm = std::localtime(&t);
1269    char buf[1024];
1270    strftime(buf,sizeof(buf), "%F %T (%Z)", tm);
1271    os << buf;
1272    return os;
1273}
1274```
1275
1276This may not be practically best implementation but you get the point.
1277
1278 > 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.
1279
1280 [![top] Goto Top](#table-of-contents)
1281
1282### Manually Flushing and Rolling Log Files
1283You 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).
1284
1285If 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&)`.
1286
1287 [![top] Goto Top](#table-of-contents)
1288
1289### Log Dispatch Callback
1290If 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<T>(const std::string&)`. If you wish to uninstall a pre-installed handler with same ID, you can do so by using `el::Helpers::uninstallLogDispatchCallback<T>(const std::string&)`
1291
1292You can use this feature to send it to custom destinations e.g, log stash or TCP client etc.
1293
1294You can also look at [send-to-network](/samples/send-to-network) sample for practical usage of this.
1295
1296```c++
1297// samples/send-to-network/network-logger.cpp
1298
1299#include "easylogging++.h"
1300
1301#include <boost/asio.hpp>
1302
1303INITIALIZE_EASYLOGGINGPP
1304
1305
1306class Client
1307{
1308    boost::asio::io_service* io_service;
1309    boost::asio::ip::tcp::socket socket;
1310
1311public:
1312    Client(boost::asio::io_service* svc, const std::string& host, const std::string& port)
1313        : io_service(svc), socket(*io_service)
1314    {
1315        boost::asio::ip::tcp::resolver resolver(*io_service);
1316        boost::asio::ip::tcp::resolver::iterator endpoint = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, port));
1317        boost::asio::connect(this->socket, endpoint);
1318    };
1319
1320    void send(std::string const& message) {
1321        socket.send(boost::asio::buffer(message));
1322    }
1323};
1324
1325class NetworkDispatcher : public el::LogDispatchCallback
1326{
1327public:
1328    void updateServer(const std::string& host, int port) {
1329        m_client = std::unique_ptr<Client>(new Client(&m_svc, host, std::to_string(port)));
1330    }
1331protected:
1332  void handle(const el::LogDispatchData* data) noexcept override {
1333      m_data = data;
1334      // Dispatch using default log builder of logger
1335      dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(),
1336                 m_data->dispatchAction() == el::base::DispatchAction::NormalLog));
1337  }
1338private:
1339  const el::LogDispatchData* m_data;
1340  boost::asio::io_service m_svc;
1341  std::unique_ptr<Client> m_client;
1342
1343  void dispatch(el::base::type::string_t&& logLine) noexcept
1344  {
1345      m_client->send(logLine);
1346  }
1347};
1348
1349
1350int main() {
1351    el::Helpers::installLogDispatchCallback<NetworkDispatcher>("NetworkDispatcher");
1352    // you can uninstall default one by
1353    // el::Helpers::uninstallLogDispatchCallback<el::base::DefaultLogDispatchCallback>("DefaultLogDispatchCallback");
1354    // Set server params
1355    NetworkDispatcher* dispatcher = el::Helpers::logDispatchCallback<NetworkDispatcher>("NetworkDispatcher");
1356    dispatcher->setEnabled(true);
1357    dispatcher->updateServer("127.0.0.1", 9090);
1358
1359    // Start logging and normal program...
1360    LOG(INFO) << "First network log";
1361
1362    // You can even use a different logger, say "network" and send using a different log pattern
1363}
1364```
1365
1366 > DO NOT LOG ANYTHING IN THIS HANDLER OR YOU WILL END UP IN INFINITE-LOOP
1367
1368 [![top] Goto Top](#table-of-contents)
1369
1370### Logger Registration Callback
1371If 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/amrayn/easyloggingpp/blob/master/samples/STL/new-logger-registration-callback.cpp) as basis.
1372
1373 > DO NOT LOG ANYTHING IN THIS HANDLER
1374
1375 [![top] Goto Top](#table-of-contents)
1376
1377### Asynchronous Logging
1378Prerequisite: Define macro `ELPP_EXPERIMENTAL_ASYNC`
1379
1380Asynchronous 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/amrayn/easyloggingpp/issues/202). Reporting issues always help for constant improvements.
1381
1382Please note:
1383* Asynchronous will only work with few compilers (it purely uses `std::thread`)
1384* Compiler should support `std::this_thread::sleep_for`. This restriction may (or may not) be removed in future (stable) version of asynchronous logging.
1385* You should not rely on asynchronous logging in production, this is because feature is in experimental stages.
1386
1387 [![top] Goto Top](#table-of-contents)
1388
1389### Helper Classes
1390There are static helper classes available to make it easy to do stuffs;
1391
1392 * `el::Helpers`
1393 * `el::Loggers`
1394
1395You can do various cool stuffs using functions in these classes, see [this issue](https://github.com/amrayn/easyloggingpp/issues/210) for instance.
1396
1397 [![top] Goto Top](#table-of-contents)
1398
1399# Contribution
1400### Submitting Patches
1401You 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.
1402
1403 [![top] Goto Top](#table-of-contents)
1404
1405### Reporting a Bug
1406If you have found a bug and wish to report it, feel free to do so at [github issue tracker](https://github.com/amrayn/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;
1407* Platform (OS, Compiler)
1408* Log file location
1409* Macros defined (on compilation) OR simple compilation
1410* Please assign issue label.
1411
1412Try to provide as much information as possible. Any bug with no clear information will be ignored and closed.
1413
1414 [![top] Goto Top](#table-of-contents)
1415
1416# Compatibility
1417
1418Easylogging++ requires a decent C++0x compliant 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
1419
1420| *****   |     Compiler/Platform     |      Notes                                                                                                                                               |
1421|---------|---------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
1422|![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.  |
1423|![llvm]  | Clang++ 3.1+              | Stack trace logging only with gcc compliant.                                                                                                             |
1424|![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                |
1425|![vcpp]  | Visual C++ 11.0+          | Tested with VS2012, VS2013; Use of argument templates instead of variadic templates. CRT warnings control. No stack trace logging.                       |
1426|![mingw] | MinGW                     | (gcc version 4.7+) Workarounds to support: Mutex wrapper, no stack trace logging. No thread ID on windows                                                |
1427|![tdm]   | TDM-GCC 4.7.1             | Tested with TDM-GCC 4.7.1 32 and 64 bit compilers                                                                                                        |
1428|![cygwin]| Cygwin                    | Tested with gcc version 4.8+                                                                                                                             |
1429|![devcpp]| Dev C++ 5.4+              | Tested with Dev-C++ 5.4.2 using TDM-GCC 4.7.1 32 & 64-bit compilers                                                                                      |
1430
1431Operating systems that have been tested are shown in table below. Easylogging++ should work on other major operating systems that are not in the list.
1432
1433| *****         | Operating System       |   Notes                                                                             |
1434|---------------|------------------------|-------------------------------------------------------------------------------------|
1435|![win10]        | Windows 10            | Tested on 64-bit, should also work on 32-bit                                        |
1436|![win8]        | Windows 8              | Tested on 64-bit, should also work on 32-bit                                        |
1437|![win7]        | Windows 7              | Tested on 64-bit, should also work on 32-bit                                        |
1438|![winxp]       | Windows XP             | Tested on 32-bit, should also work on 64-bit                                        |
1439|![mac]         | Mac OSX                | Clang++ 3.1, g++ (You need `-std=c++11 -stdlib=libc++` to successfully compile)     |
1440|![sl]          | Scientific Linux 6.2   | Tested using Intel C++ 13.1.3 (gcc version 4.4.6 compatibility)                     |
1441|![mint]        | Linux Mint 14          | 64-bit, mainly developed on this machine using all compatible linux compilers       |
1442|![fedora]      | Fedora 19              | 64-bit, using g++ 4.8.1                                                             |
1443|![ubuntu]      | Ubuntu 13.04           | 64-bit, using g++ 4.7.3 (libstdc++6-4.7-dev)                                        |
1444|![freebsd]     | FreeBSD                | (from github user)                                                                  |
1445|![android]     | Android                | Tested with C4droid (g++) on Galaxy Tab 2                                           |
1446|![raspberrypi] | RaspberryPi 7.6        | Tested with 7.6.2-1.1 (gcc version 4.9.1 (Raspbian 4.9.1-1)) by contributor         |
1447|![solaris]     | Solaris i86            | Tested by contributor                                                               |
1448|![aix]     | IBM AIX            | Support added by contributor                                                               |
1449
1450Easylogging++ has also been tested with following C++ libraries;
1451
1452| *****       | Library                |    Notes                                                                            |
1453|-------------|------------------------|-------------------------------------------------------------------------------------|
1454|![qt]        | Qt                     | Tested with Qt 4.6.2, Qt 5 and Qt 5.5 (with C++0x and C++11)                        |
1455|![boost]     | Boost                  | Tested with boost 1.51                                                              |
1456|![wxwidgets] | wxWidgets              | Tested with wxWidgets 2.9.4                                                         |
1457|![gtkmm]     | gtkmm                  | Tested with gtkmm 2.4                                                               |
1458
1459 [![top] Goto Top](#table-of-contents)
1460
1461 ## Build Matrix
1462
1463 | Branch | Platform | Build Status |
1464 | -------- |:------------:|:------------:|
1465 | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `clang++` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/develop/1)](https://travis-ci.org/amrayn/easyloggingpp) |
1466 | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-4.9` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/develop/2)](https://travis-ci.org/amrayn/easyloggingpp) |
1467 | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-5` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/develop/3)](https://travis-ci.org/amrayn/easyloggingpp) |
1468 | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-6` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/develop/4)](https://travis-ci.org/amrayn/easyloggingpp) |
1469 | `develop` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-7` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/develop/5)](https://travis-ci.org/amrayn/easyloggingpp) |
1470 | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `clang++` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/master/1)](https://travis-ci.org/amrayn/easyloggingpp) |
1471 | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-4.9` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/master/2)](https://travis-ci.org/amrayn/easyloggingpp) |
1472 | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-5` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/master/3)](https://travis-ci.org/amrayn/easyloggingpp) |
1473 | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-6` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/master/4)](https://travis-ci.org/amrayn/easyloggingpp) |
1474 | `master` | GNU/Linux 4.4 / Ubuntu 4.8.4 64-bit / `g++-7` | [![Build Status](https://travis-matrix-badges.herokuapp.com/repos/amrayn/easyloggingpp/branches/master/5)](https://travis-ci.org/amrayn/easyloggingpp) |
1475
1476  [![top] Goto Top](#table-of-contents)
1477
1478# Licence
1479```
1480The MIT License (MIT)
1481
1482Copyright (c) 2012-2018 Amrayn Web Services
1483Copyright (c) 2012-2018 @abumusamq
1484
1485https://github.com/amrayn/
1486https://amrayn.com
1487https://muflihun.com
1488
1489Permission is hereby granted, free of charge, to any person obtaining a copy of
1490this software and associated documentation files (the "Software"), to deal in
1491the Software without restriction, including without limitation the rights to
1492use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
1493the Software, and to permit persons to whom the Software is furnished to do so,
1494subject to the following conditions:
1495
1496The above copyright notice and this permission notice shall be included in all
1497copies or substantial portions of the Software.
1498
1499THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1500IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
1501FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
1502COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
1503IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1504CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1505```
1506
1507 [![top] Goto Top](#table-of-contents)
1508
1509# Disclaimer
1510Icons 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.
1511
1512"Pencil +" icon is Easylogging++ logo and should only be used where giving credit to Easylogging++ library.
1513
1514
1515 [![top] Goto Top](#table-of-contents)
1516
1517  [banner]: https://amrayn.github.io/easyloggingpp/images/banner.png?v=4
1518  [ubuntu]: https://amrayn.github.io/easyloggingpp/images/icons/ubuntu.png?v=2
1519  [mint]: https://amrayn.github.io/easyloggingpp/images/icons/linux-mint.png?v=2
1520  [freebsd]: https://amrayn.github.io/easyloggingpp/images/icons/free-bsd.png?v=2
1521  [sl]: https://amrayn.github.io/easyloggingpp/images/icons/scientific-linux.png?v=2
1522  [fedora]: https://amrayn.github.io/easyloggingpp/images/icons/fedora.png?v=3
1523  [mac]: https://amrayn.github.io/easyloggingpp/images/icons/mac-osx.png?v=2
1524  [winxp]: https://amrayn.github.io/easyloggingpp/images/icons/windowsxp.png?v=2
1525  [win7]: https://amrayn.github.io/easyloggingpp/images/icons/windows7.png?v=2
1526  [win8]: https://amrayn.github.io/easyloggingpp/images/icons/windows8.png?v=2
1527  [win10]: https://amrayn.github.io/easyloggingpp/images/icons/windows10.png?v=2
1528  [qt]: https://amrayn.github.io/easyloggingpp/images/icons/qt.png?v=3
1529  [boost]: https://amrayn.github.io/easyloggingpp/images/icons/boost.png?v=3
1530  [wxwidgets]: https://amrayn.github.io/easyloggingpp/images/icons/wxwidgets.png?v=3
1531  [devcpp]: https://amrayn.github.io/easyloggingpp/images/icons/devcpp.png?v=3
1532  [gtkmm]: https://amrayn.github.io/easyloggingpp/images/icons/gtkmm.png?v=3
1533  [tdm]: https://amrayn.github.io/easyloggingpp/images/icons/tdm.png?v=3
1534  [raspberrypi]: https://amrayn.github.io/easyloggingpp/images/icons/raspberry-pi.png?v=3
1535  [solaris]: https://amrayn.github.io/easyloggingpp/images/icons/solaris.png?v=3
1536  [aix]: https://amrayn.github.io/easyloggingpp/images/icons/aix.png?v=4
1537
1538
1539  [gcc]: https://amrayn.github.io/easyloggingpp/images/icons/gcc.png?v=4
1540  [mingw]: https://amrayn.github.io/easyloggingpp/images/icons/mingw.png?v=2
1541  [cygwin]: https://amrayn.github.io/easyloggingpp/images/icons/cygwin.png?v=2
1542  [vcpp]: https://amrayn.github.io/easyloggingpp/images/icons/vcpp.png?v=2
1543  [llvm]: https://amrayn.github.io/easyloggingpp/images/icons/llvm.png?v=2
1544  [intel]: https://amrayn.github.io/easyloggingpp/images/icons/intel.png?v=2
1545  [android]: https://amrayn.github.io/easyloggingpp/images/icons/android.png?v=2
1546  [manual]: https://amrayn.github.io/easyloggingpp/images/help.png?v=3
1547  [download]: https://amrayn.github.io/easyloggingpp/images/download.png?v=2
1548  [samples]: https://amrayn.github.io/easyloggingpp/images/sample.png?v=2
1549  [notes]: https://amrayn.github.io/easyloggingpp/images/notes.png?v=4
1550  [top]: https://amrayn.github.io/easyloggingpp/images/up.png?v=4
1551  [www]: https://amrayn.github.io/easyloggingpp/images/logo-www.png?v=6
1552