lib: keep plugin name, if any, in component class structure
[babeltrace.git] / CONTRIBUTING.adoc
... / ...
CommitLineData
1// Render with Asciidoctor
2
3= Babeltrace contributor's guide
4Jérémie Galarneau, Philippe Proulx
5v0.2, 19 June 2019
6:toc:
7:toclevels: 5
8
9
10This is a partial contributor's guide for the
11http://diamon.org/babeltrace[Babeltrace] project. If you have any
12questions that are not answered by this guide, please post them on
13https://lists.lttng.org/cgi-bin/mailman/listinfo/lttng-dev[Babeltrace's
14mailing list].
15
16
17== Babeltrace library
18
19=== Object reference counting and lifetime
20
21This section covers the rationale behind the design of Babeltrace's
22object lifetime management. This applies to the Babeltrace library, as
23well as to the CTF writer library (although the public reference
24counting functions are not named the same way).
25
26Starting from Babeltrace 2.0, all publicly exposed objects inherit a
27common base: `bt_object`. This base provides a number of facilities to
28all objects, chief amongst which are lifetime management functions.
29
30The lifetime of some public objects is managed by reference counting. In
31this case, the API offers the `+bt_*_get_ref()+` and `+bt_*_put_ref()+`
32functions which respectively increment and decrement an object's
33reference count.
34
35As far as lifetime management in concerned, Babeltrace makes a clear
36distinction between regular objects, which have a single parent, and
37root objects, which don't.
38
39
40==== The problem
41
42Let us consider a problematic case to illustrate the need for this
43distinction.
44
45A user of the Babeltrace library creates a trace class, which _has_ a
46stream class (the class of a stream) and that stream class, in turn,
47_has_ an event class (the class of an event).
48
49Nothing prevents this user from releasing his reference on any one of
50these objects in any order. However, all objects in the
51__trace--stream class--event class__ hierarchy can be retrieved
52from any other.
53
54For instance, the user could discard his reference on both the event
55class and the stream class, only keeping a reference on the trace class.
56From this trace class reference, stream classes can be enumerated,
57providing the user with a new reference to the stream class he discarded
58earlier. Event classes can also be enumerated from stream classes,
59providing the user with references to the individual event classes.
60
61Conversely, the user could also hold a reference to an event class and
62retrieve its parent stream class. The trace class, in turn, can then be
63retrieved from the stream class.
64
65This example illustrates what could be interpreted as a circular
66reference dependency existing between these objects. Of course, if the
67objects in such a scenario were to hold references to each other (in
68both directions), we would be in presence of a circular ownership
69resulting in a leak of both objects as their reference counts would
70never reach zero.
71
72Nonetheless, the API must offer the guarantee that holding a node to any
73node of the graph keeps all other reachable nodes alive.
74
75
76==== The solution
77
78The scheme employed in Babeltrace to break this cycle consists in the
79"children" holding _reverse component references_ to their parents. That
80is, in the context of the trace IR, that event classes hold a reference
81to their parent stream class and stream classes hold a reference to
82their parent trace class.
83
84On the other hand, parents hold _claiming aggregation references_ to
85their children. A claiming aggregation reference means that the object
86being referenced should not be deleted as long as the reference still
87exists. In this respect, it can be said that parents truly hold the
88ownership of their children, since they control their lifetime.
89Conversely, the reference counting mechanism is leveraged by children to
90notify parents that no other child indirectly exposes the parent.
91
92When a parented object's reference count reaches zero, it invokes
93`+bt_*_put_ref()+` on its parent and does _not_ free itself. However,
94from that point, the object depends on its parent to signal the moment
95when it can be safely reclaimed.
96
97The invocation of `+bt_*_put_ref()+` by the last children holding a
98reference to its parent might trigger a cascade of `+bt_*_put_ref()+`
99from child to parent. Eventually, a **root** object is reached. At that
100point, if this orphaned object's reference count reaches zero, the
101object invokes the destructor method defined by everyone of its children
102as part of their base `struct bt_object`. The key point here is that the
103cascade of destructor will necessarily originate from the root and
104propagate in preorder to the children. These children will propagate the
105destruction to their own children before reclaiming their own memory.
106This ensures that a node's pointer to its parent is _always_ valid since
107the parent has the responsibility of tearing-down their children before
108cleaning themselves up.
109
110Assuming a reference to an object is _acquired_ by calling
111`+bt_*_get_ref()+` while its reference count is zero, the object
112acquires, in turn, a reference on its parent using `+bt_*_get_ref()+`.
113At that point, the child can be thought of as having converted its weak
114reference to its parent into a regular reference. That is why this
115reference is referred to as a _claiming_ aggregation reference.
116
117
118==== Caveats
119
120This scheme imposes a number of strict rules defining the relation
121between objects:
122
123* Objects may only have one parent.
124* Objects, beside the root, are only retrievable from their direct
125 parent or children.
126
127
128==== Example
129
130The initial situation is rather simple: **User{nbsp}A** is holding a
131reference to a trace class, **TC1**. As per the rules previously
132enounced, stream classes **SC1** and **SC2** don't hold a reference to
133**TC1** since their own reference counts are zero. The same holds true
134for **EC1**, **EC2** and **EC3** with respect to **SC1** and **SC2**.
135
136image::doc/contributing-images/bt-ref01.png[]
137
138In this second step, we can see that **User{nbsp}A** has acquired a
139reference on **SC2** through the trace class, **TC1**.
140
141The stream class's reference count transitions from zero to one,
142triggering the acquisition of a strong reference on **TC1** from
143**SC2**.
144
145Hence, at this point, the trace class's ownership is shared by
146**User{nbsp}A** and **SC2**.
147
148image::doc/contributing-images/bt-ref02.png[]
149
150Next, **User{nbsp}A** acquires a reference on the **EC3** event class
151through its parent stream class, **SC2**. Again, the transition of an
152object's reference count from 0 to 1 triggers the acquisition of a
153reference on its parent.
154
155Note that SC2's reference count was incremented to 2. The trace class's
156reference count remains unchanged.
157
158image::doc/contributing-images/bt-ref03.png[]
159
160**User{nbsp}A** decides to drop its reference on **SC2**. **SC2**'s
161reference count returns back to 1, everything else remaining unchanged.
162
163image::doc/contributing-images/bt-ref04.png[]
164
165**User{nbsp}A** can then decide to drop its reference on the trace
166class. This results in a reversal of the initial situation:
167**User{nbsp}A** now owns an event, **EC3**, which is keeping everything
168else alive and reachable.
169
170image::doc/contributing-images/bt-ref05.png[]
171
172If another object, **User{nbsp}B**, enters the picture and acquires a
173reference on the **SC1** stream class, we see that **SC1**'s reference
174count transitioned from 0 to 1, triggering the acquisition of a
175reference on **TC1**.
176
177image::doc/contributing-images/bt-ref06.png[]
178
179**User{nbsp}B** hands off a reference to **EC1**, acquired through
180**SC1**, to another object, **User{nbsp}C**. The acquisition of a
181reference on **EC1**, which transitions from 0 to 1, triggers the
182acquisition of a reference on its parent, **SC1**.
183
184image::doc/contributing-images/bt-ref07.png[]
185
186At some point, **User{nbsp}A** releases its reference on **EC3**. Since
187**EC3**'s reference count transitions to zero, it releases its reference
188on **SC2**. **SC2**'s reference count, in turn, reaches zero and it
189releases its reference to **TC1**.
190
191**TC1**'s reference count is now 1 and no further action is taken.
192
193image::doc/contributing-images/bt-ref08.png[]
194
195**User{nbsp}B** releases its reference on **SC1**. **User{nbsp}C**
196becomes the sole owner of the whole hierarchy through his ownership of
197**EC1**.
198
199image::doc/contributing-images/bt-ref09.png[]
200
201Finally, **User{nbsp}C** releases his ownership of **EC1**, triggering
202the release of the whole hierarchy. Let's walk through the reclamation
203of the whole graph.
204
205Mirroring what happened when **User{nbsp}A** released its last reference
206on **EC3**, the release of **EC1** by **User{nbsp}C** causes its
207reference count to fall to zero.
208
209This transition to zero causes **EC1** to release its reference on
210**SC1**. **SC1**'s reference count reaching zero causes it to release
211its reference on **TC1**.
212
213image::doc/contributing-images/bt-ref10.png[]
214
215Since the reference count of **TC1**, a root object, has reached zero,
216it invokes the destructor method on its children. This method is
217recursive and causes the stream classes to call the destructor method on
218their event classes.
219
220The event classes are reached and, having no children of their own, are
221reclaimed.
222
223image::doc/contributing-images/bt-ref11.png[]
224
225The stream classes having destroyed their children, are then reclaimed
226by the trace class.
227
228image::doc/contributing-images/bt-ref12.png[]
229
230Finally, the stream classes having been reclaimed, **TC1** is reclaimed.
231
232image::doc/contributing-images/bt-ref13.png[]
233
234
235== Logging
236
237Logging is a great instrument for a developer to be able to collect
238information about a running software.
239
240Babeltrace is a complex software with many layers. When a Babeltrace
241graph fails to run, what caused the failure? It could be caused by any
242component, any message iterator, and any deeply nested validation of a
243CTF IR object (within the `ctf` plugin), for example. With the
244appropriate logging statements manually placed in the source code, we
245can find the cause of a bug faster.
246
247While <<choose-a-log-level,care must be taken>> when placing _DEBUG_ to
248_FATAL_ logging statements, you should liberally instrument your
249Babeltrace module with _TRACE_ logging statements to help future you
250and other developers understand what's happening at run time.
251
252
253=== Logging API
254
255The Babeltrace logging API is internal: it is not exposed to the users
256of the library; only to their developers. The only thing that a library
257user can control is the current log level of the library itself with
258`bt_logging_set_global_level()` and the initial library's log level with
259the `LIBBABELTRACE2_INIT_LOG_LEVEL` environment variable.
260
261This API is based on https://github.com/wonder-mice/zf_log[zf_log], a
262lightweight, yet featureful, MIT-licensed core logging library for C and
263pass:[C++]. The zf_log source files were modified to have the `BT_` and
264`bt_` prefixes, and other small changes, like color support and using
265the project's `BT_DEBUG_MODE` definition instead of the standard
266`NDEBUG`.
267
268The logging functions are implemented in the logging convenience
269library (`src/logging` directory).
270
271
272[[logging-headers]]
273==== Headers
274
275The logging API headers are:
276
277`<babeltrace2/logging.h>`::
278 Public header which a library user can use to set and get
279 libbabeltrace2's current log level.
280
281`"logging/log.h"`::
282 Internal, generic logging API which you can use in any Babeltrace
283 module. This is the translation of `zf_log.h`.
284+
285This header offers the <<gen-logging-statements,generic logging
286statement macros>>.
287
288`"lib/logging.h"`::
289 Specific internal header to use within the library.
290+
291This header defines `BT_LOG_OUTPUT_LEVEL` to a custom, library-wide
292hidden symbol which is the library's current log level before including
293`"logging/log.h"`.
294+
295This header offers the <<lib-logging-statements,library-specific logging
296statement macros>>.
297
298`"plugins/comp-logging.h"`::
299 Specific internal header to use within a component class.
300+
301This header offers the <<comp-logging-statements,component-specific
302logging statement macros>>.
303
304
305[[log-levels]]
306==== Log levels
307
308The internal logging API offers the following log levels, in ascending
309order of severity:
310
311[options="header,autowidth",cols="4"]
312|===
313|Log level name
314|Log level short name
315|Internal API enumerator
316|Public API enumerator
317
318|_TRACE_
319|`T`
320|`BT_LOG_TRACE`
321|`BT_LOGGING_LEVEL_TRACE`
322
323|_DEBUG_
324|`D`
325|`BT_LOG_DEBUG`
326|`BT_LOGGING_LEVEL_DEBUG`
327
328|_INFO_
329|`I`
330|`BT_LOG_INFO`
331|`BT_LOGGING_LEVEL_INFO`
332
333|_WARN_
334|`W`
335|`BT_LOG_WARN`
336|`BT_LOGGING_LEVEL_WARN`
337
338|_ERROR_
339|`E`
340|`BT_LOG_ERROR`
341|`BT_LOGGING_LEVEL_ERROR`
342
343|_FATAL_
344|`F`
345|`BT_LOG_FATAL`
346|`BT_LOGGING_LEVEL_FATAL`
347
348|_NONE_
349|`N`
350|`BT_LOG_NONE`
351|`BT_LOGGING_LEVEL_NONE`
352|===
353
354The short name is accepted by the log level environment variables and by
355the CLI's `--log-level` options.
356
357See <<choose-a-log-level,how to decide which one to use>> below.
358
359There are two important log level expressions:
360
361[[build-time-log-level]]Build-time, minimal log level::
362 The minimal log level, or build-time log level, is set at build time
363 and determines the minimal log level of the logging statements which
364 can be executed. This applies to all the modules (CLI, library,
365 plugins, bindings, etc.).
366+
367All the logging statements with a level below this level are **not built
368at all**. All the logging statements with a level equal to or greater
369than this level _can_ be executed, depending on the
370<<run-time-log-level,run-time log level>>.
371+
372You can set this level at configuration time with the
373`BABELTRACE_MINIMAL_LOG_LEVEL` environment variable, for example:
374+
375--
376----
377$ BABELTRACE_MINIMAL_LOG_LEVEL=WARN ./configure
378----
379--
380+
381The default build-time log level is `DEBUG`. For optimal performance,
382set it to `INFO`, which effectively disables all fast path logging in
383all the Babeltrace modules. You can't set it to `WARN`, `ERROR`,
384`FATAL`, or `NONE` because the impact on performance is minuscule
385starting from the _INFO_ log level anyway and we want any Babeltrace
386build to always be able to print _INFO_-level logs.
387+
388The library's public API provides `bt_logging_get_minimal_level()` to
389get the configured minimal log level.
390
391[[run-time-log-level]]Run-time, dynamic log level::
392 The dynamic log level is set at run time and determines the current,
393 _active_ log level. All the logging statements with a level below
394 this level are not executed, **but they still evaluate the
395 condition**. All the logging statements with a level equal to or
396 greater than this level are executed, provided that their level is
397 also <<build-time-log-level,enabled at build time>>.
398+
399`zf_log` has a concept of a global run-time log level which uses the
400`_bt_log_global_output_lvl` symbol. In practice, we never use this
401symbol, and always make sure that `BT_LOG_OUTPUT_LEVEL` is defined to a
402module-wise expression before including `"logging/log.h"`.
403+
404In the library, `"lib/logging.h"` defines its own
405`BT_LOG_OUTPUT_LEVEL` to the library's log level symbol before it
406includes `"logging/log.h"` itself.
407+
408In libbabeltrace2, the user can set the current run-time log level with
409the `bt_logging_set_global_level()` function, for example:
410+
411--
412[source,c]
413----
414bt_logging_set_global_level(BT_LOGGING_LEVEL_INFO);
415----
416--
417+
418The library's initial run-time log level is defined by the
419`LIBBABELTRACE2_INIT_LOG_LEVEL` environment variable, or set to _NONE_
420if this environment variable is undefined.
421+
422Other modules have their own way of setting their run-time log level.
423+
424For example, the CLI uses the `BABELTRACE_CLI_LOG_LEVEL` environment
425variable, as well as its global `--log-level` option:
426+
427----
428$ babeltrace2 --log-level=I ...
429----
430+
431The components use their own log level (as returned by
432`bt_component_get_logging_level()`). With the CLI, you can set a
433specific component's log level with its own, position-dependent
434`--log-level` option:
435+
436----
437$ babeltrace2 /path/to/trace -c sink.ctf.fs --log-level=D
438----
439+
440Code which is common to the whole project, for example `src/common`
441and `src/compat`, use function parameters to get its run-time log
442level, for example:
443+
444[source,c]
445----
446BT_HIDDEN
447char *bt_common_get_home_plugin_path(int log_level);
448----
449+
450Typically, when a logging-enabled module calls such a function, it
451passes its own log level expression directly (`BT_LOG_OUTPUT_LEVEL`):
452+
453[source,c]
454----
455path = bt_common_get_home_plugin_path(BT_LOG_OUTPUT_LEVEL);
456----
457+
458Otherwise, just pass `BT_LOG_NONE`:
459+
460----
461path = bt_common_get_home_plugin_path(BT_LOG_NONE);
462----
463
464
465[[gen-logging-statements]]
466==== Generic logging statement macros
467
468The Babeltrace logging statement macros work just like `printf()`
469(except the `+BT_LOG*_STR()+` ones) and contain their <<log-levels,log
470level>> (short name) in their name.
471
472Each of the following macros evaluate the
473<<build-time-log-level,build-time log level>> definition and
474<<run-time-log-level,run-time log level>> expression (as defined by
475`BT_LOG_OUTPUT_LEVEL`) to log conditionally.
476
477See <<logging-instrument-c-file-gen,Instrument a C source file
478(generic)>> and <<logging-instrument-h-file-gen,Instrument a C header
479file (generic)>> to learn how to be able to use the following macros.
480
481`+BT_LOGT("format string", ...)+`::
482 Generic trace logging statement.
483
484`+BT_LOGD("format string", ...)+`::
485 Generic debug logging statement.
486
487`+BT_LOGI("format string", ...)+`::
488 Generic info logging statement.
489
490`+BT_LOGW("format string", ...)+`::
491 Generic warning logging statement.
492
493`+BT_LOGE("format string", ...)+`::
494 Generic error logging statement.
495
496`+BT_LOGF("format string", ...)+`::
497 Generic fatal logging statement.
498
499`+BT_LOGT_STR("preformatted string")+`::
500 Generic preformatted string trace logging statement.
501
502`+BT_LOGD_STR("preformatted string")+`::
503 Generic preformatted string debug logging statement.
504
505`+BT_LOGI_STR("preformatted string")+`::
506 Generic preformatted string info logging statement.
507
508`+BT_LOGW_STR("preformatted string")+`::
509 Generic preformatted string warning logging statement.
510
511`+BT_LOGE_STR("preformatted string")+`::
512 Generic preformatted string error logging statement.
513
514`+BT_LOGF_STR("preformatted string")+`::
515 Generic preformatted string fatal logging statement.
516
517`+BT_LOGT_MEM(data_ptr, data_size, "format string", ...)+`::
518 Generic memory trace logging statement.
519
520`+BT_LOGD_MEM(data_ptr, data_size, "format string", ...)+`::
521 Generic memory debug logging statement.
522
523`+BT_LOGI_MEM(data_ptr, data_size, "format string", ...)+`::
524 Generic memory info logging statement.
525
526`+BT_LOGW_MEM(data_ptr, data_size, "format string", ...)+`::
527 Generic memory warning logging statement.
528
529`+BT_LOGE_MEM(data_ptr, data_size, "format string", ...)+`::
530 Generic memory error logging statement.
531
532`+BT_LOGF_MEM(data_ptr, data_size, "format string", ...)+`::
533 Generic memory fatal logging statement.
534
535`+BT_LOGT_ERRNO("initial message", "format string", ...)+`::
536 Generic `errno` string trace logging statement.
537
538`+BT_LOGD_ERRNO("initial message", "format string", ...)+`::
539 Generic `errno` string debug logging statement.
540
541`+BT_LOGI_ERRNO("initial message", "format string", ...)+`::
542 Generic `errno` string info logging statement.
543
544`+BT_LOGW_ERRNO("initial message", "format string", ...)+`::
545 Generic `errno` string warning logging statement.
546
547`+BT_LOGE_ERRNO("initial message", "format string", ...)+`::
548 Generic `errno` string error logging statement.
549
550`+BT_LOGF_ERRNO("initial message", "format string", ...)+`::
551 Generic `errno` string fatal logging statement.
552
553
554[[lib-logging-statements]]
555==== Library-specific logging statement macros
556
557The Babeltrace library contains an internal logging API based on the
558generic logging framework. You can use it to log known Babeltrace
559objects without having to manually log each member.
560
561See <<logging-instrument-c-file-lib,Instrument a library C source file>>
562and <<logging-instrument-h-file-lib,Instrument a library C header file>> to
563learn how to be able to use the following macros.
564
565The library logging statement macros are named `+BT_LIB_LOG*()+` instead
566of `+BT_LOG*()+`:
567
568`+BT_LIB_LOGT("format string", ...)+`::
569 Library trace logging statement.
570
571`+BT_LIB_LOGD("format string", ...)+`::
572 Library debug logging statement.
573
574`+BT_LIB_LOGI("format string", ...)+`::
575 Library info logging statement.
576
577`+BT_LIB_LOGW("format string", ...)+`::
578 Library warning logging statement.
579
580`+BT_LIB_LOGE("format string", ...)+`::
581 Library error logging statement.
582
583`+BT_LIB_LOGF("format string", ...)+`::
584 Library fatal logging statement.
585
586The macros above accept the typical `printf()` conversion specifiers
587with the following limitations:
588
589* The `+*+` width specifier is not accepted.
590* The `+*+` precision specifier is not accepted.
591* The `j` and `t` length modifiers are not accepted.
592* The `n` format specifier is not accepted.
593* The format specifiers defined in `<inttypes.h>` are not accepted,
594 except for `PRId64`, `PRIu64`, `PRIx64`, `PRIX64`, `PRIo64`, and
595 `PRIi64`.
596
597The Babeltrace library custom conversion specifier is accepted. Its
598syntax is either `%!u` to format a UUID (`bt_uuid` type), or:
599
600. Introductory `%!` sequence.
601
602. **Optional**: `[` followed by a custom prefix for the printed fields
603 of this specifier, followed by `]`. The standard form is to end this
604 prefix with `-` so that, for example, with the prefix `tc-`, the
605 complete field name becomes `tc-addr`.
606
607. **Optional**: `pass:[+]` to print extended object members. This
608 depends on the provided format specifier.
609
610. Format specifier (see below).
611
612The available format specifiers are:
613
614[options="header,autowidth",cols="3"]
615|===
616|Specifier
617|Object
618|Expected C type
619
620|`F`
621|Trace IR field class
622|`+struct bt_field_class *+`
623
624|`f`
625|Trace IR field
626|`+struct bt_field *+`
627
628|`P`
629|Trace IR field path
630|`+struct bt_field_path *+`
631
632|`E`
633|Trace IR event class
634|`+struct bt_event_class *+`
635
636|`e`
637|Trace IR event
638|`+struct bt_event *+`
639
640|`S`
641|Trace IR stream class.
642|`+struct bt_stream_class *+`
643
644|`s`
645|Trace IR stream
646|`+struct bt_stream *+`
647
648|`a`
649|Trace IR packet
650|`+struct bt_packet *+`
651
652|`T`
653|Trace IR trace class
654|`+struct bt_trace_class *+`
655
656|`t`
657|Trace IR trace
658|`+struct bt_trace *+`
659
660|`K`
661|Trace IR clock class
662|`+struct bt_clock_class *+`
663
664|`k`
665|Trace IR clock snapshot
666|`+struct bt_clock_snapshot *+`
667
668|`v`
669|Value object
670|`+struct bt_value *+`
671
672|`n`
673|Message
674|`+struct bt_message *+`
675
676|`i`
677|Message iterator
678|`struct bt_message_iterator *`
679
680|`C`
681|Component class
682|`struct bt_component_class *`
683
684|`c`
685|Component
686|`+struct bt_component *+`
687
688|`p`
689|Port
690|`+struct bt_port *+`
691
692|`x`
693|Connection
694|`+struct bt_connection *+`
695
696|`g`
697|Graph
698|`+struct bt_graph *+`
699
700|`l`
701|Plugin
702|`const struct bt_plugin *`
703
704|`o`
705|Object pool
706|`+struct bt_object_pool *+`
707
708|`O`
709|Object
710|`+struct bt_object *+`
711|===
712
713Conversion specifier examples:
714
715* `%!f`
716* `%![my-event-]+e`
717* `%!t`
718* `%!+F`
719
720The ``, `` string (comma and space) is printed between individual
721fields, but **not after the last one**. Therefore, you must put this
722separator in the format string between two conversion specifiers, for
723example:
724
725[source,c]
726----
727BT_LIB_LOGW("Message: count=%u, %!E, %!+K", count, event_class, clock_class);
728----
729
730Example with a custom prefix:
731
732[source,c]
733----
734BT_LIB_LOGI("Some message: %![ec-a-]e, %![ec-b-]+e", ec_a, ec_b);
735----
736
737It is safe to pass `NULL` as any Babeltrace object parameter: the macros
738only print its null address.
739
740WARNING: Build-time `printf()` format checks are disabled for the
741`+BT_LIB_LOG*()+` macros because there are custom conversion specifiers,
742so make sure to test your logging statements.
743
744
745[[comp-logging-statements]]
746==== Component-specific logging statement macros
747
748There are available logging macros for components. They prepend a prefix
749including the component's name to the logging message.
750
751See <<logging-instrument-c-file-compcls,Instrument a component class C
752source file>> and <<logging-instrument-h-file-compcls,Instrument a
753component class C header file>> to learn how to be able to use the
754following macros.
755
756The component logging statement macros are named `+BT_COMP_LOG*()+`
757instead of `+BT_LOG*()+`:
758
759`+BT_COMP_LOGT("format string", ...)+`::
760 Component trace logging statement.
761
762`+BT_COMP_LOGD("format string", ...)+`::
763 Component debug logging statement.
764
765`+BT_COMP_LOGI("format string", ...)+`::
766 Component info logging statement.
767
768`+BT_COMP_LOGW("format string", ...)+`::
769 Component warning logging statement.
770
771`+BT_COMP_LOGE("format string", ...)+`::
772 Component error logging statement.
773
774`+BT_COMP_LOGF("format string", ...)+`::
775 Component fatal logging statement.
776
777`+BT_COMP_LOGT_STR("preformatted string")+`::
778 Component preformatted string trace logging statement.
779
780`+BT_COMP_LOGD_STR("preformatted string")+`::
781 Component preformatted string debug logging statement.
782
783`+BT_COMP_LOGI_STR("preformatted string")+`::
784 Component preformatted string info logging statement.
785
786`+BT_COMP_LOGW_STR("preformatted string")+`::
787 Component preformatted string warning logging statement.
788
789`+BT_COMP_LOGE_STR("preformatted string")+`::
790 Component preformatted string error logging statement.
791
792`+BT_COMP_LOGF_STR("preformatted string")+`::
793 Component preformatted string fatal logging statement.
794
795`+BT_COMP_LOGT_ERRNO("initial message", "format string", ...)+`::
796 Component `errno` string trace logging statement.
797
798`+BT_COMP_LOGD_ERRNO("initial message", "format string", ...)+`::
799 Component `errno` string debug logging statement.
800
801`+BT_COMP_LOGI_ERRNO("initial message", "format string", ...)+`::
802 Component `errno` string info logging statement.
803
804`+BT_COMP_LOGW_ERRNO("initial message", "format string", ...)+`::
805 Component `errno` string warning logging statement.
806
807`+BT_COMP_LOGE_ERRNO("initial message", "format string", ...)+`::
808 Component `errno` string error logging statement.
809
810`+BT_COMP_LOGF_ERRNO("initial message", "format string", ...)+`::
811 Component `errno` string fatal logging statement.
812
813`+BT_COMP_LOGT_MEM(data_ptr, data_size, "format string", ...)+`::
814 Component memory trace logging statement.
815
816`+BT_COMP_LOGD_MEM(data_ptr, data_size, "format string", ...)+`::
817 Component memory debug logging statement.
818
819`+BT_COMP_LOGI_MEM(data_ptr, data_size, "format string", ...)+`::
820 Component memory info logging statement.
821
822`+BT_COMP_LOGW_MEM(data_ptr, data_size, "format string", ...)+`::
823 Component memory warning logging statement.
824
825`+BT_COMP_LOGE_MEM(data_ptr, data_size, "format string", ...)+`::
826 Component memory error logging statement.
827
828`+BT_COMP_LOGF_MEM(data_ptr, data_size, "format string", ...)+`::
829 Component memory fatal logging statement.
830
831
832==== Conditional logging
833
834`+BT_LOG_IF(cond, statement)+`::
835 Execute `statement` only if `cond` is true.
836+
837Example:
838+
839--
840[source,c]
841----
842BT_LOG_IF(i < count / 2, BT_LOGD("Log this: i=%d", i));
843----
844--
845
846To check the <<build-time-log-level,build-time log level>>:
847
848[source,c]
849----
850#if BT_LOG_ENABLED_DEBUG
851...
852#endif
853----
854
855This tests if the _DEBUG_ level was enabled at build time. This means
856that the current, <<run-time-log-level,run-time log level>> _could_ be
857_DEBUG_, but it could also be higher. The rule of thumb is to use only
858logging statements at the same level in a `BT_LOG_ENABLED_*` conditional
859block.
860
861The available definitions for build-time conditions are:
862
863* `BT_LOG_ENABLED_TRACE`
864* `BT_LOG_ENABLED_DEBUG`
865* `BT_LOG_ENABLED_INFO`
866* `BT_LOG_ENABLED_WARN`
867* `BT_LOG_ENABLED_ERROR`
868* `BT_LOG_ENABLED_FATAL`
869
870To check the current, <<run-time-log-level,run-time log level>>:
871
872[source,c]
873----
874if (BT_LOG_ON_DEBUG) {
875 ...
876}
877----
878
879This tests if the _DEBUG_ log level is dynamically turned on
880(implies that it's also enabled at build time). This check could have a
881noticeable impact on performance.
882
883The available definitions for run-time conditions are:
884
885* `BT_LOG_ON_TRACE`
886* `BT_LOG_ON_DEBUG`
887* `BT_LOG_ON_INFO`
888* `BT_LOG_ON_WARN`
889* `BT_LOG_ON_ERROR`
890* `BT_LOG_ON_FATAL`
891
892Those macros check the module-specific log level symbol (defined by
893`BT_LOG_OUTPUT_LEVEL`).
894
895Never, ever write code which would be executed only to compute the
896fields of a logging statement outside a conditional logging scope,
897for example:
898
899[source,c]
900----
901int number = get_number_of_event_classes_with_property_x(...);
902BT_LOGD("Bla bla: number=%d", number);
903----
904
905Do this instead:
906
907[source,c]
908----
909if (BT_LOG_ON_DEBUG) {
910 int number = get_number_of_event_classes_with_property_x(...);
911 BT_LOGD("Bla bla: number=%d", number);
912}
913----
914
915Or even this:
916
917[source,c]
918----
919BT_LOGD("Bla bla: number=%d", get_number_of_event_classes_with_property_x(...));
920----
921
922
923=== Guides
924
925[[logging-instrument-c-file-gen]]
926==== Instrument a C source file (generic)
927
928To instrument a C source file (`.c`):
929
930. At the top of the file, before the first `#include` line (if any),
931 define your file's <<choose-a-logging-tag,logging tag>> name:
932+
933--
934[source,c]
935----
936#define BT_LOG_TAG "SUBSYS/MY-MODULE/MY-FILE"
937----
938--
939
940. Below the line above, define the source file's log level expression,
941 `BT_LOG_OUTPUT_LEVEL`. This expression is evaluated for each
942 <<gen-logging-statements,logging statement>> to know the current
943 <<run-time-log-level,run-time log level>>.
944+
945Examples:
946+
947[source,c]
948----
949/* Global log level variable */
950#define BT_LOG_OUTPUT_LEVEL module_global_log_level
951----
952+
953[source,c]
954----
955/* Local log level variable; must exist where you use BT_LOG*() */
956#define BT_LOG_OUTPUT_LEVEL log_level
957----
958+
959[source,c]
960----
961/* Object's log level; `obj` must exist where you use BT_LOG*() */
962#define BT_LOG_OUTPUT_LEVEL (obj->log_level)
963----
964
965. Include `"logging/log.h"`:
966+
967[source,c]
968----
969#include "logging/log.h"
970----
971
972. In the file, instrument your code with the
973 <<gen-logging-statements,generic logging statement macros>>.
974
975
976[[logging-instrument-h-file-gen]]
977==== Instrument a C header file (generic)
978
979To instrument a C header file (`.h`), if you have `static inline`
980functions in it:
981
982. Do not include `"logging/log.h"`!
983
984. Do one of:
985
986.. In the file, instrument your code with the
987 <<gen-logging-statements,generic logging statement macros>>, making
988 each of them conditional to the existence of the macro you're using:
989+
990[source,c]
991----
992static inline
993int some_function(int x)
994{
995 /* ... */
996
997#ifdef BT_LOGT
998 BT_LOGT(...);
999#endif
1000
1001 /* ... */
1002
1003#ifdef BT_LOGW_STR
1004 BT_LOGW_STR(...);
1005#endif
1006
1007 /* ... */
1008}
1009----
1010+
1011The C source files which include this header file determine if logging
1012is enabled or not for them, and if so, what is their
1013<<choose-a-logging-tag,logging tag>> and <<run-time-log-level,run-time
1014log level>> expression.
1015
1016.. Require that logging be enabled:
1017+
1018[source,c]
1019----
1020/* Protection: this file uses BT_LOG*() macros directly */
1021#ifndef BT_LOG_SUPPORTED
1022# error Please include "logging/log.h" before including this file.
1023#endif
1024----
1025+
1026Then, in the file, instrument your code with the
1027<<gen-logging-statements,generic logging statement macros>>.
1028
1029
1030[[logging-instrument-c-file-lib]]
1031==== Instrument a library C source file
1032
1033To instrument a library C source file (`.c`):
1034
1035. At the top of the file, before the first `#include` line (if any),
1036 define your file's <<choose-a-logging-tag,logging tag>> name (this
1037 tag must start with `LIB/`):
1038+
1039--
1040[source,c]
1041----
1042#define BT_LOG_TAG "LIB/THE-FILE"
1043----
1044--
1045
1046. Include `"lib/logging.h"`:
1047+
1048[source,c]
1049----
1050#include "lib/logging.h"
1051----
1052
1053. In the file, instrument your code with the
1054 <<lib-logging-statements,library logging statement macros>> or with
1055 the <<gen-logging-statements,generic logging statement macros>>.
1056
1057
1058[[logging-instrument-h-file-lib]]
1059==== Instrument a library C header file
1060
1061To instrument a library C header file (`.h`), if you have `static
1062inline` functions in it:
1063
1064. Do not include `"lib/logging.h"`!
1065
1066. Require that library logging be enabled:
1067+
1068[source,c]
1069----
1070/* Protection: this file uses BT_LIB_LOG*() macros directly */
1071#ifndef BT_LIB_LOG_SUPPORTED
1072# error Please include "lib/logging.h" before including this file.
1073#endif
1074----
1075
1076. In the file, instrument your code with the
1077 <<lib-logging-statements,library logging statement macros>> or with
1078 the <<gen-logging-statements,generic logging statement macros>>.
1079
1080
1081[[logging-instrument-c-file-compcls]]
1082==== Instrument a component class C source file
1083
1084To instrument a component class C source file (`.c`):
1085
1086. At the top of the file, before the first `#include` line (if any),
1087 define your file's <<choose-a-logging-tag,logging tag>> name (this tag
1088 must start with `PLUGIN/` followed by the component class identifier):
1089+
1090--
1091[source,c]
1092----
1093#define BT_LOG_TAG "PLUGIN/SRC.MY-PLUGIN.MY-SRC"
1094----
1095--
1096
1097. Below the line above, define the source file's log level expression,
1098 `BT_LOG_OUTPUT_LEVEL`. This expression is evaluated for each
1099 <<comp-logging-statements,logging statement>> to know the current
1100 <<run-time-log-level,run-time log level>>.
1101+
1102For a component class file, it is usually a member of a local component
1103private structure variable:
1104+
1105[source,c]
1106----
1107#define BT_LOG_OUTPUT_LEVEL (my_comp->log_level)
1108----
1109
1110. Below the line above, define `BT_COMP_LOG_SELF_COMP` to an expression
1111 which, evaluated in the context of the
1112 <<comp-logging-statements,logging statements>>, evaluates to the self
1113 component address (`+bt_self_component *+`) of the component.
1114+
1115This is usually a member of a local component private structure
1116variable:
1117+
1118[source,c]
1119----
1120#define BT_COMP_LOG_SELF_COMP (my_comp->self_comp)
1121----
1122
1123. Include `"plugins/comp-logging.h"`:
1124+
1125[source,c]
1126----
1127#include "plugins/comp-logging.h"
1128----
1129
1130. In the component initialization method, make sure to set the
1131 component private structure's log level member to the initial
1132 component's log level:
1133+
1134[source,c]
1135----
1136struct my_comp {
1137 bt_logging_level log_level;
1138 /* ... */
1139};
1140
1141BT_HIDDEN
1142bt_self_component_status my_comp_init(
1143 bt_self_component_source *self_comp_src,
1144 bt_value *params, void *init_method_data)
1145{
1146 struct my_comp *my_comp = g_new0(struct my_comp, 1);
1147 bt_self_component *self_comp =
1148 bt_self_component_source_as_self_component(self_comp_src);
1149 const bt_component *comp = bt_self_component_as_component(self_comp);
1150
1151 BT_ASSERT(my_comp);
1152 my_comp->log_level = bt_component_get_logging_level(comp);
1153
1154 /* ... */
1155}
1156----
1157
1158. In the file, instrument your code with the
1159 <<comp-logging-statements,component logging statement macros>>.
1160
1161
1162[[logging-instrument-h-file-compcls]]
1163==== Instrument a component class C header file
1164
1165To instrument a component class C header file (`.h`), if you have
1166`static inline` functions in it:
1167
1168. Do not include `"plugins/comp-logging.h"`!
1169
1170. Require that component logging be enabled:
1171+
1172[source,c]
1173----
1174/* Protection: this file uses BT_COMP_LOG*() macros directly */
1175#ifndef BT_COMP_LOG_SUPPORTED
1176# error Please include "plugins/comp-logging.h" before including this file.
1177#endif
1178----
1179
1180. In the file, instrument your code with the
1181 <<comp-logging-statements,component logging statement macros>>.
1182
1183
1184[[choose-a-logging-tag]]
1185==== Choose a logging tag
1186
1187Each logging-enabled C source file must define `BT_LOG_TAG` to a logging
1188tag. A logging tag is a namespace to identify the logging messages of
1189this specific source file.
1190
1191In general, a logging tag name _must_ be only uppercase letters, digits,
1192and the `-`, `.`, and `/` characters.
1193
1194Use `/` to show the subsystem to source file hierarchy.
1195
1196For the Babeltrace library, start with `LIB/`.
1197
1198For the CTF writer library, start with `CTF-WRITER/`.
1199
1200For component classes, use:
1201
1202[verse]
1203`PLUGIN/__CCTYPE__.__PNAME__.__CCNAME__[/__FILE__]`
1204
1205With:
1206
1207`__CCTYPE__`::
1208 Component class's type (`SRC`, `FLT`, or `SINK`).
1209
1210`__PNAME__`::
1211 Plugin's name.
1212
1213`__CCNAME__`::
1214 Component class's name.
1215
1216`__FILE__`::
1217 Additional information to specify the source file name or module.
1218
1219For plugins (files common to many component classes), use:
1220
1221[verse]
1222`PLUGIN/__PNAME__[/__FILE__]`
1223
1224With:
1225
1226`__PNAME__`::
1227 Plugin's name.
1228
1229`__FILE__`::
1230 Additional information to specify the source file name or module.
1231
1232
1233[[choose-a-log-level]]
1234==== Choose a log level
1235
1236Choosing the appropriate level for your logging statement is very
1237important.
1238
1239[options="header,autowidth",cols="1,2,3a,4"]
1240|===
1241|Log level |Description |Use cases |Expected impact on performance
1242
1243|_FATAL_
1244|
1245The program, library, or plugin cannot continue to work in this
1246condition: it must be terminated immediately.
1247
1248A _FATAL_-level logging statement should always be followed by
1249`abort()`.
1250|
1251* Unexpected return values from system calls.
1252* Logic error in internal code, for example an unexpected value in a
1253 `switch` statement.
1254* Failed assertion (within `BT_ASSERT()`).
1255* Unsatisfied library precondition (within `BT_ASSERT_PRE()`).
1256* Unsatisfied library postcondition (within `BT_ASSERT_POST()`).
1257|Almost none: always enabled.
1258
1259|_ERROR_
1260|
1261An important error which is somewhat not fatal, that is, the program,
1262library, or plugin can continue to work after this, but you judge that
1263it should be reported to the user.
1264
1265Usually, the program cannot recover from such an error, but it can at
1266least exit cleanly.
1267|
1268* Memory allocation errors.
1269* Wrong component initialization parameters.
1270* Corrupted, unrecoverable trace data.
1271* Failed to perform an operation which should work considering the
1272 implementation and the satisfied preconditions. For example, the
1273 failure to create an empty object (no parameters): most probably
1274 failed internally because of an allocation error.
1275* Almost any error in terminal elements: CLI and plugins.
1276|Almost none: always enabled.
1277
1278|_WARN_
1279|
1280An error which still allows the execution to continue, but you judge
1281that it should be reported to the user.
1282
1283_WARN_-level logging statements are for any error or weird action that
1284is directly or indirectly caused by the user, often through some bad
1285input data. For example, not having enough memory is considered beyond
1286the user's control, so we always log memory errors with an _ERROR_ level
1287(not _FATAL_ because we usually don't abort in this condition).
1288|
1289* Missing data within something that is expected to have it, but there's
1290 an alternative.
1291* Invalid file, but recoverable/fixable.
1292|Almost none: always enabled.
1293
1294|_INFO_
1295|
1296Any useful information which a non-developer user would possibly
1297understand.
1298
1299Anything logged with this level must _not_ happen repetitively on the
1300fast path, that is, nothing related to each message, for example. This
1301level is used for sporadic and one-shot events.
1302|
1303* CLI or component configuration report.
1304* Successful plugin, component, or message iterator initialization.
1305* In the library: anything related to plugins, graphs, component
1306 classes, components, message iterators, connections, and ports which
1307 is not on the fast path.
1308* Successful connection to or disconnection from another system.
1309* An _optional_ subsystem cannot be loaded.
1310* An _optional_ field/datum cannot be found.
1311|
1312Very little: always enabled.
1313
1314|_DEBUG_
1315|
1316Something that only Babeltrace developers would be interested into,
1317which can occur on the fast path, but not more often than once per
1318message.
1319
1320The _DEBUG_ level is the default <<build-time-log-level,build-time log
1321level>> as, since it's not _too_ verbose, the performance is similar to
1322an _INFO_ build.
1323|
1324* Object construction and destruction.
1325* Object recycling (except fields).
1326* Object copying (except fields and values).
1327* Object freezing (whatever the type, as freezing only occurs in
1328 developer mode).
1329* Object cancellation.
1330* Calling user methods and logging the result.
1331* Setting object properties (except fields and values).
1332|
1333Noticeable, but not as much as the _TRACE_ level: could be executed
1334in production if you're going to need a thorough log for support
1335tickets without having to rebuild the project.
1336
1337|_TRACE_
1338|
1339Low-level debugging context information (anything that does not fit the
1340other log levels). More appropriate for tracing in general.
1341|
1342* Reference count change.
1343* Fast path, low level state machine's state change.
1344* Get or set an object's property.
1345* Object comparison's intermediate results.
1346|Huge: not executed in production.
1347|===
1348
1349[IMPORTANT]
1350--
1351Make sure not to use a _WARN_ (or higher) log level when the
1352condition leading to the logging statement can occur under normal
1353circumstances.
1354
1355For example, a public function to get some object or
1356property from an object by name or key that fails to find the value is
1357not a warning scenario: the user could legitimately use this function to
1358check if the name/key exists in the object. In this case, use the
1359_TRACE_ level (or do not log at all).
1360--
1361
1362
1363[[message]]
1364==== Write an appropriate message
1365
1366Follow those rules when you write a logging statement's message:
1367
1368* Use an English sentence which starts with a capital letter.
1369
1370* Start the sentence with the appropriate verb tense depending on the
1371 context. For example:
1372+
1373--
1374** Beginning of operation (present continuous): _Creating ..._,
1375 _Copying ..._, _Serializing ..._, _Freezing ..._, _Destroying ..._
1376** End of operation (simple past): _Created ..._, _Successfully created ..._,
1377 _Failed to create ..._, _Set ..._ (simple past of _to set_ which is
1378 also _set_)
1379--
1380+
1381For warning and error messages, you can start the message with _Cannot_
1382or _Failed to_ followed by a verb if it's appropriate.
1383
1384* Do not include the log level in the message itself. For example,
1385 do not start the message with _Error while_ or _Warning:_.
1386
1387* Do not put newlines, tabs, or other special characters in the message,
1388 unless you want to log a string with such characters. Note that
1389 multiline logging messages can be hard to parse, analyze, and filter,
1390 however, so prefer multiple logging statements over a single statement
1391 with newlines.
1392
1393* **If there are fields that your logging statement must record**,
1394 follow the message with `:` followed by a space, then with the list of
1395 fields (more about this below). If there are no fields, end the
1396 sentence with a period.
1397
1398The statement's fields _must_ be a comma-separated list of
1399`__name__=__value__` tokens. Keep `__name__` as simple as possible; use
1400kebab case if possible. If `__value__` is a non-alphanumeric string, put
1401it between double quotes (`"%s"` specifier). Always use the `PRId64` and
1402`PRIu64` specifiers to log an `int64_t` or an `uint64_t` value. Use `%d`
1403to log a boolean value.
1404
1405Example:
1406
1407 "Cannot read stream data for indexing: path=\"%s\", name=\"%s\", "
1408 "stream-id=%" PRIu64 ", stream-fd=%d, "
1409 "index=%" PRIu64 ", status=%s, is-mapped=%d"
1410
1411By following a standard format for the statement fields, it is easier to
1412use tools like https://www.elastic.co/products/logstash[Logstash] or
1413even https://www.splunk.com/[Splunk] to split fields and analyze logs.
1414
1415Prefer the following suffixes in field names:
1416
1417[options="header,autowidth"]
1418|===
1419|Field name suffix |Description |Format specifier
1420
1421|`-addr` |Memory address |`%p`
1422|`-fd` |File descriptor |`%d`
1423|`-fp` |File stream (`+FILE *+`) |`%p`
1424|`-id` |Object's ID |`%" PRIu64 "`
1425|`-index` |Index |`%" PRIu64 "`
1426|`-name` |Object's name |`\"%s\"`
1427|===
1428
1429
1430=== Output
1431
1432The log is printed to the standard error stream. A log line contains the
1433time, the process and thread IDs, the <<log-levels,log level>>, the
1434<<choose-a-logging-tag,logging tag>>, the source's function name, file
1435name and line number, and the <<message,message>>.
1436
1437When Babeltrace supports terminal color codes (depends on the
1438`BABELTRACE_TERM_COLOR` environment variable's value and what the
1439standard output and error streams are plugged into), _INFO_-level lines
1440are blue, _WARN_-level lines are yellow, and _ERROR_-level and
1441_FATAL_-level lines are red.
1442
1443Log line example:
1444
1445----
144605-11 00:58:03.691 23402 23402 D VALUES bt_value_destroy@values.c:498 Destroying value: addr=0xb9c3eb0
1447----
1448
1449You can easily filter the log with `grep` or `ag`. For example, to keep
1450only the _DEBUG_-level logging messages that the `FIELD-CLASS` module
1451generates:
1452
1453----
1454$ babeltrace2 --log-level=D /path/to/trace |& ag 'D FIELD-CLASS'
1455----
1456
1457
1458== Valgrind
1459
1460To use Valgrind on an application (for example, the CLI or a test) which
1461loads libbabeltrace2, use:
1462
1463----
1464$ G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc \
1465 LIBBABELTRACE2_NO_DLCLOSE=1 valgrind --leak-check=full \
1466 --suppressions=/path/to/babeltrace/extras/valgrind/popt.supp app
1467----
1468
1469`G_SLICE=always-malloc` and `G_DEBUG=gc-friendly` is for GLib and
1470`PYTHONMALLOC=malloc` is for the Python interpreter, if it is used by
1471the Python plugin provider (Valgrind will probably show a lot of errors
1472which originate from the Python interpreter anyway).
1473
1474`LIBBABELTRACE2_NO_DLCLOSE=1` makes libbabeltrace2 not close the shared
1475libraries (plugins) which it loads. You need this to see the appropriate
1476backtrace when Valgrind shows errors.
1477
1478== Testing
1479
1480=== Python Bindings
1481
1482To run all the `bt2` Python package tests use:
1483
1484----
1485$ BT_TESTS_BUILDDIR=/path/to/build/babeltrace/tests \
1486 ./tests/bindings/python/bt2/test_python_bt2
1487----
1488
1489To run all the tests in a test module (e.g. `test_event.py`) use:
1490
1491----
1492$ BT_TESTS_BUILDDIR=/path/to/build/babeltrace/tests \
1493 ./tests/utils/run_python_bt2 python3 ./tests/utils/python/testrunner.py \
1494 -t test_event \
1495 ./tests/bindings/python/bt2/
1496----
1497
1498To run a specific test (e.g. `EventTestCase.test_clock_value`) in a test module
1499(e.g. `test_event.py`) use:
1500
1501----
1502$ BT_TESTS_BUILDDIR=/path/to/build/babeltrace/tests \
1503 ./tests/utils/run_python_bt2 python3 ./tests/utils/python/testrunner.py \
1504 -t test_event.EventTestCase.test_clock_value \
1505 ./tests/bindings/python/bt2/
1506----
This page took 0.028339 seconds and 4 git commands to generate.