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