1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
33 * @Title: Message Output and Debugging Functions
34 * @Short_description: functions to output messages and help debug applications
36 * These functions provide support for outputting messages.
38 * The g_return family of macros (g_return_if_fail(),
39 * g_return_val_if_fail(), g_return_if_reached(),
40 * g_return_val_if_reached()) should only be used for programming
41 * errors, a typical use case is checking for invalid parameters at
42 * the beginning of a public function. They should not be used if
43 * you just mean "if (error) return", they should only be used if
44 * you mean "if (bug in program) return". The program behavior is
45 * generally considered undefined after one of these checks fails.
46 * They are not intended for normal control flow, only to give a
47 * perhaps-helpful warning before giving up.
49 * Structured logging output is supported using g_log_structured(). This differs
50 * from the traditional g_log() API in that log messages are handled as a
51 * collection of key–value pairs representing individual pieces of information,
52 * rather than as a single string containing all the information in an arbitrary
55 * The convenience macros g_info(), g_message(), g_debug(), g_warning() and g_error()
56 * will use the traditional g_log() API unless you define the symbol
57 * %G_LOG_USE_STRUCTURED before including `glib.h`. But note that even messages
58 * logged through the traditional g_log() API are ultimatively passed to
59 * g_log_structured(), so that all log messages end up in same destination.
60 * If %G_LOG_USE_STRUCTURED is defined, g_test_expect_message() will become
61 * ineffective for the wrapper macros g_warning() and friends (see
62 * [Testing for Messages][testing-for-messages]).
64 * The support for structured logging was motivated by the following needs (some
65 * of which were supported previously; others weren’t):
66 * * Support for multiple logging levels.
67 * * Structured log support with the ability to add `MESSAGE_ID`s (see
68 * g_log_structured()).
69 * * Moving the responsibility for filtering log messages from the program to
70 * the log viewer — instead of libraries and programs installing log handlers
71 * (with g_log_set_handler()) which filter messages before output, all log
72 * messages are outputted, and the log viewer program (such as `journalctl`)
73 * must filter them. This is based on the idea that bugs are sometimes hard
74 * to reproduce, so it is better to log everything possible and then use
75 * tools to analyse the logs than it is to not be able to reproduce a bug to
76 * get additional log data. Code which uses logging in performance-critical
77 * sections should compile out the g_log_structured() calls in
78 * release builds, and compile them in in debugging builds.
79 * * A single writer function which handles all log messages in a process, from
80 * all libraries and program code; rather than multiple log handlers with
81 * poorly defined interactions between them. This allows a program to easily
82 * change its logging policy by changing the writer function, for example to
83 * log to an additional location or to change what logging output fallbacks
84 * are used. The log writer functions provided by GLib are exposed publicly
85 * so they can be used from programs’ log writers. This allows log writer
86 * policy and implementation to be kept separate.
87 * * If a library wants to add standard information to all of its log messages
88 * (such as library state) or to redact private data (such as passwords or
89 * network credentials), it should use a wrapper function around its
90 * g_log_structured() calls or implement that in the single log writer
92 * * If a program wants to pass context data from a g_log_structured() call to
93 * its log writer function so that, for example, it can use the correct
94 * server connection to submit logs to, that user data can be passed as a
95 * zero-length #GLogField to g_log_structured_array().
96 * * Color output needed to be supported on the terminal, to make reading
97 * through logs easier.
99 * ## Using Structured Logging ## {#using-structured-logging}
101 * To use structured logging (rather than the old-style logging), either use
102 * the g_log_structured() and g_log_structured_array() functions; or define
103 * `G_LOG_USE_STRUCTURED` before including any GLib header, and use the
104 * g_message(), g_debug(), g_error() (etc.) macros.
106 * You do not need to define `G_LOG_USE_STRUCTURED` to use g_log_structured(),
107 * but it is a good idea to avoid confusion.
109 * ## Log Domains ## {#log-domains}
111 * Log domains may be used to broadly split up the origins of log messages.
112 * Typically, there are one or a few log domains per application or library.
113 * %G_LOG_DOMAIN should be used to define the default log domain for the current
114 * compilation unit — it is typically defined at the top of a source file, or in
115 * the preprocessor flags for a group of source files.
117 * Log domains must be unique, and it is recommended that they are the
118 * application or library name, optionally followed by a hyphen and a sub-domain
119 * name. For example, `bloatpad` or `bloatpad-io`.
121 * ## Debug Message Output ## {#debug-message-output}
123 * The default log functions (g_log_default_handler() for the old-style API and
124 * g_log_writer_default() for the structured API) both drop debug and
125 * informational messages by default, unless the log domains of those messages
126 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
129 * It is recommended that custom log writer functions re-use the
130 * `G_MESSAGES_DEBUG` environment variable, rather than inventing a custom one,
131 * so that developers can re-use the same debugging techniques and tools across
132 * projects. Since GLib 2.68, this can be implemented by dropping messages
133 * for which g_log_writer_default_would_drop() returns %TRUE.
135 * ## Testing for Messages ## {#testing-for-messages}
137 * With the old g_log() API, g_test_expect_message() and
138 * g_test_assert_expected_messages() could be used in simple cases to check
139 * whether some code under test had emitted a given log message. These
140 * functions have been deprecated with the structured logging API, for several
142 * * They relied on an internal queue which was too inflexible for many use
143 * cases, where messages might be emitted in several orders, some
144 * messages might not be emitted deterministically, or messages might be
145 * emitted by unrelated log domains.
146 * * They do not support structured log fields.
147 * * Examining the log output of code is a bad approach to testing it, and
148 * while it might be necessary for legacy code which uses g_log(), it should
149 * be avoided for new code using g_log_structured().
151 * They will continue to work as before if g_log() is in use (and
152 * %G_LOG_USE_STRUCTURED is not defined). They will do nothing if used with the
153 * structured logging API.
155 * Examining the log output of code is discouraged: libraries should not emit to
156 * `stderr` during defined behaviour, and hence this should not be tested. If
157 * the log emissions of a library during undefined behaviour need to be tested,
158 * they should be limited to asserting that the library aborts and prints a
159 * suitable error message before aborting. This should be done with
160 * g_test_trap_assert_stderr().
162 * If it is really necessary to test the structured log messages emitted by a
163 * particular piece of code – and the code cannot be restructured to be more
164 * suitable to more conventional unit testing – you should write a custom log
165 * writer function (see g_log_set_writer_func()) which appends all log messages
166 * to a queue. When you want to check the log messages, examine and clear the
167 * queue, ignoring irrelevant log messages (for example, from log domains other
168 * than the one under test).
181 #if defined(__linux__) && !defined(__BIONIC__)
182 #include <sys/types.h>
183 #include <sys/socket.h>
190 #include "gbacktrace.h"
191 #include "gcharset.h"
192 #include "gconvert.h"
193 #include "genviron.h"
194 #include "glib-init.h"
195 #include "glib-private.h"
198 #include "gpattern.h"
199 #include "gprintfint.h"
200 #include "gstrfuncs.h"
202 #include "gtestutils.h"
204 #include "gthreadprivate.h"
205 #include "gutilsprivate.h"
207 #if defined(__linux__) && !defined(__BIONIC__)
208 #include "gjournal-private.h"
216 #include <process.h> /* For getpid() */
218 # include <windows.h>
220 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
221 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
230 * Defines the log domain. See [Log Domains](#log-domains).
232 * Libraries should define this so that any messages
233 * which they log can be differentiated from messages from other
234 * libraries and application code. But be careful not to define
235 * it in any public header files.
237 * Log domains must be unique, and it is recommended that they are the
238 * application or library name, optionally followed by a hyphen and a sub-domain
239 * name. For example, `bloatpad` or `bloatpad-io`.
241 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
242 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
243 * environment variable.
245 * For example, GTK uses this in its `Makefile.am`:
247 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
250 * Applications can choose to leave it as the default %NULL (or `""`)
251 * domain. However, defining the domain offers the same advantages as
260 * GLib log levels that are considered fatal by default.
262 * This is not used if structured logging is enabled; see
263 * [Using Structured Logging][using-structured-logging].
268 * @log_domain: the log domain of the message
269 * @log_level: the log level of the message (including the
270 * fatal and recursion flags)
271 * @message: the message to process
272 * @user_data: user data, set in g_log_set_handler()
274 * Specifies the prototype of log handler functions.
276 * The default log handler, g_log_default_handler(), automatically appends a
277 * new-line character to @message when printing it. It is advised that any
278 * custom log handler functions behave similarly, so that logging calls in user
279 * code do not need modifying to add a new-line character to the message if the
280 * log handler is changed.
282 * This is not used if structured logging is enabled; see
283 * [Using Structured Logging][using-structured-logging].
288 * @G_LOG_FLAG_RECURSION: internal flag
289 * @G_LOG_FLAG_FATAL: internal flag
290 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
291 * This level is also used for messages produced by g_assert().
292 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
294 * This level is also used for messages produced by g_return_if_fail()
295 * and g_return_val_if_fail().
296 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
297 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
298 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
299 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
300 * @G_LOG_LEVEL_MASK: a mask including all log levels
302 * Flags specifying the level of log messages.
304 * It is possible to change how GLib treats messages of the various
305 * levels using g_log_set_handler() and g_log_set_fatal_mask().
309 * G_LOG_LEVEL_USER_SHIFT:
311 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
312 * Higher bits can be used for user-defined log levels.
317 * @...: format string, followed by parameters to insert
318 * into the format string (as with printf())
320 * A convenience function/macro to log a normal message.
322 * If g_log_default_handler() is used as the log handler function, a new-line
323 * character will automatically be appended to @..., and need not be entered
326 * If structured logging is enabled, this will use g_log_structured();
327 * otherwise it will use g_log(). See
328 * [Using Structured Logging][using-structured-logging].
333 * @...: format string, followed by parameters to insert
334 * into the format string (as with printf())
336 * A convenience function/macro to log a warning message. The message should
337 * typically *not* be translated to the user's language.
339 * This is not intended for end user error reporting. Use of #GError is
340 * preferred for that instead, as it allows calling functions to perform actions
341 * conditional on the type of error.
343 * Warning messages are intended to be used in the event of unexpected
344 * external conditions (system misconfiguration, missing files,
345 * other trusted programs violating protocol, invalid contents in
346 * trusted files, etc.)
348 * If attempting to deal with programmer errors (for example, incorrect function
349 * parameters) then you should use %G_LOG_LEVEL_CRITICAL instead.
351 * g_warn_if_reached() and g_warn_if_fail() log at %G_LOG_LEVEL_WARNING.
353 * You can make warnings fatal at runtime by setting the `G_DEBUG`
354 * environment variable (see
355 * [Running GLib Applications](glib-running.html)):
358 * G_DEBUG=fatal-warnings gdb ./my-program
361 * Any unrelated failures can be skipped over in
362 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
364 * If g_log_default_handler() is used as the log handler function,
365 * a newline character will automatically be appended to @..., and
366 * need not be entered manually.
368 * If structured logging is enabled, this will use g_log_structured();
369 * otherwise it will use g_log(). See
370 * [Using Structured Logging][using-structured-logging].
375 * @...: format string, followed by parameters to insert
376 * into the format string (as with printf())
378 * Logs a "critical warning" (%G_LOG_LEVEL_CRITICAL).
380 * Critical warnings are intended to be used in the event of an error
381 * that originated in the current process (a programmer error).
382 * Logging of a critical error is by definition an indication of a bug
383 * somewhere in the current program (or its libraries).
385 * g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and
386 * g_return_val_if_reached() log at %G_LOG_LEVEL_CRITICAL.
388 * You can make critical warnings fatal at runtime by
389 * setting the `G_DEBUG` environment variable (see
390 * [Running GLib Applications](glib-running.html)):
393 * G_DEBUG=fatal-warnings gdb ./my-program
396 * You can also use g_log_set_always_fatal().
398 * Any unrelated failures can be skipped over in
399 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
401 * The message should typically *not* be translated to the
404 * If g_log_default_handler() is used as the log handler function, a new-line
405 * character will automatically be appended to @..., and need not be entered
408 * If structured logging is enabled, this will use g_log_structured();
409 * otherwise it will use g_log(). See
410 * [Using Structured Logging][using-structured-logging].
415 * @...: format string, followed by parameters to insert
416 * into the format string (as with printf())
418 * A convenience function/macro to log an error message. The message should
419 * typically *not* be translated to the user's language.
421 * This is not intended for end user error reporting. Use of #GError is
422 * preferred for that instead, as it allows calling functions to perform actions
423 * conditional on the type of error.
425 * Error messages are always fatal, resulting in a call to G_BREAKPOINT()
426 * to terminate the application. This function will
427 * result in a core dump; don't use it for errors you expect.
428 * Using this function indicates a bug in your program, i.e.
429 * an assertion failure.
431 * If g_log_default_handler() is used as the log handler function, a new-line
432 * character will automatically be appended to @..., and need not be entered
435 * If structured logging is enabled, this will use g_log_structured();
436 * otherwise it will use g_log(). See
437 * [Using Structured Logging][using-structured-logging].
442 * @...: format string, followed by parameters to insert
443 * into the format string (as with printf())
445 * A convenience function/macro to log an informational message. Seldom used.
447 * If g_log_default_handler() is used as the log handler function, a new-line
448 * character will automatically be appended to @..., and need not be entered
451 * Such messages are suppressed by the g_log_default_handler() and
452 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
455 * If structured logging is enabled, this will use g_log_structured();
456 * otherwise it will use g_log(). See
457 * [Using Structured Logging][using-structured-logging].
464 * @...: format string, followed by parameters to insert
465 * into the format string (as with printf())
467 * A convenience function/macro to log a debug message. The message should
468 * typically *not* be translated to the user's language.
470 * If g_log_default_handler() is used as the log handler function, a new-line
471 * character will automatically be appended to @..., and need not be entered
474 * Such messages are suppressed by the g_log_default_handler() and
475 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
478 * If structured logging is enabled, this will use g_log_structured();
479 * otherwise it will use g_log(). See
480 * [Using Structured Logging][using-structured-logging].
485 /* --- structures --- */
486 typedef struct _GLogDomain GLogDomain;
487 typedef struct _GLogHandler GLogHandler;
491 GLogLevelFlags fatal_mask;
492 GLogHandler *handlers;
498 GLogLevelFlags log_level;
501 GDestroyNotify destroy;
505 static void g_default_print_func (const gchar *string);
506 static void g_default_printerr_func (const gchar *string);
508 /* --- variables --- */
509 static GMutex g_messages_lock;
510 static GLogDomain *g_log_domains = NULL;
511 static GPrintFunc glib_print_func = g_default_print_func;
512 static GPrintFunc glib_printerr_func = g_default_printerr_func;
513 static GPrivate g_log_depth;
514 static GPrivate g_log_structured_depth;
515 static GLogFunc default_log_func = g_log_default_handler;
516 static gpointer default_log_data = NULL;
517 static GTestLogFatalFunc fatal_log_func = NULL;
518 static gpointer fatal_log_data;
519 static GLogWriterFunc log_writer_func = g_log_writer_default;
520 static gpointer log_writer_user_data = NULL;
521 static GDestroyNotify log_writer_user_data_free = NULL;
522 static gboolean g_log_debug_enabled = FALSE; /* (atomic) */
524 /* --- functions --- */
526 static void _g_log_abort (gboolean breakpoint);
527 static inline const char * format_string (const char *format,
529 char **out_allocated_string)
530 G_GNUC_PRINTF (1, 0);
531 static inline FILE * log_level_to_file (GLogLevelFlags log_level);
534 _g_log_abort (gboolean breakpoint)
536 gboolean debugger_present;
538 if (g_test_subprocess ())
540 /* If this is a test case subprocess then it probably caused
541 * this error message on purpose, so just exit() rather than
542 * abort()ing, to avoid triggering any system crash-reporting
549 debugger_present = IsDebuggerPresent ();
551 /* Assume GDB is attached. */
552 debugger_present = TRUE;
553 #endif /* !G_OS_WIN32 */
555 if (debugger_present && breakpoint)
562 static gboolean win32_keep_fatal_message = FALSE;
564 /* This default message will usually be overwritten. */
565 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
566 * called with huge strings, is it?
568 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
569 static gchar *fatal_msg_ptr = fatal_msg_buf;
577 if (win32_keep_fatal_message)
579 memcpy (fatal_msg_ptr, buf, len);
580 fatal_msg_ptr += len;
585 write (fd, buf, len);
589 #define write(fd, buf, len) dowrite(fd, buf, len)
594 write_string (FILE *stream,
597 if (fputs (string, stream) == EOF)
599 /* Something failed, but it's not an error we can handle at glib level
600 * so let's just continue without the compiler blaming us
606 write_string_sized (FILE *stream,
610 /* Is it nul-terminated? */
612 write_string (stream, string);
613 else if (fwrite (string, 1, length, stream) < (size_t) length)
615 /* Something failed, but it's not an error we can handle at glib level
616 * so let's just continue without the compiler blaming us
622 g_log_find_domain_L (const gchar *log_domain)
626 domain = g_log_domains;
629 if (strcmp (domain->log_domain, log_domain) == 0)
631 domain = domain->next;
637 g_log_domain_new_L (const gchar *log_domain)
641 domain = g_new (GLogDomain, 1);
642 domain->log_domain = g_strdup (log_domain);
643 domain->fatal_mask = G_LOG_FATAL_MASK;
644 domain->handlers = NULL;
646 domain->next = g_log_domains;
647 g_log_domains = domain;
653 g_log_domain_check_free_L (GLogDomain *domain)
655 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
656 domain->handlers == NULL)
658 GLogDomain *last, *work;
662 work = g_log_domains;
668 last->next = domain->next;
670 g_log_domains = domain->next;
671 g_free (domain->log_domain);
682 g_log_domain_get_handler_L (GLogDomain *domain,
683 GLogLevelFlags log_level,
686 if (domain && log_level)
688 GLogHandler *handler;
690 handler = domain->handlers;
693 if ((handler->log_level & log_level) == log_level)
695 *data = handler->data;
696 return handler->log_func;
698 handler = handler->next;
702 *data = default_log_data;
703 return default_log_func;
707 * g_log_set_always_fatal:
708 * @fatal_mask: the mask containing bits set for each level
709 * of error which is to be fatal
711 * Sets the message levels which are always fatal, in any log domain.
712 * When a message with any of these levels is logged the program terminates.
713 * You can only set the levels defined by GLib to be fatal.
714 * %G_LOG_LEVEL_ERROR is always fatal.
716 * You can also make some message levels fatal at runtime by setting
717 * the `G_DEBUG` environment variable (see
718 * [Running GLib Applications](glib-running.html)).
720 * Libraries should not call this function, as it affects all messages logged
721 * by a process, including those from other libraries.
723 * Structured log messages (using g_log_structured() and
724 * g_log_structured_array()) are fatal only if the default log writer is used;
725 * otherwise it is up to the writer function to determine which log messages
726 * are fatal. See [Using Structured Logging][using-structured-logging].
728 * Returns: the old fatal mask
731 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
733 GLogLevelFlags old_mask;
735 /* restrict the global mask to levels that are known to glib
736 * since this setting applies to all domains
738 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
739 /* force errors to be fatal */
740 fatal_mask |= G_LOG_LEVEL_ERROR;
741 /* remove bogus flag */
742 fatal_mask &= ~G_LOG_FLAG_FATAL;
744 g_mutex_lock (&g_messages_lock);
745 old_mask = g_log_always_fatal;
746 g_log_always_fatal = fatal_mask;
747 g_mutex_unlock (&g_messages_lock);
753 * g_log_set_fatal_mask:
754 * @log_domain: the log domain
755 * @fatal_mask: the new fatal mask
757 * Sets the log levels which are fatal in the given domain.
758 * %G_LOG_LEVEL_ERROR is always fatal.
760 * This has no effect on structured log messages (using g_log_structured() or
761 * g_log_structured_array()). To change the fatal behaviour for specific log
762 * messages, programs must install a custom log writer function using
763 * g_log_set_writer_func(). See
764 * [Using Structured Logging][using-structured-logging].
766 * This function is mostly intended to be used with
767 * %G_LOG_LEVEL_CRITICAL. You should typically not set
768 * %G_LOG_LEVEL_WARNING, %G_LOG_LEVEL_MESSAGE, %G_LOG_LEVEL_INFO or
769 * %G_LOG_LEVEL_DEBUG as fatal except inside of test programs.
771 * Returns: the old fatal mask for the log domain
774 g_log_set_fatal_mask (const gchar *log_domain,
775 GLogLevelFlags fatal_mask)
777 GLogLevelFlags old_flags;
783 /* force errors to be fatal */
784 fatal_mask |= G_LOG_LEVEL_ERROR;
785 /* remove bogus flag */
786 fatal_mask &= ~G_LOG_FLAG_FATAL;
788 g_mutex_lock (&g_messages_lock);
790 domain = g_log_find_domain_L (log_domain);
792 domain = g_log_domain_new_L (log_domain);
793 old_flags = domain->fatal_mask;
795 domain->fatal_mask = fatal_mask;
796 g_log_domain_check_free_L (domain);
798 g_mutex_unlock (&g_messages_lock);
805 * @log_domain: (nullable): the log domain, or %NULL for the default ""
807 * @log_levels: the log levels to apply the log handler for.
808 * To handle fatal and recursive messages as well, combine
809 * the log levels with the %G_LOG_FLAG_FATAL and
810 * %G_LOG_FLAG_RECURSION bit flags.
811 * @log_func: the log handler function
812 * @user_data: data passed to the log handler
814 * Sets the log handler for a domain and a set of log levels.
816 * To handle fatal and recursive messages the @log_levels parameter
817 * must be combined with the %G_LOG_FLAG_FATAL and %G_LOG_FLAG_RECURSION
820 * Note that since the %G_LOG_LEVEL_ERROR log level is always fatal, if
821 * you want to set a handler for this log level you must combine it with
824 * This has no effect if structured logging is enabled; see
825 * [Using Structured Logging][using-structured-logging].
827 * Here is an example for adding a log handler for all warning messages
828 * in the default domain:
830 * |[<!-- language="C" -->
831 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
832 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
835 * This example adds a log handler for all critical messages from GTK:
837 * |[<!-- language="C" -->
838 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
839 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
842 * This example adds a log handler for all messages from GLib:
844 * |[<!-- language="C" -->
845 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
846 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
849 * Returns: the id of the new handler
852 g_log_set_handler (const gchar *log_domain,
853 GLogLevelFlags log_levels,
857 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
861 * g_log_set_handler_full: (rename-to g_log_set_handler)
862 * @log_domain: (nullable): the log domain, or %NULL for the default ""
864 * @log_levels: the log levels to apply the log handler for.
865 * To handle fatal and recursive messages as well, combine
866 * the log levels with the %G_LOG_FLAG_FATAL and
867 * %G_LOG_FLAG_RECURSION bit flags.
868 * @log_func: the log handler function
869 * @user_data: data passed to the log handler
870 * @destroy: destroy notify for @user_data, or %NULL
872 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
874 * This has no effect if structured logging is enabled; see
875 * [Using Structured Logging][using-structured-logging].
877 * Returns: the id of the new handler
882 g_log_set_handler_full (const gchar *log_domain,
883 GLogLevelFlags log_levels,
886 GDestroyNotify destroy)
888 static guint handler_id = 0;
890 GLogHandler *handler;
892 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
893 g_return_val_if_fail (log_func != NULL, 0);
898 handler = g_new (GLogHandler, 1);
900 g_mutex_lock (&g_messages_lock);
902 domain = g_log_find_domain_L (log_domain);
904 domain = g_log_domain_new_L (log_domain);
906 handler->id = ++handler_id;
907 handler->log_level = log_levels;
908 handler->log_func = log_func;
909 handler->data = user_data;
910 handler->destroy = destroy;
911 handler->next = domain->handlers;
912 domain->handlers = handler;
914 g_mutex_unlock (&g_messages_lock);
920 * g_log_set_default_handler:
921 * @log_func: the log handler function
922 * @user_data: data passed to the log handler
924 * Installs a default log handler which is used if no
925 * log handler has been set for the particular log domain
926 * and log level combination. By default, GLib uses
927 * g_log_default_handler() as default log handler.
929 * This has no effect if structured logging is enabled; see
930 * [Using Structured Logging][using-structured-logging].
932 * Returns: the previous default log handler
937 g_log_set_default_handler (GLogFunc log_func,
940 GLogFunc old_log_func;
942 g_mutex_lock (&g_messages_lock);
943 old_log_func = default_log_func;
944 default_log_func = log_func;
945 default_log_data = user_data;
946 g_mutex_unlock (&g_messages_lock);
952 * g_test_log_set_fatal_handler:
953 * @log_func: the log handler function.
954 * @user_data: data passed to the log handler.
956 * Installs a non-error fatal log handler which can be
957 * used to decide whether log messages which are counted
958 * as fatal abort the program.
960 * The use case here is that you are running a test case
961 * that depends on particular libraries or circumstances
962 * and cannot prevent certain known critical or warning
963 * messages. So you install a handler that compares the
964 * domain and message to precisely not abort in such a case.
966 * Note that the handler is reset at the beginning of
967 * any test case, so you have to set it inside each test
968 * function which needs the special behavior.
970 * This handler has no effect on g_error messages.
972 * This handler also has no effect on structured log messages (using
973 * g_log_structured() or g_log_structured_array()). To change the fatal
974 * behaviour for specific log messages, programs must install a custom log
975 * writer function using g_log_set_writer_func().See
976 * [Using Structured Logging][using-structured-logging].
981 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
984 g_mutex_lock (&g_messages_lock);
985 fatal_log_func = log_func;
986 fatal_log_data = user_data;
987 g_mutex_unlock (&g_messages_lock);
991 * g_log_remove_handler:
992 * @log_domain: the log domain
993 * @handler_id: the id of the handler, which was returned
994 * in g_log_set_handler()
996 * Removes the log handler.
998 * This has no effect if structured logging is enabled; see
999 * [Using Structured Logging][using-structured-logging].
1002 g_log_remove_handler (const gchar *log_domain,
1007 g_return_if_fail (handler_id > 0);
1012 g_mutex_lock (&g_messages_lock);
1013 domain = g_log_find_domain_L (log_domain);
1016 GLogHandler *work, *last;
1019 work = domain->handlers;
1022 if (work->id == handler_id)
1025 last->next = work->next;
1027 domain->handlers = work->next;
1028 g_log_domain_check_free_L (domain);
1029 g_mutex_unlock (&g_messages_lock);
1031 work->destroy (work->data);
1039 g_mutex_unlock (&g_messages_lock);
1040 g_info ("%s: could not find handler with id '%d' for domain \"%s\"",
1041 G_STRLOC, handler_id, log_domain);
1044 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1046 (wc >= 0x80 && wc < 0xa0)))
1049 strdup_convert (const gchar *string,
1050 const gchar *charset)
1052 if (!g_utf8_validate (string, -1, NULL))
1054 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1057 for (p = (guchar *)string; *p; p++)
1059 if (CHAR_IS_SAFE(*p) &&
1060 !(*p == '\r' && *(p + 1) != '\n') &&
1062 g_string_append_c (gstring, *p);
1064 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1067 return g_string_free (gstring, FALSE);
1073 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1078 /* Not thread-safe, but doesn't matter if we print the warning twice
1080 static gboolean warned = FALSE;
1084 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1088 return g_strdup (string);
1093 /* For a radix of 8 we need at most 3 output bytes for 1 input
1094 * byte. Additionally we might need up to 2 output bytes for the
1095 * readix prefix and 1 byte for the trailing NULL.
1097 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1100 format_unsigned (gchar *buf,
1108 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1110 if (radix != 8 && radix != 10 && radix != 16)
1128 else if (radix == 8)
1143 /* Again we can't use g_assert; actually this check should _never_ fail. */
1144 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1157 buf[i] = c + 'a' - 10;
1164 /* string size big enough to hold level prefix */
1165 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1167 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1169 /* these are emitted by the default log handler */
1170 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1171 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1172 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1174 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1175 gboolean use_color);
1176 static const gchar *color_reset (gboolean use_color);
1178 static gboolean gmessages_use_stderr = FALSE;
1181 * g_log_writer_default_set_use_stderr:
1182 * @use_stderr: If %TRUE, use `stderr` for log messages that would
1183 * normally have appeared on `stdout`
1185 * Configure whether the built-in log functions
1186 * (g_log_default_handler() for the old-style API, and both
1187 * g_log_writer_default() and g_log_writer_standard_streams() for the
1188 * structured API) will output all log messages to `stderr`.
1190 * By default, log messages of levels %G_LOG_LEVEL_INFO and
1191 * %G_LOG_LEVEL_DEBUG are sent to `stdout`, and other log messages are
1192 * sent to `stderr`. This is problematic for applications that intend
1193 * to reserve `stdout` for structured output such as JSON or XML.
1195 * This function sets global state. It is not thread-aware, and should be
1196 * called at the very start of a program, before creating any other threads
1197 * or creating objects that could create worker threads of their own.
1202 g_log_writer_default_set_use_stderr (gboolean use_stderr)
1204 g_return_if_fail (g_thread_n_created () == 0);
1205 gmessages_use_stderr = use_stderr;
1209 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1210 GLogLevelFlags log_level,
1213 /* we may not call _any_ GLib functions here */
1215 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1217 switch (log_level & G_LOG_LEVEL_MASK)
1219 case G_LOG_LEVEL_ERROR:
1220 strcat (level_prefix, "ERROR");
1222 case G_LOG_LEVEL_CRITICAL:
1223 strcat (level_prefix, "CRITICAL");
1225 case G_LOG_LEVEL_WARNING:
1226 strcat (level_prefix, "WARNING");
1228 case G_LOG_LEVEL_MESSAGE:
1229 strcat (level_prefix, "Message");
1231 case G_LOG_LEVEL_INFO:
1232 strcat (level_prefix, "INFO");
1234 case G_LOG_LEVEL_DEBUG:
1235 strcat (level_prefix, "DEBUG");
1240 strcat (level_prefix, "LOG-");
1241 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1244 strcat (level_prefix, "LOG");
1248 strcat (level_prefix, color_reset (use_color));
1250 if (log_level & G_LOG_FLAG_RECURSION)
1251 strcat (level_prefix, " (recursed)");
1252 if (log_level & ALERT_LEVELS)
1253 strcat (level_prefix, " **");
1256 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1257 win32_keep_fatal_message = TRUE;
1259 return log_level_to_file (log_level);
1264 GLogLevelFlags log_level;
1266 } GTestExpectedMessage;
1268 static GSList *expected_messages = NULL;
1272 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1273 * application domain
1274 * @log_level: the log level
1275 * @format: the message format. See the printf() documentation
1276 * @args: the parameters to insert into the format string
1278 * Logs an error or debugging message.
1280 * If the log level has been set as fatal, G_BREAKPOINT() is called
1281 * to terminate the program. See the documentation for G_BREAKPOINT() for
1282 * details of the debugging options this provides.
1284 * If g_log_default_handler() is used as the log handler function, a new-line
1285 * character will automatically be appended to @..., and need not be entered
1288 * If [structured logging is enabled][using-structured-logging] this will
1289 * output via the structured log writer function (see g_log_set_writer_func()).
1292 g_logv (const gchar *log_domain,
1293 GLogLevelFlags log_level,
1294 const gchar *format,
1297 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1298 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1299 char buffer[1025], *msg_alloc = NULL;
1303 log_level &= G_LOG_LEVEL_MASK;
1307 if (log_level & G_LOG_FLAG_RECURSION)
1309 /* we use a stack buffer of fixed size, since we're likely
1310 * in an out-of-memory situation
1312 gsize size G_GNUC_UNUSED;
1314 size = _g_vsnprintf (buffer, 1024, format, args);
1319 msg = format_string (format, args, &msg_alloc);
1322 if (expected_messages)
1324 GTestExpectedMessage *expected = expected_messages->data;
1326 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1327 ((log_level & expected->log_level) == expected->log_level) &&
1328 g_pattern_match_simple (expected->pattern, msg))
1330 expected_messages = g_slist_delete_link (expected_messages,
1332 g_free (expected->log_domain);
1333 g_free (expected->pattern);
1338 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1340 gchar level_prefix[STRING_BUFFER_SIZE];
1341 gchar *expected_message;
1343 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1344 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1345 expected->log_domain ? expected->log_domain : "**",
1346 level_prefix, expected->pattern);
1347 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1348 g_free (expected_message);
1350 log_level |= G_LOG_FLAG_FATAL;
1354 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1356 GLogLevelFlags test_level;
1358 test_level = 1L << i;
1359 if (log_level & test_level)
1363 GLogLevelFlags domain_fatal_mask;
1364 gpointer data = NULL;
1365 gboolean masquerade_fatal = FALSE;
1369 test_level |= G_LOG_FLAG_FATAL;
1371 test_level |= G_LOG_FLAG_RECURSION;
1373 /* check recursion and lookup handler */
1374 g_mutex_lock (&g_messages_lock);
1375 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1376 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1378 test_level |= G_LOG_FLAG_RECURSION;
1380 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1381 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1382 test_level |= G_LOG_FLAG_FATAL;
1383 if (test_level & G_LOG_FLAG_RECURSION)
1384 log_func = _g_log_fallback_handler;
1386 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1388 g_mutex_unlock (&g_messages_lock);
1390 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1392 log_func (log_domain, test_level, msg, data);
1394 if ((test_level & G_LOG_FLAG_FATAL)
1395 && !(test_level & G_LOG_LEVEL_ERROR))
1397 masquerade_fatal = fatal_log_func
1398 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1401 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1403 /* MessageBox is allowed on UWP apps only when building against
1404 * the debug CRT, which will set -D_DEBUG */
1405 #if defined(G_OS_WIN32) && (defined(_DEBUG) || !defined(G_WINAPI_ONLY_APP))
1406 if (win32_keep_fatal_message)
1410 wide_msg = g_utf8_to_utf16 (fatal_msg_buf, -1, NULL, NULL, NULL);
1412 MessageBoxW (NULL, wide_msg, NULL,
1413 MB_ICONERROR | MB_SETFOREGROUND);
1419 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1423 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1432 * @log_domain: (nullable): the log domain, usually %G_LOG_DOMAIN, or %NULL
1434 * @log_level: the log level, either from #GLogLevelFlags
1435 * or a user-defined level
1436 * @format: the message format. See the `printf()` documentation
1437 * @...: the parameters to insert into the format string
1439 * Logs an error or debugging message.
1441 * If the log level has been set as fatal, G_BREAKPOINT() is called
1442 * to terminate the program. See the documentation for G_BREAKPOINT() for
1443 * details of the debugging options this provides.
1445 * If g_log_default_handler() is used as the log handler function, a new-line
1446 * character will automatically be appended to @..., and need not be entered
1449 * If [structured logging is enabled][using-structured-logging] this will
1450 * output via the structured log writer function (see g_log_set_writer_func()).
1453 g_log (const gchar *log_domain,
1454 GLogLevelFlags log_level,
1455 const gchar *format,
1460 va_start (args, format);
1461 g_logv (log_domain, log_level, format, args);
1465 /* Return value must be 1 byte long (plus nul byte).
1466 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1468 static const gchar *
1469 log_level_to_priority (GLogLevelFlags log_level)
1471 if (log_level & G_LOG_LEVEL_ERROR)
1473 else if (log_level & G_LOG_LEVEL_CRITICAL)
1475 else if (log_level & G_LOG_LEVEL_WARNING)
1477 else if (log_level & G_LOG_LEVEL_MESSAGE)
1479 else if (log_level & G_LOG_LEVEL_INFO)
1481 else if (log_level & G_LOG_LEVEL_DEBUG)
1484 /* Default to LOG_NOTICE for custom log levels. */
1488 static inline FILE *
1489 log_level_to_file (GLogLevelFlags log_level)
1491 if (gmessages_use_stderr)
1494 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1495 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1501 static const gchar *
1502 log_level_to_color (GLogLevelFlags log_level,
1505 /* we may not call _any_ GLib functions here */
1510 if (log_level & G_LOG_LEVEL_ERROR)
1511 return "\033[1;31m"; /* red */
1512 else if (log_level & G_LOG_LEVEL_CRITICAL)
1513 return "\033[1;35m"; /* magenta */
1514 else if (log_level & G_LOG_LEVEL_WARNING)
1515 return "\033[1;33m"; /* yellow */
1516 else if (log_level & G_LOG_LEVEL_MESSAGE)
1517 return "\033[1;32m"; /* green */
1518 else if (log_level & G_LOG_LEVEL_INFO)
1519 return "\033[1;32m"; /* green */
1520 else if (log_level & G_LOG_LEVEL_DEBUG)
1521 return "\033[1;32m"; /* green */
1523 /* No color for custom log levels. */
1527 static const gchar *
1528 color_reset (gboolean use_color)
1530 /* we may not call _any_ GLib functions here */
1540 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1541 * so we need to check the name of the pipe if _isatty (fd) == 0
1545 win32_is_pipe_tty (int fd)
1547 gboolean result = FALSE;
1549 FILE_NAME_INFO *info = NULL;
1550 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1551 wchar_t *name = NULL;
1554 h_fd = (HANDLE) _get_osfhandle (fd);
1556 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1559 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1561 info = g_try_malloc (info_size);
1564 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1567 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1568 name = info->FileName;
1570 length = wcslen (L"\\cygwin-");
1571 if (wcsncmp (name, L"\\cygwin-", length))
1573 length = wcslen (L"\\msys-");
1574 if (wcsncmp (name, L"\\msys-", length))
1579 length = wcsspn (name, L"0123456789abcdefABCDEF");
1584 length = wcslen (L"-pty");
1585 if (wcsncmp (name, L"-pty", length))
1589 length = wcsspn (name, L"0123456789");
1594 length = wcslen (L"-to-master");
1595 if (wcsncmp (name, L"-to-master", length))
1597 length = wcslen (L"-from-master");
1598 if (wcsncmp (name, L"-from-master", length))
1612 #pragma GCC diagnostic push
1613 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1617 * @log_domain: log domain, usually %G_LOG_DOMAIN
1618 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1620 * @...: key-value pairs of structured data to add to the log entry, followed
1621 * by the key "MESSAGE", followed by a printf()-style message format,
1622 * followed by parameters to insert in the format string
1624 * Log a message with structured data.
1626 * The message will be passed through to the log writer set by the application
1627 * using g_log_set_writer_func(). If the message is fatal (i.e. its log level
1628 * is %G_LOG_LEVEL_ERROR), the program will be aborted by calling
1629 * G_BREAKPOINT() at the end of this function. If the log writer returns
1630 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1631 * See the documentation for #GLogWriterFunc for information on chaining
1634 * The structured data is provided as key–value pairs, where keys are UTF-8
1635 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1636 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1637 * structured data, use g_log_structured_array(). The keys for structured data
1638 * should follow the [systemd journal
1639 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1640 * specification. It is suggested that custom keys are namespaced according to
1641 * the code which sets them. For example, custom keys from GLib all have a
1644 * Note that keys that expect UTF-8 strings (specifically `"MESSAGE"` and
1645 * `"GLIB_DOMAIN"`) must be passed as NUL-terminated UTF-8 strings until GLib
1646 * version 2.74.1 because the default log handler did not consider the length of
1647 * the `GLogField`. Starting with GLib 2.74.1 this is fixed and
1648 * non-NUL-terminated UTF-8 strings can be passed with their correct length.
1650 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1651 * be converted into a
1652 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1653 * field. The format string will have its placeholders substituted for the provided
1654 * values and be converted into a
1655 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1658 * Other fields you may commonly want to pass into this function:
1660 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1661 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1662 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1663 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1664 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1666 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1667 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1668 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1673 * |[<!-- language="C" -->
1674 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1675 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1676 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1677 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1678 * some_pointer, some_integer);
1681 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1682 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1683 * If adding a `MESSAGE_ID`, consider shipping a [message
1684 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1687 * To pass a user data pointer to the log writer function which is specific to
1688 * this logging call, you must use g_log_structured_array() and pass the pointer
1689 * as a field with #GLogField.length set to zero, otherwise it will be
1690 * interpreted as a string.
1694 * |[<!-- language="C" -->
1695 * const GLogField fields[] = {
1696 * { "MESSAGE", "This is a debug message.", -1 },
1697 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1698 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1699 * { "MY_APPLICATION_STATE", state_object, 0 },
1701 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1704 * Note also that, even if no other structured fields are specified, there
1705 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1706 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1707 * field for which printf()-style formatting is supported.
1709 * The default writer function for `stdout` and `stderr` will automatically
1710 * append a new-line character after the message, so you should not add one
1711 * manually to the format string.
1716 g_log_structured (const gchar *log_domain,
1717 GLogLevelFlags log_level,
1721 gchar buffer[1025], *message_allocated = NULL;
1723 const gchar *message;
1726 GLogField stack_fields[16];
1727 GLogField *fields = stack_fields;
1728 GLogField *fields_allocated = NULL;
1729 GArray *array = NULL;
1731 va_start (args, log_level);
1733 /* MESSAGE and PRIORITY are a given */
1739 for (p = va_arg (args, gchar *), i = n_fields;
1740 strcmp (p, "MESSAGE") != 0;
1741 p = va_arg (args, gchar *), i++)
1744 const gchar *key = p;
1745 gconstpointer value = va_arg (args, gpointer);
1748 field.value = value;
1752 stack_fields[i] = field;
1755 /* Don't allow dynamic allocation, since we're likely
1756 * in an out-of-memory situation. For lack of a better solution,
1757 * just ignore further key-value pairs.
1759 if (log_level & G_LOG_FLAG_RECURSION)
1764 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1765 g_array_append_vals (array, stack_fields, 16);
1768 g_array_append_val (array, field);
1775 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1777 format = va_arg (args, gchar *);
1779 if (log_level & G_LOG_FLAG_RECURSION)
1781 /* we use a stack buffer of fixed size, since we're likely
1782 * in an out-of-memory situation
1784 gsize size G_GNUC_UNUSED;
1786 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1791 message = format_string (format, args, &message_allocated);
1794 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1795 fields[0].key = "MESSAGE";
1796 fields[0].value = message;
1797 fields[0].length = -1;
1799 fields[1].key = "PRIORITY";
1800 fields[1].value = log_level_to_priority (log_level);
1801 fields[1].length = -1;
1805 fields[2].key = "GLIB_DOMAIN";
1806 fields[2].value = log_domain;
1807 fields[2].length = -1;
1811 g_log_structured_array (log_level, fields, n_fields);
1813 g_free (fields_allocated);
1814 g_free (message_allocated);
1821 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1822 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1824 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1825 * containing the key-value pairs of message data.
1827 * Log a message with structured data, accepting the data within a #GVariant. This
1828 * version is especially useful for use in other languages, via introspection.
1830 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1831 * contain the text shown to the user.
1833 * The values in the @fields dictionary are likely to be of type String
1834 * (%G_VARIANT_TYPE_STRING). Array of bytes (%G_VARIANT_TYPE_BYTESTRING) is also
1835 * supported. In this case the message is handled as binary and will be forwarded
1836 * to the log writer as such. The size of the array should not be higher than
1837 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1838 * g_variant_print() will be used to convert the value into a string.
1840 * For more details on its usage and about the parameters, see g_log_structured().
1846 g_log_variant (const gchar *log_domain,
1847 GLogLevelFlags log_level,
1853 GArray *fields_array;
1855 GSList *values_list, *print_list;
1857 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1859 values_list = print_list = NULL;
1860 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1862 field.key = "PRIORITY";
1863 field.value = log_level_to_priority (log_level);
1865 g_array_append_val (fields_array, field);
1869 field.key = "GLIB_DOMAIN";
1870 field.value = log_domain;
1872 g_array_append_val (fields_array, field);
1875 g_variant_iter_init (&iter, fields);
1876 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1878 gboolean defer_unref = TRUE;
1883 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1885 field.value = g_variant_get_string (value, NULL);
1887 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1890 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1891 if (G_LIKELY (s <= G_MAXSSIZE))
1898 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1899 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1901 field.length = G_MAXSSIZE;
1906 char *s = g_variant_print (value, FALSE);
1908 print_list = g_slist_prepend (print_list, s);
1909 defer_unref = FALSE;
1912 g_array_append_val (fields_array, field);
1914 if (G_LIKELY (defer_unref))
1915 values_list = g_slist_prepend (values_list, value);
1917 g_variant_unref (value);
1921 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1923 g_array_free (fields_array, TRUE);
1924 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1925 g_slist_free_full (print_list, g_free);
1929 #pragma GCC diagnostic pop
1931 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1932 const GLogField *fields,
1934 gpointer user_data);
1937 * g_log_structured_array:
1938 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1940 * @fields: (array length=n_fields): key–value pairs of structured data to add
1941 * to the log message
1942 * @n_fields: number of elements in the @fields array
1944 * Log a message with structured data. The message will be passed through to the
1945 * log writer set by the application using g_log_set_writer_func(). If the
1946 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1947 * be aborted at the end of this function.
1949 * See g_log_structured() for more documentation.
1951 * This assumes that @log_level is already present in @fields (typically as the
1952 * `PRIORITY` field).
1957 g_log_structured_array (GLogLevelFlags log_level,
1958 const GLogField *fields,
1961 GLogWriterFunc writer_func;
1962 gpointer writer_user_data;
1969 /* Check for recursion and look up the writer function. */
1970 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1971 recursion = (depth > 0);
1973 g_mutex_lock (&g_messages_lock);
1975 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1976 writer_user_data = log_writer_user_data;
1978 g_mutex_unlock (&g_messages_lock);
1980 /* Write the log entry. */
1981 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1983 g_assert (writer_func != NULL);
1984 writer_func (log_level, fields, n_fields, writer_user_data);
1986 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1988 /* Abort if the message was fatal. */
1989 if (log_level & G_LOG_FATAL_MASK)
1990 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1993 /* Semi-private helper function to implement the g_message() (etc.) macros
1994 * with support for G_GNUC_PRINTF so that @message_format can be checked
1997 g_log_structured_standard (const gchar *log_domain,
1998 GLogLevelFlags log_level,
2002 const gchar *message_format,
2005 GLogField fields[] =
2007 { "PRIORITY", log_level_to_priority (log_level), -1 },
2008 { "CODE_FILE", file, -1 },
2009 { "CODE_LINE", line, -1 },
2010 { "CODE_FUNC", func, -1 },
2011 /* Filled in later: */
2012 { "MESSAGE", NULL, -1 },
2013 /* If @log_domain is %NULL, we will not pass this field: */
2014 { "GLIB_DOMAIN", log_domain, -1 },
2017 gchar *message_allocated = NULL;
2021 va_start (args, message_format);
2023 if (log_level & G_LOG_FLAG_RECURSION)
2025 /* we use a stack buffer of fixed size, since we're likely
2026 * in an out-of-memory situation
2028 gsize size G_GNUC_UNUSED;
2030 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
2031 fields[4].value = buffer;
2035 fields[4].value = format_string (message_format, args, &message_allocated);
2040 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
2041 g_log_structured_array (log_level, fields, n_fields);
2043 g_free (message_allocated);
2047 * g_log_set_writer_func:
2048 * @func: log writer function, which must not be %NULL
2049 * @user_data: (closure func): user data to pass to @func
2050 * @user_data_free: (destroy func): function to free @user_data once it’s
2051 * finished with, if non-%NULL
2053 * Set a writer function which will be called to format and write out each log
2054 * message. Each program should set a writer function, or the default writer
2055 * (g_log_writer_default()) will be used.
2057 * Libraries **must not** call this function — only programs are allowed to
2058 * install a writer function, as there must be a single, central point where
2059 * log messages are formatted and outputted.
2061 * There can only be one writer function. It is an error to set more than one.
2066 g_log_set_writer_func (GLogWriterFunc func,
2068 GDestroyNotify user_data_free)
2070 g_return_if_fail (func != NULL);
2072 g_mutex_lock (&g_messages_lock);
2074 if (log_writer_func != g_log_writer_default)
2076 g_mutex_unlock (&g_messages_lock);
2077 g_error ("g_log_set_writer_func() called multiple times");
2081 log_writer_func = func;
2082 log_writer_user_data = user_data;
2083 log_writer_user_data_free = user_data_free;
2085 g_mutex_unlock (&g_messages_lock);
2089 * g_log_writer_supports_color:
2090 * @output_fd: output file descriptor to check
2092 * Check whether the given @output_fd file descriptor supports ANSI color
2093 * escape sequences. If so, they can safely be used when formatting log
2096 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2100 g_log_writer_supports_color (gint output_fd)
2103 gboolean result = FALSE;
2104 GWin32InvalidParameterHandler handler;
2107 g_return_val_if_fail (output_fd >= 0, FALSE);
2109 /* FIXME: This check could easily be expanded in future to be more robust
2110 * against different types of terminal, which still vary in their color
2111 * support. cmd.exe on Windows, for example, supports ANSI colors only
2112 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2113 * The Windows 10 color support is supported on:
2114 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2115 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2117 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2118 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2120 * On UNIX systems, we probably want to use the functions from terminfo to
2121 * work out whether colors are supported.
2124 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2125 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2126 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2127 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2131 g_win32_push_empty_invalid_parameter_handler (&handler);
2133 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2138 if (_isatty (output_fd))
2140 h_output = (HANDLE) _get_osfhandle (output_fd);
2142 if (!GetConsoleMode (h_output, &dw_mode))
2143 goto reset_invalid_param_handler;
2145 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2148 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2149 goto reset_invalid_param_handler;
2155 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2156 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2157 * (bug 775468), on standard Windows consoles, such as cmd.exe
2160 result = win32_is_pipe_tty (output_fd);
2162 reset_invalid_param_handler:
2163 g_win32_pop_invalid_parameter_handler (&handler);
2167 return isatty (output_fd);
2171 #if defined(__linux__) && !defined(__BIONIC__)
2172 static int journal_fd = -1;
2174 #ifndef SOCK_CLOEXEC
2175 #define SOCK_CLOEXEC 0
2177 #define HAVE_SOCK_CLOEXEC 1
2183 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2186 #ifndef HAVE_SOCK_CLOEXEC
2187 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2197 * g_log_writer_is_journald:
2198 * @output_fd: output file descriptor to check
2200 * Check whether the given @output_fd file descriptor is a connection to the
2201 * systemd journal, or something else (like a log file or `stdout` or
2204 * Invalid file descriptors are accepted and return %FALSE, which allows for
2205 * the following construct without needing any additional error handling:
2206 * |[<!-- language="C" -->
2207 * is_journald = g_log_writer_is_journald (fileno (stderr));
2210 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2214 g_log_writer_is_journald (gint output_fd)
2216 #if defined(__linux__) && !defined(__BIONIC__)
2217 return _g_fd_is_journal (output_fd);
2223 static void escape_string (GString *string);
2226 * g_log_writer_format_fields:
2227 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2229 * @fields: (array length=n_fields): key–value pairs of structured data forming
2231 * @n_fields: number of elements in the @fields array
2232 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2233 * message, %FALSE to not
2235 * Format a structured log message as a string suitable for outputting to the
2236 * terminal (or elsewhere). This will include the values of all fields it knows
2237 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2238 * documentation for g_log_structured()). It does not include values from
2241 * The returned string does **not** have a trailing new-line character. It is
2242 * encoded in the character set of the current locale, which is not necessarily
2245 * Returns: (transfer full): string containing the formatted log message, in
2246 * the character set of the current locale
2250 g_log_writer_format_fields (GLogLevelFlags log_level,
2251 const GLogField *fields,
2256 const gchar *message = NULL;
2257 const gchar *log_domain = NULL;
2258 gssize message_length = -1;
2259 gssize log_domain_length = -1;
2260 gchar level_prefix[STRING_BUFFER_SIZE];
2265 gchar time_buf[128];
2267 /* Extract some common fields. */
2268 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2270 const GLogField *field = &fields[i];
2272 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2274 message = field->value;
2275 message_length = field->length;
2277 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2279 log_domain = field->value;
2280 log_domain_length = field->length;
2284 /* Format things. */
2285 mklevel_prefix (level_prefix, log_level, use_color);
2287 gstring = g_string_new (NULL);
2288 if (log_level & ALERT_LEVELS)
2289 g_string_append (gstring, "\n");
2291 g_string_append (gstring, "** ");
2293 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2294 (log_level & G_LOG_LEVEL_MASK))
2296 const gchar *prg_name = g_get_prgname ();
2297 gulong pid = getpid ();
2299 if (prg_name == NULL)
2300 g_string_append_printf (gstring, "(process:%lu): ", pid);
2302 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2305 if (log_domain != NULL)
2307 g_string_append_len (gstring, log_domain, log_domain_length);
2308 g_string_append_c (gstring, '-');
2310 g_string_append (gstring, level_prefix);
2312 g_string_append (gstring, ": ");
2315 now = g_get_real_time ();
2316 now_secs = (time_t) (now / 1000000);
2317 if (_g_localtime (now_secs, &now_tm))
2318 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", &now_tm);
2320 strcpy (time_buf, "(error)");
2322 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2323 use_color ? "\033[34m" : "",
2324 time_buf, (gint) ((now / 1000) % 1000),
2325 color_reset (use_color));
2327 if (message == NULL)
2329 g_string_append (gstring, "(NULL) message");
2334 const gchar *charset;
2336 msg = g_string_new_len (message, message_length);
2337 escape_string (msg);
2339 if (g_get_console_charset (&charset))
2341 /* charset is UTF-8 already */
2342 g_string_append (gstring, msg->str);
2346 gchar *lstring = strdup_convert (msg->str, charset);
2347 g_string_append (gstring, lstring);
2351 g_string_free (msg, TRUE);
2354 return g_string_free (gstring, FALSE);
2357 /* Enable support for the journal if we're on a recent enough Linux */
2358 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2359 #define ENABLE_JOURNAL_SENDV
2362 #ifdef ENABLE_JOURNAL_SENDV
2364 journal_sendv (struct iovec *iov,
2369 struct sockaddr_un sa;
2371 struct cmsghdr cmsghdr;
2372 guint8 buf[CMSG_SPACE(sizeof(int))];
2374 struct cmsghdr *cmsg;
2375 char path[] = "/dev/shm/journal.XXXXXX";
2383 memset (&sa, 0, sizeof (sa));
2384 sa.sun_family = AF_UNIX;
2385 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2388 memset (&mh, 0, sizeof (mh));
2390 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2392 mh.msg_iovlen = iovlen;
2395 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2401 if (errno != EMSGSIZE && errno != ENOBUFS)
2404 /* Message was too large, so dump to temporary file
2405 * and pass an FD to the journal
2407 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2410 if (unlink (path) < 0)
2416 if (writev (buf_fd, iov, iovlen) < 0)
2425 memset (&control, 0, sizeof (control));
2426 mh.msg_control = &control;
2427 mh.msg_controllen = sizeof (control);
2429 cmsg = CMSG_FIRSTHDR (&mh);
2430 cmsg->cmsg_level = SOL_SOCKET;
2431 cmsg->cmsg_type = SCM_RIGHTS;
2432 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2433 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2435 mh.msg_controllen = cmsg->cmsg_len;
2438 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2446 #endif /* ENABLE_JOURNAL_SENDV */
2449 * g_log_writer_journald:
2450 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2452 * @fields: (array length=n_fields): key–value pairs of structured data forming
2454 * @n_fields: number of elements in the @fields array
2455 * @user_data: user data passed to g_log_set_writer_func()
2457 * Format a structured log message and send it to the systemd journal as a set
2458 * of key–value pairs. All fields are sent to the journal, but if a field has
2459 * length zero (indicating program-specific data) then only its key will be
2462 * This is suitable for use as a #GLogWriterFunc.
2464 * If GLib has been compiled without systemd support, this function is still
2465 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2467 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2471 g_log_writer_journald (GLogLevelFlags log_level,
2472 const GLogField *fields,
2476 #ifdef ENABLE_JOURNAL_SENDV
2477 const char equals = '=';
2478 const char newline = '\n';
2480 struct iovec *iov, *v;
2484 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2485 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2487 /* According to systemd.journal-fields(7), the journal allows fields in any
2488 * format (including arbitrary binary), but expects text fields to be UTF-8.
2489 * This is great, because we require input strings to be in UTF-8, so no
2490 * conversion is necessary and we don’t need to care about the current
2491 * locale’s character set.
2494 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2495 buf = g_alloca (32 * n_fields);
2499 for (i = 0; i < n_fields; i++)
2504 if (fields[i].length < 0)
2506 length = strlen (fields[i].value);
2507 binary = strchr (fields[i].value, '\n') != NULL;
2511 length = fields[i].length;
2519 v[0].iov_base = (gpointer)fields[i].key;
2520 v[0].iov_len = strlen (fields[i].key);
2522 v[1].iov_base = (gpointer)&newline;
2525 nstr = GUINT64_TO_LE(length);
2526 memcpy (&buf[k], &nstr, sizeof (nstr));
2528 v[2].iov_base = &buf[k];
2529 v[2].iov_len = sizeof (nstr);
2535 v[0].iov_base = (gpointer)fields[i].key;
2536 v[0].iov_len = strlen (fields[i].key);
2538 v[1].iov_base = (gpointer)=
2543 v[0].iov_base = (gpointer)fields[i].value;
2544 v[0].iov_len = length;
2546 v[1].iov_base = (gpointer)&newline;
2551 retval = journal_sendv (iov, v - iov);
2553 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2555 return G_LOG_WRITER_UNHANDLED;
2556 #endif /* ENABLE_JOURNAL_SENDV */
2560 * g_log_writer_standard_streams:
2561 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2563 * @fields: (array length=n_fields): key–value pairs of structured data forming
2565 * @n_fields: number of elements in the @fields array
2566 * @user_data: user data passed to g_log_set_writer_func()
2568 * Format a structured log message and print it to either `stdout` or `stderr`,
2569 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2570 * are sent to `stdout`, or to `stderr` if requested by
2571 * g_log_writer_default_set_use_stderr();
2572 * all other log levels are sent to `stderr`. Only fields
2573 * which are understood by this function are included in the formatted string
2576 * If the output stream supports ANSI color escape sequences, they will be used
2579 * A trailing new-line character is added to the log message when it is printed.
2581 * This is suitable for use as a #GLogWriterFunc.
2583 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2587 g_log_writer_standard_streams (GLogLevelFlags log_level,
2588 const GLogField *fields,
2593 gchar *out = NULL; /* in the current locale’s character set */
2595 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2596 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2598 stream = log_level_to_file (log_level);
2599 if (!stream || fileno (stream) < 0)
2600 return G_LOG_WRITER_UNHANDLED;
2602 out = g_log_writer_format_fields (log_level, fields, n_fields,
2603 g_log_writer_supports_color (fileno (stream)));
2604 _g_fprintf (stream, "%s\n", out);
2608 return G_LOG_WRITER_HANDLED;
2611 /* The old g_log() API is implemented in terms of the new structured log API.
2612 * However, some of the checks do not line up between the two APIs: the
2613 * structured API only handles fatalness of messages for log levels; the old API
2614 * handles it per-domain as well. Consequently, we need to disable fatalness
2615 * handling in the structured log API when called from the old g_log() API.
2617 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2618 * the first field to g_log_structured_array(), if that is the case.
2621 log_is_old_api (const GLogField *fields,
2624 return (n_fields >= 1 &&
2625 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2626 g_strcmp0 (fields[0].value, "1") == 0);
2630 * Internal version of g_log_writer_default_would_drop(), which can
2631 * read from either a log_domain or an array of fields. This avoids
2632 * having to iterate through the fields if the @log_level is sufficient
2633 * to make the decision.
2636 should_drop_message (GLogLevelFlags log_level,
2637 const char *log_domain,
2638 const GLogField *fields,
2641 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2642 if (!(log_level & DEFAULT_LEVELS) &&
2643 !(log_level >> G_LOG_LEVEL_USER_SHIFT) &&
2644 !g_log_get_debug_enabled ())
2646 const gchar *domains;
2649 domains = g_getenv ("G_MESSAGES_DEBUG");
2651 if ((log_level & INFO_LEVELS) == 0 ||
2655 if (log_domain == NULL)
2657 for (i = 0; i < n_fields; i++)
2659 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2661 log_domain = fields[i].value;
2667 if (strcmp (domains, "all") != 0 &&
2668 (log_domain == NULL || !strstr (domains, log_domain)))
2676 * g_log_writer_default_would_drop:
2677 * @log_domain: (nullable): log domain
2678 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2681 * Check whether g_log_writer_default() and g_log_default_handler() would
2682 * ignore a message with the given domain and level.
2684 * As with g_log_default_handler(), this function drops debug and informational
2685 * messages unless their log domain (or `all`) is listed in the space-separated
2686 * `G_MESSAGES_DEBUG` environment variable.
2688 * This can be used when implementing log writers with the same filtering
2689 * behaviour as the default, but a different destination or output format:
2691 * |[<!-- language="C" -->
2692 * if (g_log_writer_default_would_drop (log_level, log_domain))
2693 * return G_LOG_WRITER_HANDLED;
2696 * or to skip an expensive computation if it is only needed for a debugging
2697 * message, and `G_MESSAGES_DEBUG` is not set:
2699 * |[<!-- language="C" -->
2700 * if (!g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
2702 * gchar *result = expensive_computation (my_object);
2704 * g_debug ("my_object result: %s", result);
2709 * Returns: %TRUE if the log message would be dropped by GLib's
2710 * default log handlers
2714 g_log_writer_default_would_drop (GLogLevelFlags log_level,
2715 const char *log_domain)
2717 return should_drop_message (log_level, log_domain, NULL, 0);
2721 * g_log_writer_default:
2722 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2724 * @fields: (array length=n_fields): key–value pairs of structured data forming
2726 * @n_fields: number of elements in the @fields array
2727 * @user_data: user data passed to g_log_set_writer_func()
2729 * Format a structured log message and output it to the default log destination
2730 * for the platform. On Linux, this is typically the systemd journal, falling
2731 * back to `stdout` or `stderr` if running from the terminal or if output is
2732 * being redirected to a file.
2734 * Support for other platform-specific logging mechanisms may be added in
2735 * future. Distributors of GLib may modify this function to impose their own
2736 * (documented) platform-specific log writing policies.
2738 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2739 * if no other is set using g_log_set_writer_func().
2741 * As with g_log_default_handler(), this function drops debug and informational
2742 * messages unless their log domain (or `all`) is listed in the space-separated
2743 * `G_MESSAGES_DEBUG` environment variable.
2745 * g_log_writer_default() uses the mask set by g_log_set_always_fatal() to
2746 * determine which messages are fatal. When using a custom writer func instead it is
2747 * up to the writer function to determine which log messages are fatal.
2749 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2753 g_log_writer_default (GLogLevelFlags log_level,
2754 const GLogField *fields,
2758 static gsize initialized = 0;
2759 static gboolean stderr_is_journal = FALSE;
2761 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2762 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2764 if (should_drop_message (log_level, NULL, fields, n_fields))
2765 return G_LOG_WRITER_HANDLED;
2767 /* Mark messages as fatal if they have a level set in
2768 * g_log_set_always_fatal().
2770 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2771 log_level |= G_LOG_FLAG_FATAL;
2773 /* Try logging to the systemd journal as first choice. */
2774 if (g_once_init_enter (&initialized))
2776 stderr_is_journal = g_log_writer_is_journald (fileno (stderr));
2777 g_once_init_leave (&initialized, TRUE);
2780 if (stderr_is_journal &&
2781 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2782 G_LOG_WRITER_HANDLED)
2785 /* FIXME: Add support for the Windows log. */
2787 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2788 G_LOG_WRITER_HANDLED)
2791 return G_LOG_WRITER_UNHANDLED;
2794 /* Abort if the message was fatal. */
2795 if (log_level & G_LOG_FLAG_FATAL)
2797 /* MessageBox is allowed on UWP apps only when building against
2798 * the debug CRT, which will set -D_DEBUG */
2799 #if defined(G_OS_WIN32) && (defined(_DEBUG) || !defined(G_WINAPI_ONLY_APP))
2800 if (!g_test_initialized ())
2804 wide_msg = g_utf8_to_utf16 (fatal_msg_buf, -1, NULL, NULL, NULL);
2806 MessageBoxW (NULL, wide_msg, NULL, MB_ICONERROR | MB_SETFOREGROUND);
2810 #endif /* !G_OS_WIN32 */
2812 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2815 return G_LOG_WRITER_HANDLED;
2818 static GLogWriterOutput
2819 _g_log_writer_fallback (GLogLevelFlags log_level,
2820 const GLogField *fields,
2827 /* we cannot call _any_ GLib functions in this fallback handler,
2828 * which is why we skip UTF-8 conversion, etc.
2829 * since we either recursed or ran out of memory, we're in a pretty
2830 * pathologic situation anyways, what we can do is giving the
2831 * the process ID unconditionally however.
2834 stream = log_level_to_file (log_level);
2836 for (i = 0; i < n_fields; i++)
2838 const GLogField *field = &fields[i];
2840 /* Only print fields we definitely recognise, otherwise we could end up
2841 * printing a random non-string pointer provided by the user to be
2842 * interpreted by their writer function.
2844 if (strcmp (field->key, "MESSAGE") != 0 &&
2845 strcmp (field->key, "MESSAGE_ID") != 0 &&
2846 strcmp (field->key, "PRIORITY") != 0 &&
2847 strcmp (field->key, "CODE_FILE") != 0 &&
2848 strcmp (field->key, "CODE_LINE") != 0 &&
2849 strcmp (field->key, "CODE_FUNC") != 0 &&
2850 strcmp (field->key, "ERRNO") != 0 &&
2851 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2852 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2853 strcmp (field->key, "SYSLOG_PID") != 0 &&
2854 strcmp (field->key, "GLIB_DOMAIN") != 0)
2857 write_string (stream, field->key);
2858 write_string (stream, "=");
2859 write_string_sized (stream, field->value, field->length);
2864 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2866 format_unsigned (pid_string, getpid (), 10);
2867 write_string (stream, "_PID=");
2868 write_string (stream, pid_string);
2872 return G_LOG_WRITER_HANDLED;
2876 * g_log_get_debug_enabled:
2878 * Return whether debug output from the GLib logging system is enabled.
2880 * Note that this should not be used to conditionalise calls to g_debug() or
2881 * other logging functions; it should only be used from %GLogWriterFunc
2884 * Note also that the value of this does not depend on `G_MESSAGES_DEBUG`; see
2885 * the docs for g_log_set_debug_enabled().
2887 * Returns: %TRUE if debug output is enabled, %FALSE otherwise
2892 g_log_get_debug_enabled (void)
2894 return g_atomic_int_get (&g_log_debug_enabled);
2898 * g_log_set_debug_enabled:
2899 * @enabled: %TRUE to enable debug output, %FALSE otherwise
2901 * Enable or disable debug output from the GLib logging system for all domains.
2902 * This value interacts disjunctively with `G_MESSAGES_DEBUG` — if either of
2903 * them would allow a debug message to be outputted, it will be.
2905 * Note that this should not be used from within library code to enable debug
2906 * output — it is intended for external use.
2911 g_log_set_debug_enabled (gboolean enabled)
2913 g_atomic_int_set (&g_log_debug_enabled, enabled);
2917 * g_return_if_fail_warning: (skip)
2918 * @log_domain: (nullable): log domain
2919 * @pretty_function: function containing the assertion
2920 * @expression: (nullable): expression which failed
2922 * Internal function used to print messages from the public g_return_if_fail()
2923 * and g_return_val_if_fail() macros.
2926 g_return_if_fail_warning (const char *log_domain,
2927 const char *pretty_function,
2928 const char *expression)
2931 G_LOG_LEVEL_CRITICAL,
2932 "%s: assertion '%s' failed",
2938 * g_warn_message: (skip)
2939 * @domain: (nullable): log domain
2940 * @file: file containing the warning
2941 * @line: line number of the warning
2942 * @func: function containing the warning
2943 * @warnexpr: (nullable): expression which failed
2945 * Internal function used to print messages from the public g_warn_if_reached()
2946 * and g_warn_if_fail() macros.
2949 g_warn_message (const char *domain,
2953 const char *warnexpr)
2956 g_snprintf (lstr, 32, "%d", line);
2958 s = g_strconcat ("(", file, ":", lstr, "):",
2959 func, func[0] ? ":" : "",
2960 " runtime check failed: (", warnexpr, ")", NULL);
2962 s = g_strconcat ("(", file, ":", lstr, "):",
2963 func, func[0] ? ":" : "",
2964 " ", "code should not be reached", NULL);
2965 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2970 g_assert_warning (const char *log_domain,
2973 const char *pretty_function,
2974 const char *expression)
2979 "file %s: line %d (%s): assertion failed: (%s)",
2987 "file %s: line %d (%s): should not be reached",
2991 _g_log_abort (FALSE);
2996 * g_test_expect_message:
2997 * @log_domain: (nullable): the log domain of the message
2998 * @log_level: the log level of the message
2999 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
3001 * Indicates that a message with the given @log_domain and @log_level,
3002 * with text matching @pattern, is expected to be logged. When this
3003 * message is logged, it will not be printed, and the test case will
3006 * This API may only be used with the old logging API (g_log() without
3007 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
3008 * API. See [Testing for Messages][testing-for-messages].
3010 * Use g_test_assert_expected_messages() to assert that all
3011 * previously-expected messages have been seen and suppressed.
3013 * You can call this multiple times in a row, if multiple messages are
3014 * expected as a result of a single call. (The messages must appear in
3015 * the same order as the calls to g_test_expect_message().)
3019 * |[<!-- language="C" -->
3020 * // g_main_context_push_thread_default() should fail if the
3021 * // context is already owned by another thread.
3022 * g_test_expect_message (G_LOG_DOMAIN,
3023 * G_LOG_LEVEL_CRITICAL,
3024 * "assertion*acquired_context*failed");
3025 * g_main_context_push_thread_default (bad_context);
3026 * g_test_assert_expected_messages ();
3029 * Note that you cannot use this to test g_error() messages, since
3030 * g_error() intentionally never returns even if the program doesn't
3031 * abort; use g_test_trap_subprocess() in this case.
3033 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
3034 * expected via g_test_expect_message() then they will be ignored.
3039 g_test_expect_message (const gchar *log_domain,
3040 GLogLevelFlags log_level,
3041 const gchar *pattern)
3043 GTestExpectedMessage *expected;
3045 g_return_if_fail (log_level != 0);
3046 g_return_if_fail (pattern != NULL);
3047 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
3049 expected = g_new (GTestExpectedMessage, 1);
3050 expected->log_domain = g_strdup (log_domain);
3051 expected->log_level = log_level;
3052 expected->pattern = g_strdup (pattern);
3054 expected_messages = g_slist_append (expected_messages, expected);
3058 g_test_assert_expected_messages_internal (const char *domain,
3063 if (expected_messages)
3065 GTestExpectedMessage *expected;
3066 gchar level_prefix[STRING_BUFFER_SIZE];
3069 expected = expected_messages->data;
3071 mklevel_prefix (level_prefix, expected->log_level, FALSE);
3072 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
3073 expected->log_domain ? expected->log_domain : "**",
3074 level_prefix, expected->pattern);
3075 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
3081 * g_test_assert_expected_messages:
3083 * Asserts that all messages previously indicated via
3084 * g_test_expect_message() have been seen and suppressed.
3086 * This API may only be used with the old logging API (g_log() without
3087 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
3088 * API. See [Testing for Messages][testing-for-messages].
3090 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
3091 * expected via g_test_expect_message() then they will be ignored.
3097 _g_log_fallback_handler (const gchar *log_domain,
3098 GLogLevelFlags log_level,
3099 const gchar *message,
3100 gpointer unused_data)
3102 gchar level_prefix[STRING_BUFFER_SIZE];
3104 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
3108 /* we cannot call _any_ GLib functions in this fallback handler,
3109 * which is why we skip UTF-8 conversion, etc.
3110 * since we either recursed or ran out of memory, we're in a pretty
3111 * pathologic situation anyways, what we can do is giving the
3112 * the process ID unconditionally however.
3115 stream = mklevel_prefix (level_prefix, log_level, FALSE);
3117 message = "(NULL) message";
3120 format_unsigned (pid_string, getpid (), 10);
3124 write_string (stream, "\n");
3126 write_string (stream, "\n** ");
3129 write_string (stream, "(process:");
3130 write_string (stream, pid_string);
3131 write_string (stream, "): ");
3136 write_string (stream, log_domain);
3137 write_string (stream, "-");
3139 write_string (stream, level_prefix);
3140 write_string (stream, ": ");
3141 write_string (stream, message);
3142 write_string (stream, "\n");
3146 escape_string (GString *string)
3148 const char *p = string->str;
3151 while (p < string->str + string->len)
3155 wc = g_utf8_get_char_validated (p, -1);
3156 if (wc == (gunichar)-1 || wc == (gunichar)-2)
3161 pos = p - string->str;
3163 /* Emit invalid UTF-8 as hex escapes
3165 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
3166 g_string_erase (string, pos, 1);
3167 g_string_insert (string, pos, tmp);
3169 p = string->str + (pos + 4); /* Skip over escape sequence */
3176 safe = *(p + 1) == '\n';
3180 safe = CHAR_IS_SAFE (wc);
3188 pos = p - string->str;
3190 /* Largest char we escape is 0x0a, so we don't have to worry
3191 * about 8-digit \Uxxxxyyyy
3193 tmp = g_strdup_printf ("\\u%04x", wc);
3194 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3195 g_string_insert (string, pos, tmp);
3198 p = string->str + (pos + 6); /* Skip over escape sequence */
3201 p = g_utf8_next_char (p);
3206 * g_log_default_handler:
3207 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3208 * default "" application domain
3209 * @log_level: the level of the message
3210 * @message: (nullable): the message
3211 * @unused_data: (nullable): data passed from g_log() which is unused
3213 * The default log handler set up by GLib; g_log_set_default_handler()
3214 * allows to install an alternate default log handler.
3215 * This is used if no log handler has been set for the particular log
3216 * domain and log level combination. It outputs the message to stderr
3217 * or stdout and if the log level is fatal it calls G_BREAKPOINT(). It automatically
3218 * prints a new-line character after the message, so one does not need to be
3219 * manually included in @message.
3221 * The behavior of this log handler can be influenced by a number of
3222 * environment variables:
3224 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3225 * messages should be prefixed by the program name and PID of the
3228 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3229 * which debug and informational messages are printed. By default
3230 * these messages are not printed.
3232 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3233 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3234 * the rest, unless stderr was requested by
3235 * g_log_writer_default_set_use_stderr().
3237 * This has no effect if structured logging is enabled; see
3238 * [Using Structured Logging][using-structured-logging].
3241 g_log_default_handler (const gchar *log_domain,
3242 GLogLevelFlags log_level,
3243 const gchar *message,
3244 gpointer unused_data)
3246 GLogField fields[4];
3249 /* we can be called externally with recursion for whatever reason */
3250 if (log_level & G_LOG_FLAG_RECURSION)
3252 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3256 fields[0].key = "GLIB_OLD_LOG_API";
3257 fields[0].value = "1";
3258 fields[0].length = -1;
3261 fields[1].key = "MESSAGE";
3262 fields[1].value = message;
3263 fields[1].length = -1;
3266 fields[2].key = "PRIORITY";
3267 fields[2].value = log_level_to_priority (log_level);
3268 fields[2].length = -1;
3273 fields[3].key = "GLIB_DOMAIN";
3274 fields[3].value = log_domain;
3275 fields[3].length = -1;
3279 /* Print out via the structured log API, but drop any fatal flags since we
3280 * have already handled them. The fatal handling in the structured logging
3281 * API is more coarse-grained than in the old g_log() API, so we don't want
3284 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3288 * g_set_print_handler:
3289 * @func: (nullable): the new print handler or %NULL to
3290 * reset to the default
3292 * Sets the print handler to @func, or resets it to the
3293 * default GLib handler if %NULL.
3295 * Any messages passed to g_print() will be output via
3296 * the new handler. The default handler outputs
3297 * the encoded message to stdout. By providing your own handler
3298 * you can redirect the output, to a GTK widget or a
3299 * log file for example.
3301 * Since 2.76 this functions always returns a valid
3302 * #GPrintFunc, and never returns %NULL. If no custom
3303 * print handler was set, it will return the GLib
3304 * default print handler and that can be re-used to
3305 * decorate its output and/or to write to stderr
3306 * in all platforms. Before GLib 2.76, this was %NULL.
3308 * Returns: (not nullable): the old print handler
3311 g_set_print_handler (GPrintFunc func)
3313 return g_atomic_pointer_exchange (&glib_print_func,
3314 func ? func : g_default_print_func);
3318 print_string (FILE *stream,
3319 const gchar *string)
3321 const gchar *charset;
3324 if (g_get_console_charset (&charset))
3326 /* charset is UTF-8 already */
3327 ret = fputs (string, stream);
3331 gchar *converted_string = strdup_convert (string, charset);
3333 ret = fputs (converted_string, stream);
3334 g_free (converted_string);
3337 /* In case of failure we can just return early, but there's nothing else
3338 * we can do at this level
3346 G_ALWAYS_INLINE static inline const char *
3347 format_string (const char *format,
3349 char **out_allocated_string)
3351 #ifdef G_ENABLE_DEBUG
3352 g_assert (out_allocated_string != NULL);
3355 /* If there is no formatting to be done, avoid an allocation */
3356 if (strchr (format, '%') == NULL)
3358 *out_allocated_string = NULL;
3363 *out_allocated_string = g_strdup_vprintf (format, args);
3364 return *out_allocated_string;
3369 g_default_print_func (const gchar *string)
3371 print_string (stdout, string);
3375 g_default_printerr_func (const gchar *string)
3377 print_string (stderr, string);
3382 * @format: the message format. See the printf() documentation
3383 * @...: the parameters to insert into the format string
3385 * Outputs a formatted message via the print handler.
3386 * The default print handler outputs the encoded message to stdout, without
3387 * appending a trailing new-line character. Typically, @format should end with
3388 * its own new-line character.
3390 * g_print() should not be used from within libraries for debugging
3391 * messages, since it may be redirected by applications to special
3392 * purpose message windows or even files. Instead, libraries should
3393 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3394 * g_warning() and g_error().
3397 g_print (const gchar *format,
3401 const gchar *string;
3402 gchar *free_me = NULL;
3403 GPrintFunc local_glib_print_func;
3405 g_return_if_fail (format != NULL);
3407 va_start (args, format);
3408 string = format_string (format, args, &free_me);
3411 local_glib_print_func = g_atomic_pointer_get (&glib_print_func);
3412 local_glib_print_func (string);
3417 * g_set_printerr_handler:
3418 * @func: (nullable): he new error message handler or %NULL
3419 * to reset to the default
3421 * Sets the handler for printing error messages to @func,
3422 * or resets it to the default GLib handler if %NULL.
3424 * Any messages passed to g_printerr() will be output via
3425 * the new handler. The default handler outputs the encoded
3426 * message to stderr. By providing your own handler you can
3427 * redirect the output, to a GTK widget or a log file for
3430 * Since 2.76 this functions always returns a valid
3431 * #GPrintFunc, and never returns %NULL. If no custom error
3432 * print handler was set, it will return the GLib default
3433 * error print handler and that can be re-used to decorate
3434 * its output and/or to write to stderr in all platforms.
3435 * Before GLib 2.76, this was %NULL.
3437 * Returns: (not nullable): the old error message handler
3440 g_set_printerr_handler (GPrintFunc func)
3442 return g_atomic_pointer_exchange (&glib_printerr_func,
3443 func ? func : g_default_printerr_func);
3448 * @format: the message format. See the printf() documentation
3449 * @...: the parameters to insert into the format string
3451 * Outputs a formatted message via the error message handler.
3452 * The default handler outputs the encoded message to stderr, without appending
3453 * a trailing new-line character. Typically, @format should end with its own
3454 * new-line character.
3456 * g_printerr() should not be used from within libraries.
3457 * Instead g_log() or g_log_structured() should be used, or the convenience
3458 * macros g_message(), g_warning() and g_error().
3461 g_printerr (const gchar *format,
3466 char *free_me = NULL;
3467 GPrintFunc local_glib_printerr_func;
3469 g_return_if_fail (format != NULL);
3471 va_start (args, format);
3472 string = format_string (format, args, &free_me);
3475 local_glib_printerr_func = g_atomic_pointer_get (&glib_printerr_func);
3476 local_glib_printerr_func (string);
3481 * g_printf_string_upper_bound:
3482 * @format: the format string. See the printf() documentation
3483 * @args: the parameters to be inserted into the format string
3485 * Calculates the maximum space needed to store the output
3486 * of the sprintf() function.
3488 * Returns: the maximum space needed to store the formatted string
3491 g_printf_string_upper_bound (const gchar *format,
3495 return _g_vsnprintf (&c, 1, format, args) + 1;