g3log/g3log_usage/index.html
2025-06-10 14:30:34 +00:00

713 lines
24 KiB
HTML

<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="author" content="Kjell Hedstrom">
<link rel="canonical" href="https://kjellkod.github.io/g3log/g3log_usage/">
<link rel="icon" href="../assets/images/favicon.png">
<meta name="generator" content="mkdocs-1.6.1, mkdocs-material-9.6.14">
<title>G3log usage - G3log, an asynchronous "crash-safe" logger</title>
<link rel="stylesheet" href="../assets/stylesheets/main.342714a4.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i%7CRoboto+Mono:400,400i,700,700i&display=fallback">
<style>:root{--md-text-font:"Roboto";--md-code-font:"Roboto Mono"}</style>
<script>__md_scope=new URL("..",location),__md_hash=e=>[...e].reduce(((e,_)=>(e<<5)-e+_.charCodeAt(0)),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script>
</head>
<body dir="ltr">
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" for="__drawer"></label>
<div data-md-component="skip">
<a href="#how-to-use-g3log" class="md-skip">
Skip to content
</a>
</div>
<div data-md-component="announce">
</div>
<header class="md-header md-header--shadow" data-md-component="header">
<nav class="md-header__inner md-grid" aria-label="Header">
<a href=".." title="G3log, an asynchronous &#34;crash-safe&#34; logger" class="md-header__button md-logo" aria-label="G3log, an asynchronous "crash-safe" logger" data-md-component="logo">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg>
</a>
<label class="md-header__button md-icon" for="__drawer">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3zm0 5h18v2H3zm0 5h18v2H3z"/></svg>
</label>
<div class="md-header__title" data-md-component="header-title">
<div class="md-header__ellipsis">
<div class="md-header__topic">
<span class="md-ellipsis">
G3log, an asynchronous "crash-safe" logger
</span>
</div>
<div class="md-header__topic" data-md-component="header-topic">
<span class="md-ellipsis">
G3log usage
</span>
</div>
</div>
</div>
<script>var palette=__md_get("__palette");if(palette&&palette.color){if("(prefers-color-scheme)"===palette.color.media){var media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']");palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent")}for(var[key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script>
<label class="md-header__button md-icon" for="__search">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.52 6.52 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5"/></svg>
</label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" aria-label="Search" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="search-query" required>
<label class="md-search__icon md-icon" for="__search">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.52 6.52 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg>
</label>
<nav class="md-search__options" aria-label="Search">
<button type="reset" class="md-search__icon md-icon" title="Clear" aria-label="Clear" tabindex="-1">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>
</button>
</nav>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" tabindex="0" data-md-scrollfix>
<div class="md-search-result" data-md-component="search-result">
<div class="md-search-result__meta">
Initializing search
</div>
<ol class="md-search-result__list" role="presentation"></ol>
</div>
</div>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container" data-md-component="container">
<main class="md-main" data-md-component="main">
<div class="md-main__inner md-grid">
<div class="md-sidebar md-sidebar--primary" data-md-component="sidebar" data-md-type="navigation" >
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" aria-label="Navigation" data-md-level="0">
<label class="md-nav__title" for="__drawer">
<a href=".." title="G3log, an asynchronous &#34;crash-safe&#34; logger" class="md-nav__button md-logo" aria-label="G3log, an asynchronous "crash-safe" logger" data-md-component="logo">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54"/></svg>
</a>
G3log, an asynchronous "crash-safe" logger
</label>
<ul class="md-nav__list" data-md-scrollfix>
<li class="md-nav__item">
<a href=".." class="md-nav__link">
<span class="md-ellipsis">
Introduction to G3log
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../g3log.md" class="md-nav__link">
<span class="md-ellipsis">
G3log usage
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../API/" class="md-nav__link">
<span class="md-ellipsis">
API description
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../API_custom_formatting/" class="md-nav__link">
<span class="md-ellipsis">
API for custom log formatting
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../building/" class="md-nav__link">
<span class="md-ellipsis">
Configure, Build, Package, Install and Test
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../contributing/" class="md-nav__link">
<span class="md-ellipsis">
License and contribution
</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="sidebar" data-md-type="toc" >
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary" aria-label="Table of contents">
<label class="md-nav__title" for="__toc">
<span class="md-nav__icon md-icon"></span>
Table of contents
</label>
<ul class="md-nav__list" data-md-component="toc" data-md-scrollfix>
<li class="md-nav__item">
<a href="#example-usage" class="md-nav__link">
<span class="md-ellipsis">
Example USAGE
</span>
</a>
<nav class="md-nav" aria-label="Example USAGE">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#optional-to-use-either-streaming-or-printf-like-syntax" class="md-nav__link">
<span class="md-ellipsis">
Optional to use either streaming or printf-like syntax
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
<a href="#what-g3log-is" class="md-nav__link">
<span class="md-ellipsis">
What g3Log is
</span>
</a>
<nav class="md-nav" aria-label="What g3Log is">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#conditional-logging" class="md-nav__link">
<span class="md-ellipsis">
Conditional logging
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#design-by-contract" class="md-nav__link">
<span class="md-ellipsis">
Design-by-Contract
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#detailed-api-documentation" class="md-nav__link">
<span class="md-ellipsis">
Detailed API documentation
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
<a href="#benefits-you-get-when-using-g3log" class="md-nav__link">
<span class="md-ellipsis">
Benefits you get when using g3log
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#g3log-with-sinks" class="md-nav__link">
<span class="md-ellipsis">
G3log with sinks
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#adding-and-removing-sinks" class="md-nav__link">
<span class="md-ellipsis">
Adding and Removing Sinks
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#code-examples" class="md-nav__link">
<span class="md-ellipsis">
Code Examples
</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content" data-md-component="content">
<article class="md-content__inner md-typeset">
<p><a href="../">introduction</a> | <a href="./"><strong>detailed information</strong></a> | <a href="../building/">Configure &amp; Build</a> | <a href="../API/">API description</a> | <a href="../API_custom_formatting/">Custom log formatting</a></p>
<h1 id="how-to-use-g3log">How to use g3log</h1>
<p>G3log is an asynchronous logger with dynamic sinks</p>
<h2 id="example-usage">Example USAGE</h2>
<h4 id="optional-to-use-either-streaming-or-printf-like-syntax">Optional to use either streaming or printf-like syntax</h4>
<pre><code>LOG(INFO) &lt;&lt; &quot;streaming API is as easy as ABC or &quot; &lt;&lt; 123;
LOGF(WARNING, &quot;Printf-style syntax is also %s&quot;, &quot;available&quot;);
</code></pre>
<h2 id="what-g3log-is"><a name="what-g3log-is">What g3Log is</a></h2>
<ul>
<li><strong><em>G3log</em></strong> is the acting name for the third version of g2log and it stands for <strong>g3log with dynamic sinks</strong></li>
<li>G3log is an asynchronous, "crash-safe" logger. You can read more about it here <a href="http://www.codeproject.com/Articles/288827/g2log-An-efficient-asynchronous-logger-using-Cplus">[g2log version]</a></li>
<li>You can choose to use the default log receiver which saves all LOG calls to file, <strong>or</strong> you can choose to use your own custom made log receiver(s), <strong>or</strong> both, <strong>or</strong> as many sinks as you need.</li>
</ul>
<h4 id="conditional-logging"><a name="#conditional-logging">Conditional logging</a></h4>
<pre><code>int less = 1; int more = 2
LOG_IF(INFO, (less&lt;more)) &lt;&lt;"If [true], then this text will be logged";
// or with printf-like syntax
LOGF_IF(INFO, (less&lt;more), "if %d&lt;%d then this text will be logged", less,more);
</code></pre>
<h4 id="design-by-contract"><a name="design-by-contract">Design-by-Contract</a></h4>
<p><em>CHECK(false)</em> will trigger a "fatal" message. It will be logged, and then the
application will exit.</p>
<pre><code>CHECK(less != more); // not FATAL
CHECK(less &gt; more) &lt;&lt; &quot;CHECK(false) triggers a FATAL message&quot;;
</code></pre>
<h3 id="detailed-api-documentation">Detailed API documentation</h3>
<p>Please look at <a href="../API/">API.md</a> for detailed API documentation</p>
<h2 id="benefits-you-get-when-using-g3log"><a name="benefits-with-g3log">Benefits you get when using g3log</a></h2>
<ol>
<li>
<p>Easy to use, clean syntax and a blazing fast logger.</p>
</li>
<li>
<p>All the slow log I/O disk access is done in a background thread. This ensures that the LOG caller can immediately continue with other tasks and do not have to wait for the LOG call to finish.</p>
</li>
<li>
<p>G3log provides logging, Design-by-Contract [#CHECK], and flush of log to file at
shutdown. Buffered logs will be written to the sink before the application shuts down.</p>
</li>
<li>
<p>It is thread safe, so using it from multiple threads is completely fine.</p>
</li>
<li>
<p>It is <em>CRASH SAFE</em>. It will save the made logs to the sink before it shuts down.
The logger will catch certain fatal events <em>(Linux/OSX: signals, Windows: fatal OS exceptions and signals)</em> , so if your application crashes due to, say a segmentation fault, <em>SIGSEGV</em>, it will log and save the crash and all previously buffered log entries before exiting.</p>
</li>
<li>
<p>It is cross platform. Tested and used by me or by clients on OSX, Windows, Ubuntu, CentOS</p>
</li>
<li>
<p>G3log and G2log are used worldwide in commercial products as well as hobby projects. G2log was introduced in early 2011 and is now retired.</p>
</li>
<li>
<p>The code is given for free as public domain. This gives the option to change, use, and do whatever with it, no strings attached.</p>
</li>
<li>
<p><em><a href="https://github.com/KjellKod/g3log">g3log</a></em> : is made to facilitate easy adding of custom log receivers. Its tested on at least the following platforms with <strong>Linux</strong>(Clang/gcc), <strong>Windows</strong> (mingw, visual studio) and <strong>OSX</strong>. My recommendation is to go with g3log if you have full C++17 support </p>
</li>
</ol>
<p>C++11 support up to version: https://github.com/KjellKod/g3log/releases/tag/1.3.1).</p>
<p>C++14 support up to version: https://github.com/KjellKod/g3log/releases/tag/1.3.4</p>
<h2 id="g3log-with-sinks"><a name="g3log-with-sinks">G3log with sinks</a></h2>
<p><a href="http://en.wikipedia.org/wiki/Sink_(computing)">Sinks</a> are receivers of LOG calls. G3log comes with a default sink (<em>the same as g3log uses</em>) that can be used to save log to file. A sink can be of <em>any</em> class type without restrictions as long as it can either receive a LOG message as a <em>std::string</em> <strong>or</strong> as a <em>g3::LogMessageMover</em>.</p>
<p>The <em>std::string</em> comes pre-formatted. The <em>g3::LogMessageMover</em> is a wrapped struct that contains the raw data for custom handling in your own sink.</p>
<p>A sink is <em>owned</em> by the g3log and is added to the logger inside a <code>std::unique_ptr</code>. The sink can be called though its public API through a <em>handler</em> which will asynchronously forward the call to the receiving sink.</p>
<p>It is <a name="crazy-simple">crazy simple to create a custom sink</a>. This example show what is needed to make a custom sink that is using custom log formatting but only using that
for adding color to the default log formatting. The sink forwards the colored log to cout</p>
<pre><code class="language-cpp">// in file Customsink.hpp
#pragma once
#include &lt;string&gt;
#include &lt;iostream&gt;
#include &lt;g3log/logmessage.hpp&gt;
struct CustomSink {
// Linux xterm color
// http://stackoverflow.com/questions/2616906/how-do-i-output-coloured-text-to-a-linux-terminal
enum FG_Color {YELLOW = 33, RED = 31, GREEN=32, WHITE = 97};
FG_Color GetColor(const LEVELS level) const {
if (level.value == WARNING.value) { return YELLOW; }
if (level.value == DEBUG.value) { return GREEN; }
if (g3::internal::wasFatal(level)) { return RED; }
return WHITE;
}
void ReceiveLogMessage(g3::LogMessageMover logEntry) {
auto level = logEntry.get()._level;
auto color = GetColor(level);
std::cout &lt;&lt; &quot;\033[&quot; &lt;&lt; color &lt;&lt; &quot;m&quot;
&lt;&lt; logEntry.get().toString() &lt;&lt; &quot;\033[m&quot; &lt;&lt; std::endl;
}
};
// in main.cpp, main() function
auto sinkHandle = logworker-&gt;addSink(std::make_unique&lt;CustomSink&gt;(),
&amp;CustomSink::ReceiveLogMessage);
</code></pre>
<h2 id="adding-and-removing-sinks">Adding and Removing Sinks</h2>
<p>You can safely remove and add sinks during the running of your program. </p>
<p><strong>Keep in mind</strong></p>
<ul>
<li><em>Initialization of the logger should happen before you have started any other threads that may call the logger.</em> </li>
<li><em>Destruction of the logger (RAII concept) should happen AFTER shutdown of other threads that are calling the logger.</em></li>
</ul>
<p><strong>Adding Sinks</strong></p>
<pre><code class="language-cpp"> auto sinkHandle1 = logworker-&gt;addSink(std::make_unique&lt;CustomSink&gt;(),
&amp;CustomSink::ReceiveLogMessage);
auto sinkHandle2 = logworker-&gt;addDefaultLogger(argv[0],
path_to_log_file);
logworker-&gt;removeSink(std::move(sinkHandle1)); // this will in a thread-safe manner remove the sinkHandle1
logworker-&gt;removeAllSinks(); // this will in a thread-safe manner remove any sinks.
</code></pre>
<p><strong>More sinks</strong> can be found in the repository <strong><a href="https://github.com/KjellKod/g3sinks">github.com/KjellKod/g3sinks</a></strong>.</p>
<h2 id="code-examples"><a name="code-examples">Code Examples</a></h2>
<p>Example usage where a <a name="custom-sink">custom sink</a> is added. A function is called though the sink handler to the actual sink object.</p>
<pre><code class="language-cpp">// main.cpp
#include &lt;g3log/g3log.hpp&gt;
#include &lt;g3log/logworker.hpp&gt;
#include &lt;memory&gt;
#include &quot;CustomSink.h&quot;
int main(int argc, char**argv) {
using namespace g3;
std::unique_ptr&lt;LogWorker&gt; logworker{ LogWorker::createLogWorker() };
auto sinkHandle = logworker-&gt;addSink(std::make_unique&lt;CustomSink&gt;(),
&amp;CustomSink::ReceiveLogMessage);
// initialize the logger before it can receive LOG calls
initializeLogging(logworker.get());
LOG(WARNING) &lt;&lt; &quot;This log call, may or may not happend before&quot;
&lt;&lt; &quot;the sinkHandle-&gt;call below&quot;;
// You can call in a thread safe manner public functions on your sink
// The call is asynchronously executed on your custom sink.
std::future&lt;void&gt; received = sinkHandle-&gt;call(&amp;CustomSink::Foo,
param1, param2);
// If the LogWorker is initialized then at scope exit the g3::internal::shutDownLogging() will be called.
// This is important since it protects from LOG calls from static or other entities that will go out of
// scope at a later time.
//
// It can also be called manually:
g3::internal::shutDownLogging();
}
// some_file.cpp : To show how easy it is to get the logger to work
// in other parts of your software
#include &lt;g3log/g3log.hpp&gt;
void SomeFunction() {
...
LOG(INFO) &lt;&lt; &quot;Hello World&quot;;
}
</code></pre>
<p>Example usage where a the <a name="default-file-logger">default file logger</a> is used <strong>and</strong> a custom sink is added</p>
<pre><code class="language-cpp">// main.cpp
#include &lt;g3log/g3log.hpp&gt;
#include &lt;g3log/logworker.hpp&gt;
#include &lt;memory&gt;
#include &quot;CustomSink.h&quot;
int main(int argc, char**argv) {
using namespace g3;
auto worker = LogWorker::createLogWorker();
auto defaultHandler = worker-&gt;addDefaultLogger(argv[0],
path_to_log_file);
// logger is initialized
g3::initializeLogging(worker.get());
LOG(DEBUG) &lt;&lt; &quot;Make log call, then add another sink&quot;;
worker-&gt;addSink(std::make_unique&lt;CustomSink&gt;(),
&amp;CustomSink::ReceiveLogMessage);
...
}
</code></pre>
<p><a href="../">introduction</a> | <a href="./"><strong>detailed information</strong></a> | <a href="../building/">Configure &amp; Build</a> | <a href="../API/">API description</a> | <a href="../API_custom_formatting/">Custom log formatting</a></p>
</article>
</div>
<script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-copyright">
Made with
<a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener">
Material for MkDocs
</a>
</div>
</div>
</div>
</footer>
</div>
<div class="md-dialog" data-md-component="dialog">
<div class="md-dialog__inner md-typeset"></div>
</div>
<script id="__config" type="application/json">{"base": "..", "features": [], "search": "../assets/javascripts/workers/search.d50fe291.min.js", "tags": null, "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}, "version": null}</script>
<script src="../assets/javascripts/bundle.13a4f30d.min.js"></script>
</body>
</html>