README.rst 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. Google Logging Library
  2. ======================
  3. |Linux Github actions| |Windows Github actions| |macOS Github actions| |Codecov|
  4. Google Logging (glog) is a C++14 library that implements application-level
  5. logging. The library provides logging APIs based on C++-style streams and
  6. various helper macros.
  7. .. role:: cmake(code)
  8. :language: cmake
  9. .. role:: cmd(code)
  10. :language: bash
  11. .. role:: cpp(code)
  12. :language: cpp
  13. .. role:: bazel(code)
  14. :language: starlark
  15. Getting Started
  16. ---------------
  17. You can log a message by simply streaming things to ``LOG``\ (<a
  18. particular `severity level <#severity-levels>`__>), e.g.,
  19. .. code:: cpp
  20. #include <glog/logging.h>
  21. int main(int argc, char* argv[]) {
  22. // Initialize Google’s logging library.
  23. google::InitGoogleLogging(argv[0]);
  24. // ...
  25. LOG(INFO) << "Found " << num_cookies << " cookies";
  26. }
  27. For a detailed overview of glog features and their usage, please refer
  28. to the `user guide <#user-guide>`__.
  29. .. contents:: Table of Contents
  30. Building from Source
  31. --------------------
  32. glog supports multiple build systems for compiling the project from
  33. source: `Bazel <#bazel>`__, `CMake <#cmake>`__, `vcpkg <#vcpkg>`__, and `conan <#conan>`__.
  34. Bazel
  35. ~~~~~
  36. To use glog within a project which uses the
  37. `Bazel <https://bazel.build/>`__ build tool, add the following lines to
  38. your ``WORKSPACE`` file:
  39. .. code:: bazel
  40. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
  41. http_archive(
  42. name = "com_github_gflags_gflags",
  43. sha256 = "34af2f15cf7367513b352bdcd2493ab14ce43692d2dcd9dfc499492966c64dcf",
  44. strip_prefix = "gflags-2.2.2",
  45. urls = ["https://github.com/gflags/gflags/archive/v2.2.2.tar.gz"],
  46. )
  47. http_archive(
  48. name = "com_github_google_glog",
  49. sha256 = "122fb6b712808ef43fbf80f75c52a21c9760683dae470154f02bddfc61135022",
  50. strip_prefix = "glog-0.6.0",
  51. urls = ["https://github.com/google/glog/archive/v0.6.0.zip"],
  52. )
  53. You can then add :bazel:`@com_github_google_glog//:glog` to the deps section
  54. of a :bazel:`cc_binary` or :bazel:`cc_library` rule, and :code:`#include
  55. <glog/logging.h>` to include it in your source code. Here’s a simple example:
  56. .. code:: bazel
  57. cc_binary(
  58. name = "main",
  59. srcs = ["main.cc"],
  60. deps = ["@com_github_google_glog//:glog"],
  61. )
  62. CMake
  63. ~~~~~
  64. glog also supports CMake that can be used to build the project on a wide
  65. range of platforms. If you don’t have CMake installed already, you can
  66. download it for from CMake’s `official
  67. website <http://www.cmake.org>`__.
  68. CMake works by generating native makefiles or build projects that can be
  69. used in the compiler environment of your choice. You can either build
  70. glog with CMake as a standalone project or it can be incorporated into
  71. an existing CMake build for another project.
  72. Building glog with CMake
  73. ^^^^^^^^^^^^^^^^^^^^^^^^
  74. When building glog as a standalone project, on Unix-like systems with
  75. GNU Make as build tool, the typical workflow is:
  76. 1. Get the source code and change to it. e.g., cloning with git:
  77. .. code:: bash
  78. git clone https://github.com/google/glog.git
  79. cd glog
  80. 2. Run CMake to configure the build tree.
  81. .. code:: bash
  82. cmake -S . -B build -G "Unix Makefiles"
  83. CMake provides different generators, and by default will pick the most
  84. relevant one to your environment. If you need a specific version of Visual
  85. Studio, use :cmd:`cmake . -G <generator-name>`, and see :cmd:`cmake --help`
  86. for the available generators. Also see :cmd:`-T <toolset-name>`, which can
  87. be used to request the native x64 toolchain with :cmd:`-T host=x64`.
  88. 3. Afterwards, generated files can be used to compile the project.
  89. .. code:: bash
  90. cmake --build build
  91. 4. Test the build software (optional).
  92. .. code:: bash
  93. cmake --build build --target test
  94. 5. Install the built files (optional).
  95. .. code:: bash
  96. cmake --build build --target install
  97. Consuming glog in a CMake Project
  98. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  99. If you have glog installed in your system, you can use the CMake command
  100. :cmake:`find_package` to build against glog in your CMake Project as follows:
  101. .. code:: cmake
  102. cmake_minimum_required (VERSION 3.16)
  103. project (myproj VERSION 1.0)
  104. find_package (glog 0.6.0 REQUIRED)
  105. add_executable (myapp main.cpp)
  106. target_link_libraries (myapp glog::glog)
  107. Compile definitions and options will be added automatically to your
  108. target as needed.
  109. Incorporating glog into a CMake Project
  110. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  111. You can also use the CMake command :cmake:`add_subdirectory` to include glog
  112. directly from a subdirectory of your project by replacing the
  113. :cmake:`find_package` call from the previous example by
  114. :cmake:`add_subdirectory`. The :cmake:`glog::glog` target is in this case an
  115. :cmake:`ALIAS` library target for the ``glog`` library target.
  116. Again, compile definitions and options will be added automatically to
  117. your target as needed.
  118. vcpkg
  119. ~~~~~
  120. You can download and install glog using the `vcpkg
  121. <https://github.com/Microsoft/vcpkg>`__ dependency manager:
  122. .. code:: bash
  123. git clone https://github.com/Microsoft/vcpkg.git
  124. cd vcpkg
  125. ./bootstrap-vcpkg.sh
  126. ./vcpkg integrate install
  127. ./vcpkg install glog
  128. The glog port in vcpkg is kept up to date by Microsoft team members and
  129. community contributors. If the version is out of date, please create an
  130. issue or pull request on the vcpkg repository.
  131. conan
  132. ~~~~~
  133. You can download and install glog using the `conan
  134. <https://conan.io>`__ package manager:
  135. .. code:: bash
  136. pip install conan
  137. conan install -r conancenter glob/<glob-version>@
  138. The glog recipe in conan center is kept up to date by conan center index community
  139. contributors. If the version is out of date, please create an
  140. issue or pull request on the `conan-center-index
  141. <https://github.com/conan-io/conan-center-index>`__ repository.
  142. User Guide
  143. ----------
  144. glog defines a series of macros that simplify many common logging tasks.
  145. You can log messages by severity level, control logging behavior from
  146. the command line, log based on conditionals, abort the program when
  147. expected conditions are not met, introduce your own verbose logging
  148. levels, customize the prefix attached to log messages, and more.
  149. Following sections describe the functionality supported by glog. Please note
  150. this description may not be complete but limited to the most useful ones. If you
  151. want to find less common features, please check header files under `src/glog
  152. <src/glog>`__ directory.
  153. Severity Levels
  154. ~~~~~~~~~~~~~~~
  155. You can specify one of the following severity levels (in increasing
  156. order of severity): ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL``.
  157. Logging a ``FATAL`` message terminates the program (after the message is
  158. logged). Note that messages of a given severity are logged not only in
  159. the logfile for that severity, but also in all logfiles of lower
  160. severity. E.g., a message of severity ``FATAL`` will be logged to the
  161. logfiles of severity ``FATAL``, ``ERROR``, ``WARNING``, and ``INFO``.
  162. The ``DFATAL`` severity logs a ``FATAL`` error in debug mode (i.e.,
  163. there is no ``NDEBUG`` macro defined), but avoids halting the program in
  164. production by automatically reducing the severity to ``ERROR``.
  165. Unless otherwise specified, glog writes to the filename
  166. ``/tmp/\<program name\>.\<hostname\>.\<user name\>.log.\<severity level\>.\<date\>-\<time\>.\<pid\>``
  167. (e.g.,
  168. ``/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474``).
  169. By default, glog copies the log messages of severity level ``ERROR`` or
  170. ``FATAL`` to standard error (``stderr``) in addition to log files.
  171. Setting Flags
  172. ~~~~~~~~~~~~~
  173. Several flags influence glog’s output behavior. If the `Google gflags library
  174. <https://github.com/gflags/gflags>`__ is installed on your machine, the build
  175. system will automatically detect and use it, allowing you to pass flags on the
  176. command line. For example, if you want to turn the flag :cmd:`--logtostderr` on,
  177. you can start your application with the following command line:
  178. .. code:: bash
  179. ./your_application --logtostderr=1
  180. If the Google gflags library isn’t installed, you set flags via
  181. environment variables, prefixing the flag name with ``GLOG_``, e.g.,
  182. .. code:: bash
  183. GLOG_logtostderr=1 ./your_application
  184. The following flags are most commonly used:
  185. ``logtostderr`` (``bool``, default=\ ``false``)
  186. Log messages to ``stderr`` instead of logfiles. Note: you can set
  187. binary flags to ``true`` by specifying ``1``, ``true``, or ``yes``
  188. (case insensitive). Also, you can set binary flags to ``false`` by
  189. specifying ``0``, ``false``, or ``no`` (again, case insensitive).
  190. ``stderrthreshold`` (``int``, default=2, which is ``ERROR``)
  191. Copy log messages at or above this level to stderr in addition to
  192. logfiles. The numbers of severity levels ``INFO``, ``WARNING``,
  193. ``ERROR``, and ``FATAL`` are 0, 1, 2, and 3, respectively.
  194. ``minloglevel`` (``int``, default=0, which is ``INFO``)
  195. Log messages at or above this level. Again, the numbers of severity
  196. levels ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL`` are 0, 1, 2,
  197. and 3, respectively.
  198. ``log_dir`` (``string``, default="")
  199. If specified, logfiles are written into this directory instead of the
  200. default logging directory.
  201. ``v`` (``int``, default=0)
  202. Show all ``VLOG(m)`` messages for ``m`` less or equal the value of
  203. this flag. Overridable by :cmd:`--vmodule`. See `the section about
  204. verbose logging <#verbose-logging>`__ for more detail.
  205. ``vmodule`` (``string``, default="")
  206. Per-module verbose level. The argument has to contain a
  207. comma-separated list of <module name>=<log level>. <module name> is a
  208. glob pattern (e.g., ``gfs*`` for all modules whose name starts with
  209. "gfs"), matched against the filename base (that is, name ignoring
  210. .cc/.h./-inl.h). <log level> overrides any value given by :cmd:`--v`.
  211. See also `the section about verbose logging <#verbose-logging>`__.
  212. There are some other flags defined in logging.cc. Please grep the source
  213. code for ``DEFINE_`` to see a complete list of all flags.
  214. You can also modify flag values in your program by modifying global
  215. variables ``FLAGS_*`` . Most settings start working immediately after
  216. you update ``FLAGS_*`` . The exceptions are the flags related to
  217. destination files. For example, you might want to set ``FLAGS_log_dir``
  218. before calling :cpp:`google::InitGoogleLogging` . Here is an example:
  219. .. code:: cpp
  220. LOG(INFO) << "file";
  221. // Most flags work immediately after updating values.
  222. FLAGS_logtostderr = 1;
  223. LOG(INFO) << "stderr";
  224. FLAGS_logtostderr = 0;
  225. // This won’t change the log destination. If you want to set this
  226. // value, you should do this before google::InitGoogleLogging .
  227. FLAGS_log_dir = "/some/log/directory";
  228. LOG(INFO) << "the same file";
  229. Conditional / Occasional Logging
  230. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  231. Sometimes, you may only want to log a message under certain conditions.
  232. You can use the following macros to perform conditional logging:
  233. .. code:: cpp
  234. LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  235. The "Got lots of cookies" message is logged only when the variable
  236. ``num_cookies`` exceeds 10. If a line of code is executed many times, it
  237. may be useful to only log a message at certain intervals. This kind of
  238. logging is most useful for informational messages.
  239. .. code:: cpp
  240. LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
  241. The above line outputs a log messages on the 1st, 11th, 21st, ... times
  242. it is executed. Note that the special ``google::COUNTER`` value is used
  243. to identify which repetition is happening.
  244. You can combine conditional and occasional logging with the following
  245. macro.
  246. .. code:: cpp
  247. LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
  248. << "th big cookie";
  249. Instead of outputting a message every nth time, you can also limit the
  250. output to the first n occurrences:
  251. .. code:: cpp
  252. LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
  253. Outputs log messages for the first 20 times it is executed. Again, the
  254. ``google::COUNTER`` identifier indicates which repetition is happening.
  255. Other times, it is desired to only log a message periodically based on a time.
  256. So for example, to log a message every 10ms:
  257. .. code:: cpp
  258. LOG_EVERY_T(INFO, 0.01) << "Got a cookie";
  259. Or every 2.35s:
  260. .. code:: cpp
  261. LOG_EVERY_T(INFO, 2.35) << "Got a cookie";
  262. Debug Mode Support
  263. ~~~~~~~~~~~~~~~~~~
  264. Special "debug mode" logging macros only have an effect in debug mode
  265. and are compiled away to nothing for non-debug mode compiles. Use these
  266. macros to avoid slowing down your production application due to
  267. excessive logging.
  268. .. code:: cpp
  269. DLOG(INFO) << "Found cookies";
  270. DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
  271. DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
  272. ``CHECK`` Macros
  273. ~~~~~~~~~~~~~~~~
  274. It is a good practice to check expected conditions in your program
  275. frequently to detect errors as early as possible. The ``CHECK`` macro
  276. provides the ability to abort the application when a condition is not
  277. met, similar to the ``assert`` macro defined in the standard C library.
  278. ``CHECK`` aborts the application if a condition is not true. Unlike
  279. ``assert``, it is \*not\* controlled by ``NDEBUG``, so the check will be
  280. executed regardless of compilation mode. Therefore, ``fp->Write(x)`` in
  281. the following example is always executed:
  282. .. code:: cpp
  283. CHECK(fp->Write(x) == 4) << "Write failed!";
  284. There are various helper macros for equality/inequality checks -
  285. ``CHECK_EQ``, ``CHECK_NE``, ``CHECK_LE``, ``CHECK_LT``, ``CHECK_GE``,
  286. and ``CHECK_GT``. They compare two values, and log a ``FATAL`` message
  287. including the two values when the result is not as expected. The values
  288. must have :cpp:`operator<<(ostream, ...)` defined.
  289. You may append to the error message like so:
  290. .. code:: cpp
  291. CHECK_NE(1, 2) << ": The world must be ending!";
  292. We are very careful to ensure that each argument is evaluated exactly
  293. once, and that anything which is legal to pass as a function argument is
  294. legal here. In particular, the arguments may be temporary expressions
  295. which will end up being destroyed at the end of the apparent statement,
  296. for example:
  297. .. code:: cpp
  298. CHECK_EQ(string("abc")[1], ’b’);
  299. The compiler reports an error if one of the arguments is a pointer and the other
  300. is :cpp:`nullptr`. To work around this, simply :cpp:`static_cast` :cpp:`nullptr` to
  301. the type of the desired pointer.
  302. .. code:: cpp
  303. CHECK_EQ(some_ptr, static_cast<SomeType*>(nullptr));
  304. Better yet, use the ``CHECK_NOTNULL`` macro:
  305. .. code:: cpp
  306. CHECK_NOTNULL(some_ptr);
  307. some_ptr->DoSomething();
  308. Since this macro returns the given pointer, this is very useful in
  309. constructor initializer lists.
  310. .. code:: cpp
  311. struct S {
  312. S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {}
  313. Something* ptr_;
  314. };
  315. Note that you cannot use this macro as a C++ stream due to this feature.
  316. Please use ``CHECK_EQ`` described above to log a custom message before
  317. aborting the application.
  318. If you are comparing C strings (:cpp:`char *`), a handy set of macros performs
  319. case sensitive as well as case insensitive comparisons - ``CHECK_STREQ``,
  320. ``CHECK_STRNE``, ``CHECK_STRCASEEQ``, and ``CHECK_STRCASENE``. The CASE versions
  321. are case-insensitive. You can safely pass :cpp:`nullptr` pointers for this macro. They
  322. treat :cpp:`nullptr` and any non-:cpp:`nullptr` string as not equal. Two :cpp:`nullptr`\
  323. s are equal.
  324. Note that both arguments may be temporary strings which are destructed
  325. at the end of the current "full expression" (e.g.,
  326. :cpp:`CHECK_STREQ(Foo().c_str(), Bar().c_str())` where ``Foo`` and ``Bar``
  327. return C++’s :cpp:`std::string`).
  328. The ``CHECK_DOUBLE_EQ`` macro checks the equality of two floating point
  329. values, accepting a small error margin. ``CHECK_NEAR`` accepts a third
  330. floating point argument, which specifies the acceptable error margin.
  331. Verbose Logging
  332. ~~~~~~~~~~~~~~~
  333. When you are chasing difficult bugs, thorough log messages are very useful.
  334. However, you may want to ignore too verbose messages in usual development. For
  335. such verbose logging, glog provides the ``VLOG`` macro, which allows you to
  336. define your own numeric logging levels. The :cmd:`--v` command line option
  337. controls which verbose messages are logged:
  338. .. code:: cpp
  339. VLOG(1) << "I’m printed when you run the program with --v=1 or higher";
  340. VLOG(2) << "I’m printed when you run the program with --v=2 or higher";
  341. With ``VLOG``, the lower the verbose level, the more likely messages are to be
  342. logged. For example, if :cmd:`--v==1`, ``VLOG(1)`` will log, but ``VLOG(2)``
  343. will not log. This is opposite of the severity level, where ``INFO`` is 0, and
  344. ``ERROR`` is 2. :cmd:`--minloglevel` of 1 will log ``WARNING`` and above. Though
  345. you can specify any integers for both ``VLOG`` macro and :cmd:`--v` flag, the
  346. common values for them are small positive integers. For example, if you write
  347. ``VLOG(0)``, you should specify :cmd:`--v=-1` or lower to silence it. This is
  348. less useful since we may not want verbose logs by default in most cases. The
  349. ``VLOG`` macros always log at the ``INFO`` log level (when they log at all).
  350. Verbose logging can be controlled from the command line on a per-module
  351. basis:
  352. .. code:: bash
  353. --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
  354. will:
  355. (a) Print ``VLOG(2)`` and lower messages from mapreduce.{h,cc}
  356. (b) Print ``VLOG(1)`` and lower messages from file.{h,cc}
  357. (c) Print ``VLOG(3)`` and lower messages from files prefixed with "gfs"
  358. (d) Print ``VLOG(0)`` and lower messages from elsewhere
  359. The wildcarding functionality shown by (c) supports both ’*’ (matches 0
  360. or more characters) and ’?’ (matches any single character) wildcards.
  361. Please also check the section about `command line flags <#setting-flags>`__.
  362. There’s also ``VLOG_IS_ON(n)`` "verbose level" condition macro. This
  363. macro returns true when the :cmd:`--v` is equal or greater than ``n``. To
  364. be used as
  365. .. code:: cpp
  366. if (VLOG_IS_ON(2)) {
  367. // do some logging preparation and logging
  368. // that can’t be accomplished with just VLOG(2) << ...;
  369. }
  370. Verbose level condition macros ``VLOG_IF``, ``VLOG_EVERY_N`` and
  371. ``VLOG_IF_EVERY_N`` behave analogous to ``LOG_IF``, ``LOG_EVERY_N``,
  372. ``LOF_IF_EVERY``, but accept a numeric verbosity level as opposed to a
  373. severity level.
  374. .. code:: cpp
  375. VLOG_IF(1, (size > 1024))
  376. << "I’m printed when size is more than 1024 and when you run the "
  377. "program with --v=1 or more";
  378. VLOG_EVERY_N(1, 10)
  379. << "I’m printed every 10th occurrence, and when you run the program "
  380. "with --v=1 or more. Present occurence is " << google::COUNTER;
  381. VLOG_IF_EVERY_N(1, (size > 1024), 10)
  382. << "I’m printed on every 10th occurence of case when size is more "
  383. " than 1024, when you run the program with --v=1 or more. ";
  384. "Present occurence is " << google::COUNTER;
  385. Custom Log Prefix Format
  386. ~~~~~~~~~~~~~~~~~~~~~~~~
  387. glog supports changing the format of the prefix attached to log messages by
  388. receiving a user-provided callback to be used to generate such strings.
  389. For each log entry, the callback will be invoked with a ``LogMessageInfo``
  390. struct containing the severity, filename, line number, thread ID, and time of
  391. the event. It will also be given a reference to the output stream, whose
  392. contents will be prepended to the actual message in the final log line.
  393. For example:
  394. .. code:: cpp
  395. /* This function writes a prefix that matches glog's default format.
  396. * (The third parameter can be used to receive user-supplied data, and is
  397. * nullptr by default.)
  398. */
  399. void CustomPrefix(std::ostream &s, const LogMessageInfo &l, void*) {
  400. s << l.severity[0]
  401. << setw(4) << 1900 + l.time.year()
  402. << setw(2) << 1 + l.time.month()
  403. << setw(2) << l.time.day()
  404. << ' '
  405. << setw(2) << l.time.hour() << ':'
  406. << setw(2) << l.time.min() << ':'
  407. << setw(2) << l.time.sec() << "."
  408. << setw(6) << l.time.usec()
  409. << ' '
  410. << setfill(' ') << setw(5)
  411. << l.thread_id << setfill('0')
  412. << ' '
  413. << l.filename << ':' << l.line_number << "]";
  414. }
  415. To enable the use of ``CustomPrefix()``, simply give glog a pointer to it
  416. during initialization: ``InitGoogleLogging(argv[0], &CustomPrefix);``.
  417. Optionally, ``InitGoogleLogging()`` takes a third argument of type ``void*``
  418. to pass on to the callback function.
  419. Failure Signal Handler
  420. ~~~~~~~~~~~~~~~~~~~~~~
  421. The library provides a convenient signal handler that will dump useful
  422. information when the program crashes on certain signals such as ``SIGSEGV``. The
  423. signal handler can be installed by :cpp:`google::InstallFailureSignalHandler()`.
  424. The following is an example of output from the signal handler.
  425. ::
  426. *** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
  427. *** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
  428. PC: @ 0x412eb1 TestWaitingLogSink::send()
  429. @ 0x7f892fb417d0 (unknown)
  430. @ 0x412eb1 TestWaitingLogSink::send()
  431. @ 0x7f89304f7f06 google::LogMessage::SendToLog()
  432. @ 0x7f89304f35af google::LogMessage::Flush()
  433. @ 0x7f89304f3739 google::LogMessage::~LogMessage()
  434. @ 0x408cf4 TestLogSinkWaitTillSent()
  435. @ 0x4115de main
  436. @ 0x7f892f7ef1c4 (unknown)
  437. @ 0x4046f9 (unknown)
  438. By default, the signal handler writes the failure dump to the standard
  439. error. You can customize the destination by :cpp:`InstallFailureWriter()`.
  440. Performance of Messages
  441. ~~~~~~~~~~~~~~~~~~~~~~~
  442. The conditional logging macros provided by glog (e.g., ``CHECK``,
  443. ``LOG_IF``, ``VLOG``, etc.) are carefully implemented and don’t execute
  444. the right hand side expressions when the conditions are false. So, the
  445. following check may not sacrifice the performance of your application.
  446. .. code:: cpp
  447. CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow();
  448. User-defined Failure Function
  449. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  450. ``FATAL`` severity level messages or unsatisfied ``CHECK`` condition
  451. terminate your program. You can change the behavior of the termination
  452. by :cpp:`InstallFailureFunction`.
  453. .. code:: cpp
  454. void YourFailureFunction() {
  455. // Reports something...
  456. exit(EXIT_FAILURE);
  457. }
  458. int main(int argc, char* argv[]) {
  459. google::InstallFailureFunction(&YourFailureFunction);
  460. }
  461. By default, glog tries to dump stacktrace and makes the program exit
  462. with status 1. The stacktrace is produced only when you run the program
  463. on an architecture for which glog supports stack tracing (as of
  464. September 2008, glog supports stack tracing for x86 and x86_64).
  465. Raw Logging
  466. ~~~~~~~~~~~
  467. The header file ``<glog/raw_logging.h>`` can be used for thread-safe logging,
  468. which does not allocate any memory or acquire any locks. Therefore, the macros
  469. defined in this header file can be used by low-level memory allocation and
  470. synchronization code. Please check `src/glog/raw_logging.h.in
  471. <src/glog/raw_logging.h.in>`__ for detail.
  472. Google Style ``perror()``
  473. ~~~~~~~~~~~~~~~~~~~~~~~~~
  474. ``PLOG()`` and ``PLOG_IF()`` and ``PCHECK()`` behave exactly like their
  475. ``LOG*`` and ``CHECK`` equivalents with the addition that they append a
  476. description of the current state of errno to their output lines. E.g.
  477. .. code:: cpp
  478. PCHECK(write(1, nullptr, 2) >= 0) << "Write nullptr failed";
  479. This check fails with the following error message.
  480. ::
  481. F0825 185142 test.cc:22] Check failed: write(1, nullptr, 2) >= 0 Write nullptr failed: Bad address [14]
  482. Syslog
  483. ~~~~~~
  484. ``SYSLOG``, ``SYSLOG_IF``, and ``SYSLOG_EVERY_N`` macros are available.
  485. These log to syslog in addition to the normal logs. Be aware that
  486. logging to syslog can drastically impact performance, especially if
  487. syslog is configured for remote logging! Make sure you understand the
  488. implications of outputting to syslog before you use these macros. In
  489. general, it’s wise to use these macros sparingly.
  490. Strip Logging Messages
  491. ~~~~~~~~~~~~~~~~~~~~~~
  492. Strings used in log messages can increase the size of your binary and
  493. present a privacy concern. You can therefore instruct glog to remove all
  494. strings which fall below a certain severity level by using the
  495. ``GOOGLE_STRIP_LOG`` macro:
  496. If your application has code like this:
  497. .. code:: cpp
  498. #define GOOGLE_STRIP_LOG 1 // this must go before the #include!
  499. #include <glog/logging.h>
  500. The compiler will remove the log messages whose severities are less than
  501. the specified integer value. Since ``VLOG`` logs at the severity level
  502. ``INFO`` (numeric value ``0``), setting ``GOOGLE_STRIP_LOG`` to 1 or
  503. greater removes all log messages associated with ``VLOG``\ s as well as
  504. ``INFO`` log statements.
  505. Automatically Remove Old Logs
  506. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  507. To enable the log cleaner:
  508. .. code:: cpp
  509. google::EnableLogCleaner(3); // keep your logs for 3 days
  510. And then glog will check if there are overdue logs whenever a flush is
  511. performed. In this example, any log file from your project whose last
  512. modified time is greater than 3 days will be unlink()ed.
  513. This feature can be disabled at any time (if it has been enabled)
  514. .. code:: cpp
  515. google::DisableLogCleaner();
  516. Notes for Windows Users
  517. ~~~~~~~~~~~~~~~~~~~~~~~
  518. glog defines a severity level ``ERROR``, which is also defined in
  519. ``windows.h`` . You can make glog not define ``INFO``, ``WARNING``,
  520. ``ERROR``, and ``FATAL`` by defining ``GLOG_NO_ABBREVIATED_SEVERITIES``
  521. before including ``glog/logging.h`` . Even with this macro, you can
  522. still use the iostream like logging facilities:
  523. .. code:: cpp
  524. #define GLOG_NO_ABBREVIATED_SEVERITIES
  525. #include <windows.h>
  526. #include <glog/logging.h>
  527. // ...
  528. LOG(ERROR) << "This should work";
  529. LOG_IF(ERROR, x > y) << "This should be also OK";
  530. However, you cannot use ``INFO``, ``WARNING``, ``ERROR``, and ``FATAL``
  531. anymore for functions defined in ``glog/logging.h`` .
  532. .. code:: cpp
  533. #define GLOG_NO_ABBREVIATED_SEVERITIES
  534. #include <windows.h>
  535. #include <glog/logging.h>
  536. // ...
  537. // This won’t work.
  538. // google::FlushLogFiles(google::ERROR);
  539. // Use this instead.
  540. google::FlushLogFiles(google::GLOG_ERROR);
  541. If you don’t need ``ERROR`` defined by ``windows.h``, there are a couple
  542. of more workarounds which sometimes don’t work:
  543. - ``#define WIN32_LEAN_AND_MEAN`` or ``NOGDI`` **before** you
  544. ``#include windows.h``.
  545. - ``#undef ERROR`` **after** you ``#include windows.h`` .
  546. See `this
  547. issue <http://code.google.com/p/google-glog/issues/detail?id=33>`__ for
  548. more detail.
  549. Installation Notes for 64-bit Linux Systems
  550. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  551. The glibc built-in stack-unwinder on 64-bit systems has some problems with glog.
  552. (In particular, if you are using :cpp:`InstallFailureSignalHandler()`, the
  553. signal may be raised in the middle of malloc, holding some malloc-related locks
  554. when they invoke the stack unwinder. The built-in stack unwinder may call malloc
  555. recursively, which may require the thread to acquire a lock it already holds:
  556. deadlock.)
  557. For that reason, if you use a 64-bit system and you need
  558. :cpp:`InstallFailureSignalHandler()`, we strongly recommend you install
  559. ``libunwind`` before trying to configure or install google glog.
  560. libunwind can be found
  561. `here <http://download.savannah.nongnu.org/releases/libunwind/libunwind-snap-070410.tar.gz>`__.
  562. Even if you already have ``libunwind`` installed, you will probably
  563. still need to install from the snapshot to get the latest version.
  564. Caution: if you install libunwind from the URL above, be aware that you
  565. may have trouble if you try to statically link your binary with glog:
  566. that is, if you link with ``gcc -static -lgcc_eh ...``. This is because
  567. both ``libunwind`` and ``libgcc`` implement the same C++ exception
  568. handling APIs, but they implement them differently on some platforms.
  569. This is not likely to be a problem on ia64, but may be on x86-64.
  570. Also, if you link binaries statically, make sure that you add
  571. :cmd:`-Wl,--eh-frame-hdr` to your linker options. This is required so that
  572. ``libunwind`` can find the information generated by the compiler required for
  573. stack unwinding.
  574. Using :cmd:`-static` is rare, though, so unless you know this will affect you it
  575. probably won’t.
  576. If you cannot or do not wish to install libunwind, you can still try to
  577. use two kinds of stack-unwinder: 1. glibc built-in stack-unwinder and 2.
  578. frame pointer based stack-unwinder.
  579. 1. As we already mentioned, glibc’s unwinder has a deadlock issue.
  580. However, if you don’t use :cpp:`InstallFailureSignalHandler()` or you
  581. don’t worry about the rare possibilities of deadlocks, you can use
  582. this stack-unwinder. If you specify no options and ``libunwind``
  583. isn’t detected on your system, the configure script chooses this
  584. unwinder by default.
  585. 2. The frame pointer based stack unwinder requires that your
  586. application, the glog library, and system libraries like libc, all be
  587. compiled with a frame pointer. This is *not* the default for x86-64.
  588. How to Contribute
  589. -----------------
  590. We’d love to accept your patches and contributions to this project.
  591. There are a just a few small guidelines you need to follow.
  592. Contributor License Agreement (CLA)
  593. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  594. Contributions to any Google project must be accompanied by a Contributor
  595. License Agreement. This is not a copyright **assignment**, it simply
  596. gives Google permission to use and redistribute your contributions as
  597. part of the project.
  598. * If you are an individual writing original source code and you’re sure
  599. you own the intellectual property, then you’ll need to sign an
  600. `individual
  601. CLA <https://developers.google.com/open-source/cla/individual>`__.
  602. * If you work for a company that wants to allow you to contribute your
  603. work, then you’ll need to sign a `corporate
  604. CLA <https://developers.google.com/open-source/cla/corporate>`__.
  605. You generally only need to submit a CLA once, so if you’ve already
  606. submitted one (even if it was for a different project), you probably
  607. don’t need to do it again.
  608. Once your CLA is submitted (or if you already submitted one for another
  609. Google project), make a commit adding yourself to the
  610. `AUTHORS <./AUTHORS>`__ and `CONTRIBUTORS <./CONTRIBUTORS>`__ files. This
  611. commit can be part of your first `pull
  612. request <https://help.github.com/articles/creating-a-pull-request>`__.
  613. Submitting a Patch
  614. ~~~~~~~~~~~~~~~~~~
  615. 1. It’s generally best to start by opening a new issue describing the
  616. bug or feature you’re intending to fix. Even if you think it’s
  617. relatively minor, it’s helpful to know what people are working on.
  618. Mention in the initial issue that you are planning to work on that
  619. bug or feature so that it can be assigned to you.
  620. 2. Follow the normal process of
  621. `forking <https://help.github.com/articles/fork-a-repo>`__ the
  622. project, and setup a new branch to work in. It’s important that each
  623. group of changes be done in separate branches in order to ensure that
  624. a pull request only includes the commits related to that bug or
  625. feature.
  626. 3. Do your best to have `well-formed commit
  627. messages <http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html>`__
  628. for each change. This provides consistency throughout the project,
  629. and ensures that commit messages are able to be formatted properly by
  630. various git tools.
  631. 4. Finally, push the commits to your fork and submit a `pull
  632. request <https://help.github.com/articles/creating-a-pull-request>`__.
  633. .. |Linux Github actions| image:: https://github.com/google/glog/actions/workflows/linux.yml/badge.svg
  634. :target: https://github.com/google/glog/actions
  635. .. |Windows Github actions| image:: https://github.com/google/glog/actions/workflows/windows.yml/badge.svg
  636. :target: https://github.com/google/glog/actions
  637. .. |macOS Github actions| image:: https://github.com/google/glog/actions/workflows/macos.yml/badge.svg
  638. :target: https://github.com/google/glog/actions
  639. .. |Codecov| image:: https://codecov.io/gh/google/glog/branch/master/graph/badge.svg?token=8an420vNju
  640. :target: https://codecov.io/gh/google/glog