Bug 1852754: part 9) Add tests for dynamically loading <link rel="prefetch"> elements...
[gecko.git] / xpcom / docs / logging.rst
blob61b12037c1d8a1978ad9e881a9d282f53fe981da
1 Gecko Logging
2 =============
4 A minimal C++ logging framework is provided for use in core Gecko code. It is
5 enabled for all builds and is thread-safe.
7 This page covers enabling logging for particular logging module, configuring
8 the logging output, and how to use the logging facilities in native code.
10 Enabling and configuring logging
11 ++++++++++++++++++++++++++++++++
13 Caveat: sandboxing when logging to a file
14 -----------------------------------------
16 A sandboxed content process cannot write to ``stderr`` or any file.  The easiest
17 way to log these processes is to disable the content sandbox by setting the
18 preference ``security.sandbox.content.level`` to ``0``, or setting the environment
19 variable ``MOZ_DISABLE_CONTENT_SANDBOX`` to ``1``.
21 On Windows, you can still see child process messages by using DOS (not the
22 ``MOZ_LOG_FILE`` variable defined below) to redirect output to a file.  For
23 example: ``MOZ_LOG="CameraChild:5" mach run >& my_log_file.txt`` will include
24 debug messages from the camera's child actor that lives in a (sandboxed) content
25 process.
27 Logging to the Firefox Profiler
28 -------------------------------
30 When a log statement is logged on a thread and the `Firefox Profiler
31 <https://profiler.firefox.com>`_ is profiling that thread, the log statements is
32 recorded as a profiler marker.
34 This allows getting logs alongside profiler markers and lots of performance
35 and contextual information, in a way that doesn't require disabling the
36 sandbox, and works across all processes.
38 The profile can be downloaded and shared e.g. via Bugzilla or email, or
39 uploaded, and the logging statements will be visible either in the marker chart
40 or the marker table.
42 While it is possible to manually configure logging module and start the profiler
43 with the right set of threads to profile, ``about:logging`` makes this task a lot
44 simpler and error-proof.
47 The ``MOZ_LOG`` syntax
48 ----------------------
50 Logging is configured using a special but simple syntax: which module should be
51 enabled, at which level, and what logging options should be enabled or disabled.
53 The syntax is a list of terms, separated by commas. There are two types of
54 terms:
56 - A log module and its level, separated by a colon (``:``), such as
57   ``example_module:5`` to enable the module ``example_module`` at logging level
58   ``5`` (verbose). This `searchfox query
59   <https://searchfox.org/mozilla-central/search?q=LazyLogModule+.*%5C%28%22&path=&case=true&regexp=true>`_
60   returns the complete list of modules available.
61 - A special string in the following table, to configure the logging behaviour.
62   Some configuration switch take an integer parameter, in which case it's
63   separated from the string by a colon (``:``). Most switches only apply in a
64   specific output context, noted in the **Context** column.
66 +----------------------+---------+-------------------------------------------------------------------------------------------+
67 | Special module name  | Context | Action                                                                                    |
68 +======================+=========+===========================================================================================+
69 | append               | File    | Append new logs to existing log file.                                                     |
70 +----------------------+---------+-------------------------------------------------------------------------------------------+
71 | sync                 | File    | Print each log synchronously, this is useful to check behavior in real time or get logs   |
72 |                      |         | immediately before crash.                                                                 |
73 +----------------------+---------+-------------------------------------------------------------------------------------------+
74 | raw                  | File    | Print exactly what has been specified in the format string, without the                   |
75 |                      |         | process/thread/timestamp, etc. prefix.                                                    |
76 +----------------------+---------+-------------------------------------------------------------------------------------------+
77 | timestamp            | File    | Insert timestamp at start of each log line.                                               |
78 +----------------------+---------+-------------------------------------------------------------------------------------------+
79 | rotate:**N**         | File    | | This limits the produced log files' size.  Only most recent **N megabytes** of log data |
80 |                      |         | | is saved.  We rotate four log files with .0, .1, .2, .3 extensions.  Note: this option  |
81 |                      |         | | disables 'append' and forces 'timestamp'.                                               |
82 +----------------------+---------+-------------------------------------------------------------------------------------------+
83 | maxsize:**N**        | File    | Limit the log to **N** MB. Only work in append mode.                                      |
84 +----------------------+---------+-------------------------------------------------------------------------------------------+
85 | prependheader        | File    | Prepend a simple header while distinguishing logging. Useful in append mode.              |
86 +----------------------+---------+-------------------------------------------------------------------------------------------+
87 | profilerstacks       | Profiler| | When profiling with the Firefox Profiler and log modules are enabled, capture the call  |
88 |                      |         | | stack for each log statement.                                                           |
89 +----------------------+---------+-------------------------------------------------------------------------------------------+
91 This syntax is used for most methods of enabling logging, with the exception of
92 settings preferences directly, see :ref:`this section <Enabling logging using preferences>` for directions.
95 Enabling Logging
96 ----------------
98 Enabling logging can be done in a variety of ways:
100 - via environment variables
101 - via command line switches
102 - using ``about:config`` preferences
103 - using ``about:logging``
105 The first two allow logging from the start of the application and are also
106 useful in case of a crash (when ``sync`` output is requested, this can also be
107 done with ``about:config`` as well to a certain extent). The last two
108 allow enabling and disabling logging at runtime and don't require using the
109 command-line.
111 By default all logging output is disabled.
113 Enabling logging using ``about:logging``
114 ''''''''''''''''''''''''''''''''''''''''
116 ``about:logging`` allows enabling logging by entering a ``MOZ_LOG`` string in the
117 text input, and validating.
119 Options allow logging to a file or using the Firefox Profiler, that can be
120 started and stopped right from the page.
122 Logging presets for common scenarios are available in a drop-down. They can be
123 associated with a profiler preset.
125 It is possible, via URL parameters, to select a particular logging
126 configuration, or to override certain parameters in a preset. This is useful to
127 ask a user to gather logs efficiently without having to fiddle with prefs and/or
128 environment variable.
130 URL parameters are described in the following table:
132 +---------------------+---------------------------------------------------------------------------------------------+
133 | Parameter           | Description                                                                                 |
134 +=====================+=============================================================================================+
135 | ``preset``          |  a `logging preset <https://searchfox.org/mozilla-central/search?q=gLoggingPresets>`_       |
136 +---------------------+---------------------------------------------------------------------------------------------+
137 | ``logging-preset``  |  alias for ``preset``                                                                       |
138 +---------------------+---------------------------------------------------------------------------------------------+
139 | ``modules``         |  a string in ``MOZ_LOG`` syntax                                                             |
140 +---------------------+---------------------------------------------------------------------------------------------+
141 | ``module``          |  alias for ``modules``                                                                      |
142 +---------------------+---------------------------------------------------------------------------------------------+
143 | ``threads``         |  a list of threads to profile, overrides what a profiler preset would have picked           |
144 +---------------------+---------------------------------------------------------------------------------------------+
145 | ``thread``          |  alias for ``threads``                                                                      |
146 +---------------------+---------------------------------------------------------------------------------------------+
147 | ``output``          |  either ``profiler`` or ``file``                                                            |
148 +---------------------+---------------------------------------------------------------------------------------------+
149 | ``output-type``     |  alias for ``output``                                                                       |
150 +---------------------+---------------------------------------------------------------------------------------------+
151 | ``profiler-preset`` |  a `profiler preset <https://searchfox.org/mozilla-central/search?q=%40type+{Presets}>`_    |
152 +---------------------+---------------------------------------------------------------------------------------------+
154 If a preset is selected, then ``threads`` or ``modules`` can be used to override the
155 profiled threads or logging modules enabled, but keeping other aspects of the
156 preset. If no preset is selected, then a generic profiling preset is used,
157 ``firefox-platform``. For example:
161   about:logging?output=profiler&preset=media-playback&modules=cubeb:4,AudioSinkWrapper:4:AudioSink:4
163 will profile the threads in the ``Media`` profiler preset, but will only log
164 specific log modules (instead of the `long list
165 <https://searchfox.org/mozilla-central/search?q="media-playback"&path=toolkit%2Fcontent%2FaboutLogging.js>`_
166 in the ``media-playback`` preset). In addition, it disallows logging to a file.
168 Enabling logging using environment variables
169 ''''''''''''''''''''''''''''''''''''''''''''
171 On UNIX, setting and environment variable can be done in a variety of ways
175   set MOZ_LOG="example_logger:3"
176   export MOZ_LOG="example_logger:3"
177   MOZ_LOG="example_logger:3" ./mach run
179 In the Windows Command Prompt (``cmd.exe``), don't use quotes:
183   set MOZ_LOG=example_logger:3
185 If you want this on GeckoView example, use the following adb command to launch process:
189   adb shell am start -n org.mozilla.geckoview_example/.GeckoViewActivity --es env0 "MOZ_LOG=example_logger:3"
191 There are special module names to change logging behavior. You can specify one or more special module names without logging level.
193 For example, if you want to specify ``sync``, ``timestamp`` and ``rotate``:
197   set MOZ_LOG="example_logger:3,timestamp,sync,rotate:10"
199 Enabling logging usually outputs the logging statements to the terminal. To
200 have the logs written to a file instead (one file per process), the environment
201 variable ``MOZ_LOG_FILE`` can be used. Logs will be written at this path
202 (either relative or absolute), suffixed by a process type and its PID.
203 ``MOZ_LOG`` files are text files and have the extension ``.moz_log``.
205 For example, setting:
209   set MOZ_LOG_FILE="firefox-logs"
211 can create a number of files like so:
215   firefox-log-main.96353.moz_log
216   firefox-log-child.96354.moz_log
218 respectively for a parent process of PID 96353 and a child process of PID
219 96354.
221 Enabling logging using command-line flags
222 '''''''''''''''''''''''''''''''''''''''''
224 The ``MOZ_LOG`` syntax can be used with the command line switch on the same
225 name, and specifying a file with ``MOZ_LOG_FILE`` works in the same way:
229   ./mach run -MOZ_LOG=timestamp,rotate:200,example_module:5 -MOZ_LOG_FILE=%TEMP%\firefox-logs
231 will enable verbose (``5``) logging for the module ``example_module``, with
232 timestamp prepended to each line, rotate the logs with 4 files of each 50MB
233 (for a total of 200MB), and write the output to the temporary directory on
234 Windows, with name starting with ``firefox-logs``.
236 .. _Enabling logging using preferences:
238 Enabling logging using preferences
239 ''''''''''''''''''''''''''''''''''
241 To adjust the logging after Firefox has started, you can set prefs under the
242 `logging.` prefix. For example, setting `logging.foo` to `3` will set the log
243 module `foo` to start logging at level 3. A number of special prefs can be set,
244 described in the table below:
246 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
247 |         Preference name             | Preference |   Preference value            |                  Description                           |
248 +=====================================+============+===============================+========================================================+
249 | ``logging.config.clear_on_startup`` |    bool    | --                            | Whether to clear all prefs under ``logging.``          |
250 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
251 | ``logging.config.LOG_FILE``         |   string   | A path (relative or absolute) | The path to which the log files will be written.       |
252 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
253 | ``logging.config.add_timestamp``    |   bool     | --                            | Whether to prefix all lines by a timestamp.            |
254 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
255 | ``logging.config.sync``             |   bool     | --                            | Whether to flush the stream after each log statements. |
256 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
257 | ``logging.config.profilerstacks``   |   bool     | --                            | | When logging to the Firefox Profiler, whether to     |
258 |                                     |            |                               | | include the call stack in each logging statement.    |
259 +-------------------------------------+------------+-------------------------------+--------------------------------------------------------+
261 Enabling logging in Rust code
262 -----------------------------
264 We're gradually adding more Rust code to Gecko, and Rust crates typically use a
265 different approach to logging. Many Rust libraries use the `log
266 <https://docs.rs/log>`_ crate to log messages, which works together with
267 `env_logger <https://docs.rs/env_logger>`_ at the application level to control
268 what's actually printed via `RUST_LOG`.
270 You can set an overall logging level, though it could be quite verbose:
274   set RUST_LOG="debug"
276 You can also target individual modules by path:
280   set RUST_LOG="style::style_resolver=debug"
282 .. note::
283   For Linux/MacOS users, you need to use `export` rather than `set`.
285 .. note::
286   Sometimes it can be useful to only log child processes and ignore the parent
287    process. In Firefox 57 and later, you can use `RUST_LOG_CHILD` instead of
288    `RUST_LOG` to specify log settings that will only apply to child processes.
290 The `log` crate lists the available `log levels <https://docs.rs/log/0.3.8/log/enum.LogLevel.html>`_:
292 +-----------+---------------------------------------------------------------------------------------------------------+
293 | Log Level | Purpose                                                                                                 |
294 +===========+=========================================================================================================+
295 | error     | Designates very serious errors.                                                                         |
296 +-----------+---------------------------------------------------------------------------------------------------------+
297 | warn      | Designates hazardous situations.                                                                        |
298 +-----------+---------------------------------------------------------------------------------------------------------+
299 | info      | Designates useful information.                                                                          |
300 +-----------+---------------------------------------------------------------------------------------------------------+
301 | debug     | Designates lower priority information.                                                                  |
302 +-----------+---------------------------------------------------------------------------------------------------------+
303 | trace     | Designates very low priority, often extremely verbose, information.                                     |
304 +-----------+---------------------------------------------------------------------------------------------------------+
306 It is common for debug and trace to be disabled at compile time in release builds, so you may need a debug build if you want logs from those levels.
308 Check the `env_logger <https://docs.rs/env_logger>`_ docs for more details on logging options.
310 Additionally, a mapping from `RUST_LOG` is available. When using the `MOZ_LOG`
311 syntax, it is possible to enable logging in rust crate using a similar syntax:
315   MOZ_LOG=rust_crate_name::*:4
317 will enable `debug` logging for all log statements in the crate
318 ``rust_crate_name``.
320 `*` can be replaced by a series of modules if more specificity is needed:
324   MOZ_LOG=rust_crate_name::module::submodule:4
326 will enable `debug` logging for all log statements in the sub-module
327 ``submodule`` of the module ``module`` of the crate ``rust_crate_name``.
330 A table mapping Rust log levels to `MOZ_LOG` log level is available below:
332 +----------------+---------------+-----------------+
333 | Rust log level | MOZ_LOG level | Numerical value |
334 +================+===============+=================+
335 |      off       |     Disabled  |        0        |
336 +----------------+---------------+-----------------+
337 |      error     |     Error     |        1        |
338 +----------------+---------------+-----------------+
339 |      warn      |     Warning   |        2        |
340 +----------------+---------------+-----------------+
341 |      info      |     Info      |        3        |
342 +----------------+---------------+-----------------+
343 |      debug     |     Debug     |        4        |
344 +----------------+---------------+-----------------+
345 |      trace     |     Verbose   |        5        |
346 +----------------+---------------+-----------------+
349 Enabling logging on Android, interleaved with system logs (``logcat``)
350 ----------------------------------------------------------------------
352 While logging to the Firefox Profiler works it's sometimes useful to have
353 system logs (``adb logcat``) interleaved with application logging. With a
354 device (or emulator) that ``adb devices`` sees, it's possible to set
355 environment variables like so, for e.g. ``GeckoView_example``:
358 .. code-block:: sh
360   adb shell am start -n org.mozilla.geckoview_example/.GeckoViewActivity --es env0 MOZ_LOG=MediaDemuxer:4
363 It is then possible to see the logging statements like so, to display all logs,
364 including ``MOZ_LOG``:
366 .. code-block:: sh
368   adb logcat
370 and to only see ``MOZ_LOG`` like so:
372 .. code-block:: sh
374   adb logcat Gecko:V '*:S'
376 This expression means: print log module ``Gecko`` from log level ``Verbose``
377 (lowest level, this means that all levels are printed), and filter out (``S``
378 for silence) all other logging (``*``, be careful to quote it or escape it
379 appropriately, it so that it's not expanded by the shell).
381 While interactive with e.g. ``GeckoView`` code, it can be useful to specify
382 more logging tags like so:
384 .. code-block:: sh
386   adb logcat GeckoViewActivity:V Gecko:V '*:S'
389 Enabling logging on Android, using the Firefox Profiler
390 -------------------------------------------------------
392 Set the logging modules using `about:config` (this requires a Nightly build)
393 using the instructions outlined above, and start the profile using an
394 appropriate profiling preset to profile the correct threads using the instructions
395 written in Firefox Profiler documentation's `dedicated page
396 <https://profiler.firefox.com/docs/#/./guide-profiling-android-directly-on-device>`_.
398 `Bug 1803607 <https://bugzilla.mozilla.org/show_bug.cgi?id=1803607>`_ tracks
399 improving the logging experience on mobile.
401 Working with ``MOZ_LOG`` in the code
402 ++++++++++++++++++++++++++++++++++++
404 Declaring a Log Module
405 ----------------------
407 ``LazyLogModule`` defers the creation the backing ``LogModule`` in a thread-safe manner and is the preferred method to declare a log module. Multiple ``LazyLogModules`` with the same name can be declared, all will share the same backing ``LogModule``. This makes it much simpler to share a log module across multiple translation units. ``LazyLogLodule`` provides a conversion operator to ``LogModule*`` and is suitable for passing into the logging macros detailed below.
409 Note: Log module names can only contain specific characters. The first character must be a lowercase or uppercase ASCII char, underscore, dash, or dot. Subsequent characters may be any of those, or an ASCII digit.
411 .. code-block:: c++
413   #include "mozilla/Logging.h"
415   static mozilla::LazyLogModule sFooLog("foo");
418 Logging interface
419 -----------------
421 A basic interface is provided in the form of 2 macros and an enum class.
423 +----------------------------------------+----------------------------------------------------------------------------+
424 | MOZ_LOG(module, level, message)        | Outputs the given message if the module has the given log level enabled:   |
425 |                                        |                                                                            |
426 |                                        | *   module: The log module to use.                                         |
427 |                                        | *   level: The log level of the message.                                   |
428 |                                        | *   message: A printf-style message to output. Must be enclosed in         |
429 |                                        |     parentheses.                                                           |
430 +----------------------------------------+----------------------------------------------------------------------------+
431 | MOZ_LOG_TEST(module, level)            | Checks if the module has the given level enabled:                          |
432 |                                        |                                                                            |
433 |                                        | *    module: The log module to use.                                        |
434 |                                        | *    level: The output level of the message.                               |
435 +----------------------------------------+----------------------------------------------------------------------------+
438 +-----------+---------------+-----------------------------------------------------------------------------------------+
439 | Log Level | Numeric Value | Purpose                                                                                 |
440 +===========+===============+=========================================================================================+
441 | Disabled  |      0        | Indicates logging is disabled. This should not be used directly in code.                |
442 +-----------+---------------+-----------------------------------------------------------------------------------------+
443 | Error     |      1        | An error occurred, generally something you would consider asserting in a debug build.   |
444 +-----------+---------------+-----------------------------------------------------------------------------------------+
445 | Warning   |      2        | A warning often indicates an unexpected state.                                          |
446 +-----------+---------------+-----------------------------------------------------------------------------------------+
447 | Info      |      3        | An informational message, often indicates the current program state.                    |
448 +-----------+---------------+-----------------------------------------------------------------------------------------+
449 | Debug     |      4        | A debug message, useful for debugging but too verbose to be turned on normally.         |
450 +-----------+---------------+-----------------------------------------------------------------------------------------+
451 | Verbose   |      5        | A message that will be printed a lot, useful for debugging program flow and will        |
452 |           |               | probably impact performance.                                                            |
453 +-----------+---------------+-----------------------------------------------------------------------------------------+
455 Example Usage
456 -------------
458 .. code-block:: c++
460   #include "mozilla/Logging.h"
462   using mozilla::LogLevel;
464   static mozilla::LazyLogModule sLogger("example_logger");
466   static void DoStuff()
467   {
468     MOZ_LOG(sLogger, LogLevel::Info, ("Doing stuff."));
470     int i = 0;
471     int start = Time::NowMS();
472     MOZ_LOG(sLogger, LogLevel::Debug, ("Starting loop."));
473     while (i++ &lt; 10) {
474       MOZ_LOG(sLogger, LogLevel::Verbose, ("i = %d", i));
475     }
477     // Only calculate the elapsed time if the Warning level is enabled.
478     if (MOZ_LOG_TEST(sLogger, LogLevel::Warning)) {
479       int elapsed = Time::NowMS() - start;
480       if (elapsed &gt; 1000) {
481         MOZ_LOG(sLogger, LogLevel::Warning, ("Loop took %dms!", elapsed));
482       }
483     }
485     if (i != 10) {
486       MOZ_LOG(sLogger, LogLevel::Error, ("i should be 10!"));
487     }
488   }