Debian Codegraph @

lib/wp/log.c

raw
1 /* WirePlumber
2 *
3 * Copyright © 2020 Collabora Ltd.
4 * @author George Kiagiadakis <[email protected]>
5 *
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include "log.h"
10 #include "wp.h"
11 #include <pipewire/pipewire.h>
12 #include <spa/support/log.h>
13
14 WP_DEFINE_LOCAL_LOG_TOPIC ("wp-log")
15
16 /*!
17 * \defgroup wplog Debug Logging
18 * \{
19 */
20 /*!
21 * \def WP_DEFINE_LOCAL_LOG_TOPIC(name)
22 * \brief Defines a static \em WpLogTopic* variable called \em WP_LOCAL_LOG_TOPIC
23 *
24 * The log topic is automatically initialized to the given topic \a name when
25 * it is first used. The default logging macros expect this variable to be
26 * defined, so it is a good coding practice in the WirePlumber codebase to
27 * start all files at the top with:
28 * \code
29 * WP_DEFINE_LOCAL_LOG_TOPIC ("some-topic")
30 * \endcode
31 *
32 * \param name The name of the log topic
33 */
34 /*!
35 * \def WP_LOG_TOPIC_STATIC(var, name)
36 * \brief Defines a static \em WpLogTopic* variable called \a var with the given
37 * topic \a name
38 * \param var The name of the variable to define
39 * \param name The name of the log topic
40 */
41 /*!
42 * \def WP_LOG_TOPIC(var, name)
43 * \brief Defines a \em WpLogTopic* variable called \a var with the given
44 * topic \a name. Unlike WP_LOG_TOPIC_STATIC(), the variable defined here is
45 * not static, so it can be linked to by other object files.
46 * \param var The name of the variable to define
47 * \param name The name of the log topic
48 */
49 /*!
50 * \def WP_LOG_TOPIC_EXTERN(var)
51 * \brief Declares an extern \em WpLogTopic* variable called \a var.
52 * This variable is meant to be defined in a .c file with WP_LOG_TOPIC()
53 * \param var The name of the variable to declare
54 */
55 /*!
56 * \def WP_OBJECT_FORMAT
57 * \brief A format string to print GObjects with WP_OBJECT_ARGS()
58 * For example:
59 * \code
60 * GObject *myobj = ...;
61 * wp_debug ("This: " WP_OBJECT_FORMAT " is an object", WP_OBJECT_ARGS (myobj));
62 * \endcode
63 */
64 /*!
65 * \def WP_OBJECT_ARGS(object)
66 * \brief A macro to format an object for printing with WP_OBJECT_FORMAT
67 */
68 /*!
69 * \def wp_critical(...)
70 * \brief Logs a critical message to the standard log via GLib's logging system.
71 * \param ... A format string, followed by format arguments in printf() style
72 */
73 /*!
74 * \def wp_critical_object(object, ...)
75 * \brief Logs a critical message to the standard log via GLib's logging system.
76 * \param object A GObject associated with the log; this is printed in a special
77 * way to make it easier to track messages from a specific object
78 * \param ... A format string, followed by format arguments in printf() style
79 */
80 /*!
81 * \def wp_critical_boxed(type, object, ...)
82 * \brief Logs a critical message to the standard log via GLib's logging system.
83 * \param type The type of \a object
84 * \param object A boxed object associated with the log; this is printed in a
85 * special way to make it easier to track messages from a specific object.
86 * For some object types, contents from the object are also printed (ex WpSpaPod)
87 * \param ... A format string, followed by format arguments in printf() style
88 */
89 /*!
90 * \def wp_warning(...)
91 * \brief Logs a warning message to the standard log via GLib's logging system.
92 * \param ... A format string, followed by format arguments in printf() style
93 */
94 /*!
95 * \def wp_warning_object(object, ...)
96 * \brief Logs a warning message to the standard log via GLib's logging system.
97 * \param object A GObject associated with the log; this is printed in a special
98 * way to make it easier to track messages from a specific object
99 * \param ... A format string, followed by format arguments in printf() style
100 */
101 /*!
102 * \def wp_warning_boxed(type, object, ...)
103 * \brief Logs a warning message to the standard log via GLib's logging system.
104 * \param type The type of \a object
105 * \param object A boxed object associated with the log; this is printed in a
106 * special way to make it easier to track messages from a specific object.
107 * For some object types, contents from the object are also printed (ex WpSpaPod)
108 * \param ... A format string, followed by format arguments in printf() style
109 */
110 /*!
111 * \def wp_notice(...)
112 * \brief Logs a notice message to the standard log via GLib's logging system.
113 * \param ... A format string, followed by format arguments in printf() style
114 */
115 /*!
116 * \def wp_notice_object(object, ...)
117 * \brief Logs a notice message to the standard log via GLib's logging system.
118 * \param object A GObject associated with the log; this is printed in a special
119 * way to make it easier to track messages from a specific object
120 * \param ... A format string, followed by format arguments in printf() style
121 */
122 /*!
123 * \def wp_notice_boxed(type, object, ...)
124 * \brief Logs a notice message to the standard log via GLib's logging system.
125 * \param type The type of \a object
126 * \param object A boxed object associated with the log; this is printed in a
127 * special way to make it easier to track messages from a specific object.
128 * For some object types, contents from the object are also printed (ex WpSpaPod)
129 * \param ... A format string, followed by format arguments in printf() style
130 */
131 /*!
132 * \def wp_info(...)
133 * \brief Logs a info message to the standard log via GLib's logging system.
134 * \param ... A format string, followed by format arguments in printf() style
135 */
136 /*!
137 * \def wp_info_object(object, ...)
138 * \brief Logs a info message to the standard log via GLib's logging system.
139 * \param object A GObject associated with the log; this is printed in a special
140 * way to make it easier to track messages from a specific object
141 * \param ... A format string, followed by format arguments in printf() style
142 */
143 /*!
144 * \def wp_info_boxed(type, object, ...)
145 * \brief Logs a info message to the standard log via GLib's logging system.
146 * \param type The type of \a object
147 * \param object A boxed object associated with the log; this is printed in a
148 * special way to make it easier to track messages from a specific object.
149 * For some object types, contents from the object are also printed (ex WpSpaPod)
150 * \param ... A format string, followed by format arguments in printf() style
151 */
152 /*!
153 * \def wp_debug(...)
154 * \brief Logs a debug message to the standard log via GLib's logging system.
155 * \param ... A format string, followed by format arguments in printf() style
156 */
157 /*!
158 * \def wp_debug_object(object, ...)
159 * \brief Logs a debug message to the standard log via GLib's logging system.
160 * \param object A GObject associated with the log; this is printed in a special
161 * way to make it easier to track messages from a specific object
162 * \param ... A format string, followed by format arguments in printf() style
163 */
164 /*!
165 * \def wp_debug_boxed(type, object, ...)
166 * \brief Logs a debug message to the standard log via GLib's logging system.
167 * \param type The type of \a object
168 * \param object A boxed object associated with the log; this is printed in a
169 * special way to make it easier to track messages from a specific object.
170 * For some object types, contents from the object are also printed (ex WpSpaPod)
171 * \param ... A format string, followed by format arguments in printf() style
172 */
173 /*!
174 * \def wp_trace(...)
175 * \brief Logs a trace message to the standard log via GLib's logging system.
176 * \param ... A format string, followed by format arguments in printf() style
177 */
178 /*!
179 * \def wp_trace_object(object, ...)
180 * \brief Logs a trace message to the standard log via GLib's logging system.
181 * \param object A GObject associated with the log; this is printed in a special
182 * way to make it easier to track messages from a specific object
183 * \param ... A format string, followed by format arguments in printf() style
184 */
185 /*!
186 * \def wp_trace_boxed(type, object, ...)
187 * \brief Logs a trace message to the standard log via GLib's logging system.
188 * \param type The type of \a object
189 * \param object A boxed object associated with the log; this is printed in a
190 * special way to make it easier to track messages from a specific object.
191 * For some object types, contents from the object are also printed (ex WpSpaPod)
192 * \param ... A format string, followed by format arguments in printf() style
193 */
194 /*!
195 * \def wp_log(level, type, object, ...)
196 * \brief The generic form of all the logging macros
197 * \remark Don't use this directly, use one of the other logging macros
198 */
199 /*! \} */
200
201 static GString *spa_dbg_str = NULL;
202 #define spa_debug(...) \
203 ({ \
204 g_string_append_printf (spa_dbg_str, __VA_ARGS__); \
205 g_string_append_c (spa_dbg_str, '\n'); \
206 })
207
208 #include <spa/debug/pod.h>
209
210 #define DEFAULT_LOG_LEVEL 4 /* MESSAGE */
211 #define DEFAULT_LOG_LEVEL_FLAGS (G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR)
212
213 struct log_topic_pattern
214 {
215 GPatternSpec *spec;
216 gchar *spec_str;
217 gint log_level;
218 };
219
220 static struct {
221 gboolean use_color;
222 gboolean output_is_journal;
223 gboolean set_pw_log;
224 gint global_log_level;
225 GLogLevelFlags global_log_level_flags;
226 struct log_topic_pattern *patterns;
227 GPtrArray *log_topics;
228 GMutex log_topics_lock;
229 } log_state = {
230 .use_color = FALSE,
231 .output_is_journal = FALSE,
232 .set_pw_log = FALSE,
233 .global_log_level = DEFAULT_LOG_LEVEL,
234 .global_log_level_flags = DEFAULT_LOG_LEVEL_FLAGS,
235 .patterns = NULL,
236 .log_topics = NULL,
237 };
238
239 /* reference: https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit */
240 #define COLOR_RED "\033[1;31m"
241 #define COLOR_GREEN "\033[1;32m"
242 #define COLOR_YELLOW "\033[1;33m"
243 #define COLOR_BLUE "\033[1;34m"
244 #define COLOR_MAGENTA "\033[1;35m"
245 #define COLOR_CYAN "\033[1;36m"
246 #define COLOR_BRIGHT_RED "\033[1;91m"
247 #define COLOR_BRIGHT_GREEN "\033[1;92m"
248 #define COLOR_BRIGHT_YELLOW "\033[1;93m"
249 #define COLOR_BRIGHT_BLUE "\033[1;94m"
250 #define COLOR_BRIGHT_MAGENTA "\033[1;95m"
251 #define COLOR_BRIGHT_CYAN "\033[1;96m"
252
253 #define RESET_COLOR "\033[0m"
254
255 /* our palette */
256 #define DOMAIN_COLOR COLOR_MAGENTA
257 #define LOCATION_COLOR COLOR_BLUE
258
259 /* available colors for object printouts (the <Object:0xfoobar>) */
260 static const gchar *object_colors[] = {
261 COLOR_RED, COLOR_GREEN, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN,
262 COLOR_BRIGHT_RED, COLOR_BRIGHT_GREEN, COLOR_BRIGHT_YELLOW,
263 COLOR_BRIGHT_MAGENTA, COLOR_BRIGHT_CYAN
264 };
265
266 /*
267 * priority numbers are based on GLib's gmessages.c
268 * reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
269 */
270 static const struct {
271 GLogLevelFlags log_level_flags;
272 enum spa_log_level spa_level;
273 gchar name;
274 gchar priority[2];
275 gchar color[8];
276 } log_level_info[] = {
277 { 0, 0, 'U', "0", COLOR_BRIGHT_MAGENTA },
278 { G_LOG_LEVEL_ERROR, SPA_LOG_LEVEL_NONE, 'F', "3" /* LOG_ERR */, COLOR_BRIGHT_RED },
279 { G_LOG_LEVEL_CRITICAL,SPA_LOG_LEVEL_ERROR,'E', "4" /* LOG_WARNING */, COLOR_RED },
280 { G_LOG_LEVEL_WARNING, SPA_LOG_LEVEL_WARN, 'W', "4" /* LOG_WARNING */, COLOR_BRIGHT_YELLOW },
281 { G_LOG_LEVEL_MESSAGE, SPA_LOG_LEVEL_WARN, 'N', "5" /* LOG_NOTICE */, COLOR_BRIGHT_GREEN },
282 { G_LOG_LEVEL_INFO, SPA_LOG_LEVEL_INFO, 'I', "6" /* LOG_INFO */, COLOR_GREEN },
283 { G_LOG_LEVEL_DEBUG, SPA_LOG_LEVEL_DEBUG,'D', "7" /* LOG_DEBUG */, COLOR_BRIGHT_CYAN },
284 { WP_LOG_LEVEL_TRACE, SPA_LOG_LEVEL_TRACE,'T', "7" /* LOG_DEBUG */, COLOR_CYAN },
285 };
286
287 /* map glib's log levels, which are flags in the range (1<<2) to (1<<8),
288 to the 1-7 range; first calculate the integer part of log2(log_level)
289 to bring it down to 2-8 and substract 1 */
290 static G_GNUC_CONST inline gint
291 level_index_from_flags (GLogLevelFlags log_level)
292 {
293 gint logarithm = 0;
294 while ((log_level >>= 1) != 0)
295 logarithm += 1;
296 return (logarithm >= 2 && logarithm <= 8) ? (logarithm - 1) : 0;
297 }
298
299 /* map an index in the log_level_info table to a single GLogLevelFlags flag */
300 static G_GNUC_CONST inline GLogLevelFlags
301 level_index_to_flag (gint lvl_index)
302 {
303 if (lvl_index < 0 || lvl_index >= (gint) G_N_ELEMENTS (log_level_info))
304 return 0;
305 return log_level_info [lvl_index].log_level_flags;
306 }
307
308 /* map an index in the log_level_info table to an OR combination of all the
309 GLogLevelFlags that are enabled at this level */
310 static G_GNUC_CONST inline GLogLevelFlags
311 level_index_to_full_flags (gint lvl_index)
312 {
313 GLogLevelFlags flags = 0;
314 for (gint i = 1; i <= lvl_index; i++) {
315 flags |= level_index_to_flag (i);
316 }
317 return flags;
318 }
319
320 /* map a SPA_LOG_LEVEL_* to an index in the log_level_info table;
321 if warn_to_notice == TRUE, SPA_LOG_LEVEL_WARN maps to 4 (G_LOG_LEVEL_MESSAGE)
322 and index 3 (G_LOG_LEVEL_WARNING) can not be returned
323 if warn_to_notice == FALSE, SPA_LOG_LEVEL_WARN maps to 3 (G_LOG_LEVEL_WARNING)
324 and index 4 (G_LOG_LEVEL_MESSAGE) can not be returned */
325 static G_GNUC_CONST inline gint
326 level_index_from_spa (gint spa_lvl, gboolean warn_to_notice)
327 {
328 if (G_UNLIKELY (spa_lvl <= SPA_LOG_LEVEL_NONE))
329 return 1;
330 else if (spa_lvl == SPA_LOG_LEVEL_ERROR)
331 return 2;
332 else if (spa_lvl == SPA_LOG_LEVEL_WARN)
333 return warn_to_notice ? 4 : 3;
334 else if (G_UNLIKELY (spa_lvl > SPA_LOG_LEVEL_TRACE))
335 return (gint) G_N_ELEMENTS (log_level_info) - 1;
336 else
337 return spa_lvl + 2;
338 }
339
340 /* map an index in the log_level_info table to a SPA_LOG_LEVEL_*
341 here, G_LOG_LEVEL_MESSAGE maps to SPA_LOG_LEVEL_WARN */
342 static G_GNUC_CONST inline gint
343 level_index_to_spa (gint lvl_index)
344 {
345 if (lvl_index < 0 || lvl_index >= (gint) G_N_ELEMENTS (log_level_info))
346 return 0;
347 return log_level_info [lvl_index].spa_level;
348 }
349
350 static gboolean
351 level_index_from_string (const char *str, gint *lvl)
352 {
353 g_return_val_if_fail (str != NULL, FALSE);
354
355 /* level is always 1 character */
356 if (str[0] != '\0' && str[1] == '\0') {
357 for (guint i = 1; i < G_N_ELEMENTS (log_level_info); i++) {
358 if (str[0] == log_level_info[i].name) {
359 *lvl = i;
360 return TRUE;
361 }
362 }
363
364 if (str[0] >= '0' && str[0] <= '5') {
365 *lvl = level_index_from_spa (str[0] - '0', TRUE);
366 return TRUE;
367 }
368 }
369 return FALSE;
370 }
371
372 static gint
373 find_topic_log_level (const gchar *log_topic, bool *has_custom_level)
374 {
375 struct log_topic_pattern *pttrn = log_state.patterns;
376 guint len;
377 g_autofree gchar *reverse_topic = NULL;
378 gint log_level = log_state.global_log_level;
379
380 /* reverse string and length required for pattern match */
381 len = strlen (log_topic);
382 reverse_topic = g_strreverse (g_strndup (log_topic, len));
383
384 while (pttrn && pttrn->spec &&
385 !g_pattern_match (pttrn->spec, len, log_topic, reverse_topic))
386 pttrn++;
387
388 if (pttrn && pttrn->spec) {
389 if (has_custom_level)
390 *has_custom_level = true;
391 log_level = pttrn->log_level;
392 } else if (has_custom_level) {
393 *has_custom_level = false;
394 }
395
396 return log_level;
397 }
398
399 static void
400 log_topic_update_level (WpLogTopic *topic)
401 {
402 gint log_level = find_topic_log_level (topic->topic_name, NULL);
403 gint flags = topic->flags & ~WP_LOG_TOPIC_LEVEL_MASK;
404
405 flags |= level_index_to_full_flags (log_level);
406
407 topic->flags = flags;
408 }
409
410 static void
411 update_log_topic_levels (void)
412 {
413 guint i;
414
415 g_mutex_lock (&log_state.log_topics_lock);
416
417 if (log_state.log_topics)
418 for (i = 0; i < log_state.log_topics->len; ++i)
419 log_topic_update_level (g_ptr_array_index (log_state.log_topics, i));
420
421 g_mutex_unlock (&log_state.log_topics_lock);
422 }
423
424 static void
425 free_patterns (struct log_topic_pattern *patterns)
426 {
427 struct log_topic_pattern *p = patterns;
428
429 while (p && p->spec) {
430 g_clear_pointer (&p->spec, g_pattern_spec_free);
431 g_clear_pointer (&p->spec_str, g_free);
432 ++p;
433 }
434
435 g_free (patterns);
436 }
437
438 /* Parse value to log level and patterns. If no global level in string,
439 global_log_level is not modified. */
440 static gboolean
441 parse_log_level (const gchar *level_str, struct log_topic_pattern **global_patterns, gint *global_log_level)
442 {
443 struct log_topic_pattern *patterns = NULL, *pttrn;
444 gint n_tokens = 0;
445 gchar **tokens = NULL;
446 int level = *global_log_level;
447
448 *global_patterns = NULL;
449
450 if (level_str && level_str[0] != '\0') {
451 /* [<glob>:]<level>,..., */
452 tokens = pw_split_strv (level_str, ",", INT_MAX, &n_tokens);
453 }
454
455 /* allocate enough space to hold all pattern specs */
456 patterns = g_malloc_n ((n_tokens + 2), sizeof (struct log_topic_pattern));
457 pttrn = patterns;
458 if (!patterns)
459 g_error ("unable to allocate space for %d log patterns", n_tokens + 2);
460
461 for (gint i = 0; i < n_tokens; i++) {
462 gint n_tok;
463 gchar **tok;
464 gint lvl;
465
466 tok = pw_split_strv (tokens[i], ":", 2, &n_tok);
467 if (n_tok == 2 && level_index_from_string (tok[1], &lvl)) {
468 pttrn->spec = g_pattern_spec_new (tok[0]);
469 pttrn->spec_str = g_strdup (tok[0]);
470 pttrn->log_level = lvl;
471 pttrn++;
472 } else if (n_tok == 1 && level_index_from_string (tok[0], &lvl)) {
473 level = lvl;
474 } else {
475 pttrn->spec = NULL;
476 pw_free_strv (tok);
477 free_patterns (patterns);
478 return FALSE;
479 }
480
481 pw_free_strv (tok);
482 }
483
484 /* disable pipewire connection trace by default */
485 pttrn->spec = g_pattern_spec_new ("conn.*");
486 pttrn->spec_str = g_strdup ("conn.*");
487 pttrn->log_level = 0;
488 pttrn++;
489
490 /* terminate with NULL */
491 pttrn->spec = NULL;
492 pttrn->spec_str = NULL;
493 pttrn->log_level = 0;
494
495 pw_free_strv (tokens);
496
497 *global_patterns = patterns;
498 *global_log_level = level;
499 return TRUE;
500 }
501
502 static gchar *
503 format_pw_log_level_string (gint level, const struct log_topic_pattern *patterns)
504 {
505 GString *str = g_string_new (NULL);
506 const struct log_topic_pattern *p;
507
508 g_string_printf (str, "%d", level_index_to_spa (level));
509
510 for (p = patterns; p && p->spec; ++p)
511 g_string_append_printf (str, ",%s:%d", p->spec_str, level_index_to_spa (p->log_level));
512
513 return g_string_free (str, FALSE);
514 }
515
516 gboolean
517 wp_log_set_level (const gchar *level_str)
518 {
519 gint level;
520 GLogLevelFlags flags;
521 struct log_topic_pattern *patterns;
522
523 level = DEFAULT_LOG_LEVEL;
524 if (!parse_log_level (level_str, &patterns, &level))
525 return FALSE;
526
527 flags = level_index_to_full_flags (level);
528
529 g_mutex_lock (&log_state.log_topics_lock);
530 log_state.global_log_level = level;
531 log_state.global_log_level_flags = flags;
532 SPA_SWAP (log_state.patterns, patterns);
533 g_mutex_unlock (&log_state.log_topics_lock);
534
535 free_patterns (patterns);
536
537 update_log_topic_levels ();
538
539 wp_spa_log_get_instance()->level = level_index_to_spa (level);
540
541 if (log_state.set_pw_log) {
542 #if PW_CHECK_VERSION(1,1,0)
543 g_autofree gchar *pw_pattern = format_pw_log_level_string (log_state.global_log_level, log_state.patterns);
544 pw_log_set_level_string (pw_pattern);
545 #else
546 pw_log_set_level (level_index_to_spa (level));
547 #endif
548 }
549
550 return TRUE;
551 }
552
553 /*!
554 * \brief private, called from wp_init()
555 * \ingroup wplog
556 * \private
557 */
558 void
559 wp_log_init (gint flags)
560 {
561 log_state.use_color = g_log_writer_supports_color (fileno (stderr));
562 log_state.output_is_journal = g_log_writer_is_journald (fileno (stderr));
563 log_state.set_pw_log = flags & WP_INIT_SET_PW_LOG && !g_getenv ("WIREPLUMBER_NO_PW_LOG");
564
565 if (flags & WP_INIT_SET_GLIB_LOG)
566 g_log_set_writer_func (wp_log_writer_default, NULL, NULL);
567
568 /* set the spa_log interface that pipewire will use */
569 if (log_state.set_pw_log)
570 pw_log_set (wp_spa_log_get_instance ());
571
572 if (!wp_log_set_level (g_getenv ("WIREPLUMBER_DEBUG"))) {
573 wp_warning ("Ignoring invalid value in WIREPLUMBER_DEBUG");
574 wp_log_set_level (NULL);
575 }
576
577 if (log_state.set_pw_log) {
578 /* always set PIPEWIRE_DEBUG for 2 reasons:
579 * 1. to overwrite it from the environment, in case the user has set it
580 * 2. to prevent pw_context from parsing "log.level" from the config file;
581 * we do this ourselves here and allows us to have more control over
582 * the whole process.
583 */
584 g_autofree gchar *lvl_str = format_pw_log_level_string (log_state.global_log_level, log_state.patterns);
585 g_warn_if_fail (g_setenv ("PIPEWIRE_DEBUG", lvl_str, TRUE));
586 }
587 }
588
589 static void
590 log_topic_register (WpLogTopic *topic)
591 {
592 if (!log_state.log_topics)
593 log_state.log_topics = g_ptr_array_new ();
594
595 g_ptr_array_add (log_state.log_topics, topic);
596
597 log_topic_update_level (topic);
598 topic->flags |= WP_LOG_TOPIC_FLAG_INITIALIZED;
599 }
600
601 static void
602 log_topic_unregister (WpLogTopic *topic)
603 {
604 if (!log_state.log_topics)
605 return;
606
607 g_ptr_array_remove_fast (log_state.log_topics, topic);
608
609 if (log_state.log_topics->len == 0) {
610 g_ptr_array_free (log_state.log_topics, TRUE);
611 log_state.log_topics = NULL;
612 }
613 }
614
615 /*!
616 * \brief Registers a log topic.
617 *
618 * The log topic must be unregistered using \ref wp_log_topic_unregister
619 * before its lifetime ends.
620 *
621 * This function is threadsafe.
622 *
623 * \ingroup wplog
624 */
625 void
626 wp_log_topic_register (WpLogTopic *topic)
627 {
628 g_mutex_lock (&log_state.log_topics_lock);
629 log_topic_register (topic);
630 g_mutex_unlock (&log_state.log_topics_lock);
631 }
632
633 /*!
634 * \brief Unregisters a log topic.
635 *
636 * This function is threadsafe.
637 *
638 * \ingroup wplog
639 */
640 void
641 wp_log_topic_unregister (WpLogTopic *topic)
642 {
643 g_mutex_lock (&log_state.log_topics_lock);
644 log_topic_unregister (topic);
645 g_mutex_unlock (&log_state.log_topics_lock);
646 }
647
648 /*!
649 * \brief Initializes a log topic. Internal function, don't use it directly
650 * \ingroup wplog
651 */
652 void
653 wp_log_topic_init (WpLogTopic *topic)
654 {
655 g_mutex_lock (&log_state.log_topics_lock);
656 if ((topic->flags & WP_LOG_TOPIC_FLAG_INITIALIZED) == 0) {
657 if (topic->flags & WP_LOG_TOPIC_FLAG_STATIC) {
658 /* Auto-register log topics that have infinite lifetime */
659 log_topic_register (topic);
660 } else {
661 log_topic_update_level (topic);
662 topic->flags |= WP_LOG_TOPIC_FLAG_INITIALIZED;
663 }
664 }
665 g_mutex_unlock (&log_state.log_topics_lock);
666 }
667
668 typedef struct _WpLogFields WpLogFields;
669 struct _WpLogFields
670 {
671 const gchar *log_topic;
672 const gchar *file;
673 const gchar *line;
674 const gchar *func;
675 const gchar *message;
676 gint log_level;
677 gboolean debug;
678 GType object_type;
679 gconstpointer object;
680 };
681
682 static void
683 wp_log_fields_init (WpLogFields *lf,
684 const gchar *log_topic,
685 gint log_level,
686 gboolean debug,
687 const gchar *file,
688 const gchar *line,
689 const gchar *func,
690 GType object_type,
691 gconstpointer object,
692 const gchar *message)
693 {
694 lf->log_topic = log_topic ? log_topic : "default";
695 lf->log_level = log_level;
696 lf->debug = debug;
697 lf->file = file;
698 lf->line = line;
699 lf->func = func;
700 lf->object_type = object_type;
701 lf->object = object;
702 lf->message = message ? message : "(null)";
703 }
704
705 static gboolean
706 wp_want_debug_log (const struct spa_log_topic *topic)
707 {
708 return spa_log_level_topic_enabled (wp_spa_log_get_instance(), topic, SPA_LOG_LEVEL_DEBUG);
709 }
710
711 static void
712 wp_log_fields_init_from_glib (WpLogFields *lf, GLogLevelFlags log_level_flags,
713 const GLogField *fields, gsize n_fields)
714 {
715 wp_log_fields_init (lf, NULL, level_index_from_flags (log_level_flags),
716 wp_want_debug_log (NULL),
717 NULL, NULL, NULL, 0, NULL, NULL);
718
719 for (guint i = 0; i < n_fields; i++) {
720 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0 && fields[i].value) {
721 lf->log_topic = fields[i].value;
722 }
723 else if (g_strcmp0 (fields[i].key, "MESSAGE") == 0 && fields[i].value) {
724 lf->message = fields[i].value;
725 }
726 else if (g_strcmp0 (fields[i].key, "CODE_FILE") == 0) {
727 lf->file = fields[i].value;
728 }
729 else if (g_strcmp0 (fields[i].key, "CODE_LINE") == 0) {
730 lf->line = fields[i].value;
731 }
732 else if (g_strcmp0 (fields[i].key, "CODE_FUNC") == 0) {
733 lf->func = fields[i].value;
734 }
735 }
736 }
737
738 static void
739 wp_log_fields_write_to_stream (WpLogFields *lf, FILE *s)
740 {
741 gint64 now;
742 time_t now_secs;
743 struct tm now_tm;
744 gchar time_buf[128];
745
746 now = g_get_real_time ();
747 now_secs = (time_t) (now / G_USEC_PER_SEC);
748 localtime_r (&now_secs, &now_tm);
749 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", &now_tm);
750
751 fprintf (s, "%s%c %s.%06d %s%18.18s %s%s:%s:%s:%s %s\n",
752 /* level */
753 log_state.use_color ? log_level_info[lf->log_level].color : "",
754 log_level_info[lf->log_level].name,
755 /* timestamp */
756 time_buf,
757 (gint) (now % G_USEC_PER_SEC),
758 /* domain */
759 log_state.use_color ? DOMAIN_COLOR : "",
760 lf->log_topic,
761 /* file, line, function */
762 log_state.use_color ? LOCATION_COLOR : "",
763 lf->file,
764 lf->line,
765 lf->func,
766 log_state.use_color ? RESET_COLOR : "",
767 /* message */
768 lf->message);
769 fflush (s);
770 }
771
772 static gboolean
773 wp_log_fields_write_to_journal (WpLogFields *lf)
774 {
775 GLogField fields[10];
776 gsize n_fields = 0;
777 g_autofree gchar *full_message = NULL;
778 const gchar *message = lf->message ? lf->message : "";
779 g_autofree gchar *pid = g_strdup_printf("%d", getpid());
780 g_autofree gchar *tid = g_strdup_printf("%d", gettid());
781 #ifdef HAS_SHORT_NAME
782 const gchar *syslog_identifier = program_invocation_short_name;
783 #else
784 const gchar *syslog_identifier = g_get_prgname();
785 #endif
786
787 if (lf->debug) {
788 if (lf->file && lf->line && lf->func) {
789 g_autofree gchar *file = g_path_get_basename(lf->file);
790
791 message = full_message = g_strdup_printf("%c %s%s[%s:%s:%s]: %s",
792 log_level_info[lf->log_level].name,
793 lf->log_topic ? lf->log_topic : "",
794 lf->log_topic ? " " : "",
795 file, lf->line, lf->func, message);
796 } else {
797 message = full_message = g_strdup_printf("%c %s%s%s",
798 log_level_info[lf->log_level].name,
799 lf->log_topic ? lf->log_topic : "",
800 lf->log_topic ? ": " : "",
801 message);
802 }
803 } else if (lf->log_topic) {
804 message = full_message = g_strdup_printf("%s: %s", lf->log_topic, message);
805 }
806
807 fields[n_fields++] = (GLogField) { "SYSLOG_PID", pid, -1 };
808 fields[n_fields++] = (GLogField) { "TID", tid, -1 };
809 fields[n_fields++] = (GLogField) { "SYSLOG_IDENTIFIER", syslog_identifier, -1 };
810 fields[n_fields++] = (GLogField) { "SYSLOG_FACILITY", "3", -1 };
811 fields[n_fields++] = (GLogField) { "PRIORITY", log_level_info[lf->log_level].priority, -1 };
812 if (lf->file)
813 fields[n_fields++] = (GLogField) { "CODE_FILE", lf->file, -1 };
814 if (lf->line)
815 fields[n_fields++] = (GLogField) { "CODE_LINE", lf->line, -1 };
816 if (lf->func)
817 fields[n_fields++] = (GLogField) { "CODE_FUNC", lf->func, -1 };
818 if (lf->log_topic)
819 fields[n_fields++] = (GLogField) { "TOPIC", lf->log_topic, -1 };
820 fields[n_fields++] = (GLogField) { "MESSAGE", message, -1 };
821
822 /* the log level flags are not used in this function, so we can pass 0 */
823 return (g_log_writer_journald (0, fields, n_fields, NULL) == G_LOG_WRITER_HANDLED);
824 }
825
826 static inline gchar *
827 wp_log_fields_format_message (WpLogFields *lf)
828 {
829 g_autofree gchar *extra_message = NULL;
830 g_autofree gchar *extra_object = NULL;
831 const gchar *object_color = "";
832
833 if (log_state.use_color) {
834 guint h = g_direct_hash (lf->object) % G_N_ELEMENTS (object_colors);
835 object_color = object_colors[h];
836 }
837
838 if (lf->object_type == WP_TYPE_SPA_POD && lf->object && !spa_dbg_str) {
839 spa_dbg_str = g_string_new (lf->message);
840 g_string_append (spa_dbg_str, ":\n");
841 spa_debug_pod (2, NULL, wp_spa_pod_get_spa_pod (lf->object));
842 extra_message = g_string_free (spa_dbg_str, FALSE);
843 spa_dbg_str = NULL;
844 }
845 else if (lf->object && g_type_is_a (lf->object_type, WP_TYPE_PROXY) &&
846 (wp_object_test_active_features ((WpObject *) lf->object, WP_PROXY_FEATURE_BOUND))) {
847 extra_object = g_strdup_printf (":%u:",
848 wp_proxy_get_bound_id ((WpProxy *) lf->object));
849 }
850
851 return g_strdup_printf ("%s<%s%s%p>%s %s",
852 object_color,
853 lf->object_type != 0 ? g_type_name (lf->object_type) : "",
854 extra_object ? extra_object : ":",
855 lf->object,
856 log_state.use_color ? RESET_COLOR : "",
857 extra_message ? extra_message : lf->message);
858 }
859
860 static GLogWriterOutput
861 wp_log_fields_log (WpLogFields *lf)
862 {
863 g_autofree gchar *full_message = NULL;
864
865 /* in the unlikely event that someone messed with stderr... */
866 if (G_UNLIKELY (!stderr || fileno (stderr) < 0))
867 return G_LOG_WRITER_UNHANDLED;
868
869 /* format the message to include the object */
870 if (lf->object_type) {
871 lf->message = full_message = wp_log_fields_format_message (lf);
872 }
873
874 /* write complete field information to the journal if we are logging to it */
875 if (log_state.output_is_journal && wp_log_fields_write_to_journal (lf))
876 return G_LOG_WRITER_HANDLED;
877
878 wp_log_fields_write_to_stream (lf, stderr);
879 return G_LOG_WRITER_HANDLED;
880 }
881
882 /*!
883 * \brief WirePlumber's GLogWriterFunc
884 *
885 * This is installed automatically when you call wp_init() with
886 * WP_INIT_SET_GLIB_LOG set in the flags
887 * \ingroup wplog
888 */
889 GLogWriterOutput
890 wp_log_writer_default (GLogLevelFlags log_level_flags,
891 const GLogField *fields, gsize n_fields, gpointer user_data)
892 {
893 WpLogFields lf = {0};
894
895 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
896 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
897
898 wp_log_fields_init_from_glib (&lf, log_level_flags, fields, n_fields);
899
900 /* check if debug level & topic is enabled */
901 if (lf.log_level > find_topic_log_level (lf.log_topic, NULL))
902 return G_LOG_WRITER_HANDLED;
903
904 return wp_log_fields_log (&lf);
905 }
906
907 /*!
908 * \brief Used internally by the debug logging macros. Avoid using it directly.
909 *
910 * \deprecated Use \ref wp_logt_checked instead.
911 *
912 * This assumes that the arguments are correct and that the log_topic is
913 * enabled for the given log_level. No additional checks are performed.
914 * \ingroup wplog
915 */
916 void
917 wp_log_checked (
918 const gchar *log_topic,
919 GLogLevelFlags log_level_flags,
920 const gchar *file,
921 const gchar *line,
922 const gchar *func,
923 GType object_type,
924 gconstpointer object,
925 const gchar *message_format,
926 ...)
927 {
928 WpLogFields lf = {0};
929 g_autofree gchar *message = NULL;
930 va_list args;
931
932 va_start (args, message_format);
933 message = g_strdup_vprintf (message_format, args);
934 va_end (args);
935
936 wp_log_fields_init (&lf, log_topic, level_index_from_flags (log_level_flags),
937 wp_want_debug_log (NULL),
938 file, line, func, object_type, object, message);
939 wp_log_fields_log (&lf);
940 }
941
942 /*!
943 * \brief Used internally by the debug logging macros. Avoid using it directly.
944 *
945 * This assumes that the arguments are correct and that the log_topic is
946 * enabled for the given log_level. No additional checks are performed.
947 * \ingroup wplog
948 */
949 void
950 wp_logt_checked (
951 const WpLogTopic *topic,
952 GLogLevelFlags log_level_flags,
953 const gchar *file,
954 const gchar *line,
955 const gchar *func,
956 GType object_type,
957 gconstpointer object,
958 const gchar *message_format,
959 ...)
960 {
961 WpLogFields lf = {0};
962 g_autofree gchar *message = NULL;
963 va_list args;
964 const gchar *log_topic = topic ? topic->topic_name : NULL;
965 gboolean debug;
966
967 if (topic)
968 debug = (topic->flags & WP_LOG_TOPIC_LEVEL_MASK & G_LOG_LEVEL_DEBUG);
969 else
970 debug = wp_want_debug_log (NULL);
971
972 va_start (args, message_format);
973 message = g_strdup_vprintf (message_format, args);
974 va_end (args);
975
976 wp_log_fields_init (&lf, log_topic, level_index_from_flags (log_level_flags), debug,
977 file, line, func, object_type, object, message);
978 wp_log_fields_log (&lf);
979 }
980
981 static G_GNUC_PRINTF (7, 0) void
982 wp_spa_log_logtv (void *object,
983 enum spa_log_level level,
984 const struct spa_log_topic *topic,
985 const char *file,
986 int line,
987 const char *func,
988 const char *fmt,
989 va_list args)
990 {
991 WpLogFields lf = {0};
992 gint log_level = level_index_from_spa (level, FALSE);
993 g_autofree gchar *message = NULL;
994 gchar line_str[11];
995
996 sprintf (line_str, "%d", line);
997 message = g_strdup_vprintf (fmt, args);
998
999 wp_log_fields_init (&lf, topic ? topic->topic : NULL, log_level,
1000 wp_want_debug_log (topic),
1001 file, line_str, func, 0, NULL, message);
1002 wp_log_fields_log (&lf);
1003 }
1004
1005 static G_GNUC_PRINTF (7, 8) void
1006 wp_spa_log_logt (void *object,
1007 enum spa_log_level level,
1008 const struct spa_log_topic *topic,
1009 const char *file,
1010 int line,
1011 const char *func,
1012 const char *fmt, ...)
1013 {
1014 va_list args;
1015 va_start (args, fmt);
1016 wp_spa_log_logtv (object, level, topic, file, line, func, fmt, args);
1017 va_end (args);
1018 }
1019
1020 static G_GNUC_PRINTF (6, 0) void
1021 wp_spa_log_logv (void *object,
1022 enum spa_log_level level,
1023 const char *file,
1024 int line,
1025 const char *func,
1026 const char *fmt,
1027 va_list args)
1028 {
1029 wp_spa_log_logtv (object, level, NULL, file, line, func, fmt, args);
1030 }
1031
1032 static G_GNUC_PRINTF (6, 7) void
1033 wp_spa_log_log (void *object,
1034 enum spa_log_level level,
1035 const char *file,
1036 int line,
1037 const char *func,
1038 const char *fmt, ...)
1039 {
1040 va_list args;
1041 va_start (args, fmt);
1042 wp_spa_log_logtv (object, level, NULL, file, line, func, fmt, args);
1043 va_end (args);
1044 }
1045
1046 static void
1047 wp_spa_log_topic_init (void *object, struct spa_log_topic *topic)
1048 {
1049 gint log_level = find_topic_log_level (topic->topic, &topic->has_custom_level);
1050 topic->level = level_index_to_spa (log_level);
1051 }
1052
1053 static const struct spa_log_methods wp_spa_log_methods = {
1054 SPA_VERSION_LOG_METHODS,
1055 .log = wp_spa_log_log,
1056 .logv = wp_spa_log_logv,
1057 .logt = wp_spa_log_logt,
1058 .logtv = wp_spa_log_logtv,
1059 .topic_init = wp_spa_log_topic_init,
1060 };
1061
1062 static struct spa_log wp_spa_log = {
1063 .iface = { SPA_TYPE_INTERFACE_Log, SPA_VERSION_LOG, { &wp_spa_log_methods, NULL } },
1064 .level = SPA_LOG_LEVEL_WARN,
1065 };
1066
1067 /*!
1068 * \brief Gets WirePlumber's instance of `spa_log`
1069 * \ingroup wplog
1070 * \returns WirePlumber's instance of `spa_log`, which can be used to redirect
1071 * PipeWire's log messages to the currently installed GLogWriterFunc.
1072 * This is installed automatically when you call wp_init() with
1073 * WP_INIT_SET_PW_LOG set in the flags
1074 */
1075 struct spa_log *
1076 wp_spa_log_get_instance (void)
1077 {
1078 return &wp_spa_log;
1079 }