1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
31 * @Title: Message Output and Debugging Functions
32 * @Short_description: functions to output messages and help debug applications
34 * These functions provide support for outputting messages.
36 * The g_return family of macros (g_return_if_fail(),
37 * g_return_val_if_fail(), g_return_if_reached(),
38 * g_return_val_if_reached()) should only be used for programming
39 * errors, a typical use case is checking for invalid parameters at
40 * the beginning of a public function. They should not be used if
41 * you just mean "if (error) return", they should only be used if
42 * you mean "if (bug in program) return". The program behavior is
43 * generally considered undefined after one of these checks fails.
44 * They are not intended for normal control flow, only to give a
45 * perhaps-helpful warning before giving up.
47 * Structured logging output is supported using g_log_structured(). This differs
48 * from the traditional g_log() API in that log messages are handled as a
49 * collection of key–value pairs representing individual pieces of information,
50 * rather than as a single string containing all the information in an arbitrary
53 * The convenience macros g_info(), g_message(), g_debug(), g_warning() and g_error()
54 * will use the traditional g_log() API unless you define the symbol
55 * %G_LOG_USE_STRUCTURED before including `glib.h`. But note that even messages
56 * logged through the traditional g_log() API are ultimatively passed to
57 * g_log_structured(), so that all log messages end up in same destination.
58 * If %G_LOG_USE_STRUCTURED is defined, g_test_expect_message() will become
59 * ineffective for the wrapper macros g_warning() and friends (see
60 * [Testing for Messages][testing-for-messages]).
62 * The support for structured logging was motivated by the following needs (some
63 * of which were supported previously; others weren’t):
64 * * Support for multiple logging levels.
65 * * Structured log support with the ability to add `MESSAGE_ID`s (see
66 * g_log_structured()).
67 * * Moving the responsibility for filtering log messages from the program to
68 * the log viewer — instead of libraries and programs installing log handlers
69 * (with g_log_set_handler()) which filter messages before output, all log
70 * messages are outputted, and the log viewer program (such as `journalctl`)
71 * must filter them. This is based on the idea that bugs are sometimes hard
72 * to reproduce, so it is better to log everything possible and then use
73 * tools to analyse the logs than it is to not be able to reproduce a bug to
74 * get additional log data. Code which uses logging in performance-critical
75 * sections should compile out the g_log_structured() calls in
76 * release builds, and compile them in in debugging builds.
77 * * A single writer function which handles all log messages in a process, from
78 * all libraries and program code; rather than multiple log handlers with
79 * poorly defined interactions between them. This allows a program to easily
80 * change its logging policy by changing the writer function, for example to
81 * log to an additional location or to change what logging output fallbacks
82 * are used. The log writer functions provided by GLib are exposed publicly
83 * so they can be used from programs’ log writers. This allows log writer
84 * policy and implementation to be kept separate.
85 * * If a library wants to add standard information to all of its log messages
86 * (such as library state) or to redact private data (such as passwords or
87 * network credentials), it should use a wrapper function around its
88 * g_log_structured() calls or implement that in the single log writer
90 * * If a program wants to pass context data from a g_log_structured() call to
91 * its log writer function so that, for example, it can use the correct
92 * server connection to submit logs to, that user data can be passed as a
93 * zero-length #GLogField to g_log_structured_array().
94 * * Color output needed to be supported on the terminal, to make reading
95 * through logs easier.
97 * ## Using Structured Logging
99 * To use structured logging (rather than the old-style logging), either use
100 * the g_log_structured() and g_log_structured_array() functions; or define
101 * `G_LOG_USE_STRUCTURED` before including any GLib header, and use the
102 * g_message(), g_debug(), g_error() (etc.) macros.
104 * You do not need to define `G_LOG_USE_STRUCTURED` to use g_log_structured(),
105 * but it is a good idea to avoid confusion.
109 * Log domains may be used to broadly split up the origins of log messages.
110 * Typically, there are one or a few log domains per application or library.
111 * %G_LOG_DOMAIN should be used to define the default log domain for the current
112 * compilation unit — it is typically defined at the top of a source file, or in
113 * the preprocessor flags for a group of source files.
115 * Log domains must be unique, and it is recommended that they are the
116 * application or library name, optionally followed by a hyphen and a sub-domain
117 * name. For example, `bloatpad` or `bloatpad-io`.
119 * ## Debug Message Output
121 * The default log functions (g_log_default_handler() for the old-style API and
122 * g_log_writer_default() for the structured API) both drop debug and
123 * informational messages by default, unless the log domains of those messages
124 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
127 * It is recommended that custom log writer functions re-use the
128 * `G_MESSAGES_DEBUG` environment variable, rather than inventing a custom one,
129 * so that developers can re-use the same debugging techniques and tools across
132 * ## Testing for Messages
134 * With the old g_log() API, g_test_expect_message() and
135 * g_test_assert_expected_messages() could be used in simple cases to check
136 * whether some code under test had emitted a given log message. These
137 * functions have been deprecated with the structured logging API, for several
139 * * They relied on an internal queue which was too inflexible for many use
140 * cases, where messages might be emitted in several orders, some
141 * messages might not be emitted deterministically, or messages might be
142 * emitted by unrelated log domains.
143 * * They do not support structured log fields.
144 * * Examining the log output of code is a bad approach to testing it, and
145 * while it might be necessary for legacy code which uses g_log(), it should
146 * be avoided for new code using g_log_structured().
148 * They will continue to work as before if g_log() is in use (and
149 * %G_LOG_USE_STRUCTURED is not defined). They will do nothing if used with the
150 * structured logging API.
152 * Examining the log output of code is discouraged: libraries should not emit to
153 * `stderr` during defined behaviour, and hence this should not be tested. If
154 * the log emissions of a library during undefined behaviour need to be tested,
155 * they should be limited to asserting that the library aborts and prints a
156 * suitable error message before aborting. This should be done with
157 * g_test_trap_assert_stderr().
159 * If it is really necessary to test the structured log messages emitted by a
160 * particular piece of code – and the code cannot be restructured to be more
161 * suitable to more conventional unit testing – you should write a custom log
162 * writer function (see g_log_set_writer_func()) which appends all log messages
163 * to a queue. When you want to check the log messages, examine and clear the
164 * queue, ignoring irrelevant log messages (for example, from log domains other
165 * than the one under test).
178 #if defined(__linux__) && !defined(__BIONIC__)
179 #include <sys/types.h>
180 #include <sys/socket.h>
186 #include "glib-init.h"
188 #include "gbacktrace.h"
189 #include "gcharset.h"
190 #include "gconvert.h"
191 #include "genviron.h"
193 #include "gprintfint.h"
194 #include "gtestutils.h"
196 #include "gstrfuncs.h"
198 #include "gpattern.h"
205 #include <process.h> /* For getpid() */
207 # include <windows.h>
209 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
210 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
213 /* XXX: Remove once XP support really dropped */
214 #if _WIN32_WINNT < 0x0600
216 typedef enum _FILE_INFO_BY_HANDLE_CLASS
219 FileStandardInfo
= 1,
222 FileDispositionInfo
= 4,
223 FileAllocationInfo
= 5,
224 FileEndOfFileInfo
= 6,
226 FileCompressionInfo
= 8,
227 FileAttributeTagInfo
= 9,
228 FileIdBothDirectoryInfo
= 10,
229 FileIdBothDirectoryRestartInfo
= 11,
230 FileIoPriorityHintInfo
= 12,
231 FileRemoteProtocolInfo
= 13,
232 FileFullDirectoryInfo
= 14,
233 FileFullDirectoryRestartInfo
= 15,
234 FileStorageInfo
= 16,
235 FileAlignmentInfo
= 17,
237 FileIdExtdDirectoryInfo
= 19,
238 FileIdExtdDirectoryRestartInfo
= 20,
239 MaximumFileInfoByHandlesClass
240 } FILE_INFO_BY_HANDLE_CLASS
;
242 typedef struct _FILE_NAME_INFO
244 DWORD FileNameLength
;
248 typedef BOOL (WINAPI fGetFileInformationByHandleEx
) (HANDLE
,
249 FILE_INFO_BY_HANDLE_CLASS
,
254 #if defined (_MSC_VER) && (_MSC_VER >=1400)
255 /* This is ugly, but we need it for isatty() in case we have bad fd's,
256 * otherwise Windows will abort() the program on msvcrt80.dll and later
261 myInvalidParameterHandler(const wchar_t *expression
,
262 const wchar_t *function
,
276 * Defines the log domain.
278 * For applications, this is typically left as the default %NULL
279 * (or "") domain. Libraries should define this so that any messages
280 * which they log can be differentiated from messages from other
281 * libraries and application code. But be careful not to define
282 * it in any public header files.
284 * For example, GTK+ uses this in its Makefile.am:
286 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
293 * GLib log levels that are considered fatal by default.
295 * This is not used if structured logging is enabled; see
296 * [Using Structured Logging][using-structured-logging].
301 * @log_domain: the log domain of the message
302 * @log_level: the log level of the message (including the
303 * fatal and recursion flags)
304 * @message: the message to process
305 * @user_data: user data, set in g_log_set_handler()
307 * Specifies the prototype of log handler functions.
309 * The default log handler, g_log_default_handler(), automatically appends a
310 * new-line character to @message when printing it. It is advised that any
311 * custom log handler functions behave similarly, so that logging calls in user
312 * code do not need modifying to add a new-line character to the message if the
313 * log handler is changed.
315 * This is not used if structured logging is enabled; see
316 * [Using Structured Logging][using-structured-logging].
321 * @G_LOG_FLAG_RECURSION: internal flag
322 * @G_LOG_FLAG_FATAL: internal flag
323 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
324 * This level is also used for messages produced by g_assert().
325 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
327 * This level is also used for messages produced by g_return_if_fail()
328 * and g_return_val_if_fail().
329 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
330 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
331 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
332 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
333 * @G_LOG_LEVEL_MASK: a mask including all log levels
335 * Flags specifying the level of log messages.
337 * It is possible to change how GLib treats messages of the various
338 * levels using g_log_set_handler() and g_log_set_fatal_mask().
342 * G_LOG_LEVEL_USER_SHIFT:
344 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
345 * Higher bits can be used for user-defined log levels.
350 * @...: format string, followed by parameters to insert
351 * into the format string (as with printf())
353 * A convenience function/macro to log a normal message.
355 * If g_log_default_handler() is used as the log handler function, a new-line
356 * character will automatically be appended to @..., and need not be entered
359 * If structured logging is enabled, this will use g_log_structured();
360 * otherwise it will use g_log(). See
361 * [Using Structured Logging][using-structured-logging].
366 * @...: format string, followed by parameters to insert
367 * into the format string (as with printf())
369 * A convenience function/macro to log a warning message.
371 * This is not intended for end user error reporting. Use of #GError is
372 * preferred for that instead, as it allows calling functions to perform actions
373 * conditional on the type of error.
375 * You can make warnings fatal at runtime by setting the `G_DEBUG`
376 * environment variable (see
377 * [Running GLib Applications](glib-running.html)).
379 * If g_log_default_handler() is used as the log handler function,
380 * a newline character will automatically be appended to @..., and
381 * need not be entered manually.
383 * If structured logging is enabled, this will use g_log_structured();
384 * otherwise it will use g_log(). See
385 * [Using Structured Logging][using-structured-logging].
390 * @...: format string, followed by parameters to insert
391 * into the format string (as with printf())
393 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
394 * It's more or less application-defined what constitutes
395 * a critical vs. a regular warning. You could call
396 * g_log_set_always_fatal() to make critical warnings exit
397 * the program, then use g_critical() for fatal errors, for
400 * You can also make critical warnings fatal at runtime by
401 * setting the `G_DEBUG` environment variable (see
402 * [Running GLib Applications](glib-running.html)).
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.
420 * This is not intended for end user error reporting. Use of #GError is
421 * preferred for that instead, as it allows calling functions to perform actions
422 * conditional on the type of error.
424 * Error messages are always fatal, resulting in a call to
425 * abort() to terminate the application. This function will
426 * result in a core dump; don't use it for errors you expect.
427 * Using this function indicates a bug in your program, i.e.
428 * an assertion failure.
430 * If g_log_default_handler() is used as the log handler function, a new-line
431 * character will automatically be appended to @..., and need not be entered
434 * If structured logging is enabled, this will use g_log_structured();
435 * otherwise it will use g_log(). See
436 * [Using Structured Logging][using-structured-logging].
441 * @...: format string, followed by parameters to insert
442 * into the format string (as with printf())
444 * A convenience function/macro to log an informational message. Seldom used.
446 * If g_log_default_handler() is used as the log handler function, a new-line
447 * character will automatically be appended to @..., and need not be entered
450 * Such messages are suppressed by the g_log_default_handler() and
451 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
454 * If structured logging is enabled, this will use g_log_structured();
455 * otherwise it will use g_log(). See
456 * [Using Structured Logging][using-structured-logging].
463 * @...: format string, followed by parameters to insert
464 * into the format string (as with printf())
466 * A convenience function/macro to log a debug message.
468 * If g_log_default_handler() is used as the log handler function, a new-line
469 * character will automatically be appended to @..., and need not be entered
472 * Such messages are suppressed by the g_log_default_handler() and
473 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
476 * If structured logging is enabled, this will use g_log_structured();
477 * otherwise it will use g_log(). See
478 * [Using Structured Logging][using-structured-logging].
483 /* --- structures --- */
484 typedef struct _GLogDomain GLogDomain
;
485 typedef struct _GLogHandler GLogHandler
;
489 GLogLevelFlags fatal_mask
;
490 GLogHandler
*handlers
;
496 GLogLevelFlags log_level
;
499 GDestroyNotify destroy
;
504 /* --- variables --- */
505 static GMutex g_messages_lock
;
506 static GLogDomain
*g_log_domains
= NULL
;
507 static GPrintFunc glib_print_func
= NULL
;
508 static GPrintFunc glib_printerr_func
= NULL
;
509 static GPrivate g_log_depth
;
510 static GPrivate g_log_structured_depth
;
511 static GLogFunc default_log_func
= g_log_default_handler
;
512 static gpointer default_log_data
= NULL
;
513 static GTestLogFatalFunc fatal_log_func
= NULL
;
514 static gpointer fatal_log_data
;
515 static GLogWriterFunc log_writer_func
= g_log_writer_default
;
516 static gpointer log_writer_user_data
= NULL
;
517 static GDestroyNotify log_writer_user_data_free
= NULL
;
519 /* --- functions --- */
521 static void _g_log_abort (gboolean breakpoint
);
524 _g_log_abort (gboolean breakpoint
)
526 gboolean debugger_present
;
528 if (g_test_subprocess ())
530 /* If this is a test case subprocess then it probably caused
531 * this error message on purpose, so just exit() rather than
532 * abort()ing, to avoid triggering any system crash-reporting
539 debugger_present
= IsDebuggerPresent ();
541 /* Assume GDB is attached. */
542 debugger_present
= TRUE
;
543 #endif /* !G_OS_WIN32 */
545 if (debugger_present
&& breakpoint
)
552 static gboolean win32_keep_fatal_message
= FALSE
;
554 /* This default message will usually be overwritten. */
555 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
556 * called with huge strings, is it?
558 static gchar fatal_msg_buf
[1000] = "Unspecified fatal error encountered, aborting.";
559 static gchar
*fatal_msg_ptr
= fatal_msg_buf
;
567 if (win32_keep_fatal_message
)
569 memcpy (fatal_msg_ptr
, buf
, len
);
570 fatal_msg_ptr
+= len
;
575 write (fd
, buf
, len
);
579 #define write(fd, buf, len) dowrite(fd, buf, len)
584 write_string (FILE *stream
,
587 fputs (string
, stream
);
591 write_string_sized (FILE *stream
,
595 /* Is it nul-terminated? */
597 write_string (stream
, string
);
599 fwrite (string
, 1, length
, stream
);
603 g_log_find_domain_L (const gchar
*log_domain
)
607 domain
= g_log_domains
;
610 if (strcmp (domain
->log_domain
, log_domain
) == 0)
612 domain
= domain
->next
;
618 g_log_domain_new_L (const gchar
*log_domain
)
622 domain
= g_new (GLogDomain
, 1);
623 domain
->log_domain
= g_strdup (log_domain
);
624 domain
->fatal_mask
= G_LOG_FATAL_MASK
;
625 domain
->handlers
= NULL
;
627 domain
->next
= g_log_domains
;
628 g_log_domains
= domain
;
634 g_log_domain_check_free_L (GLogDomain
*domain
)
636 if (domain
->fatal_mask
== G_LOG_FATAL_MASK
&&
637 domain
->handlers
== NULL
)
639 GLogDomain
*last
, *work
;
643 work
= g_log_domains
;
649 last
->next
= domain
->next
;
651 g_log_domains
= domain
->next
;
652 g_free (domain
->log_domain
);
663 g_log_domain_get_handler_L (GLogDomain
*domain
,
664 GLogLevelFlags log_level
,
667 if (domain
&& log_level
)
669 GLogHandler
*handler
;
671 handler
= domain
->handlers
;
674 if ((handler
->log_level
& log_level
) == log_level
)
676 *data
= handler
->data
;
677 return handler
->log_func
;
679 handler
= handler
->next
;
683 *data
= default_log_data
;
684 return default_log_func
;
688 * g_log_set_always_fatal:
689 * @fatal_mask: the mask containing bits set for each level
690 * of error which is to be fatal
692 * Sets the message levels which are always fatal, in any log domain.
693 * When a message with any of these levels is logged the program terminates.
694 * You can only set the levels defined by GLib to be fatal.
695 * %G_LOG_LEVEL_ERROR is always fatal.
697 * You can also make some message levels fatal at runtime by setting
698 * the `G_DEBUG` environment variable (see
699 * [Running GLib Applications](glib-running.html)).
701 * Libraries should not call this function, as it affects all messages logged
702 * by a process, including those from other libraries.
704 * Structured log messages (using g_log_structured() and
705 * g_log_structured_array()) are fatal only if the default log writer is used;
706 * otherwise it is up to the writer function to determine which log messages
707 * are fatal. See [Using Structured Logging][using-structured-logging].
709 * Returns: the old fatal mask
712 g_log_set_always_fatal (GLogLevelFlags fatal_mask
)
714 GLogLevelFlags old_mask
;
716 /* restrict the global mask to levels that are known to glib
717 * since this setting applies to all domains
719 fatal_mask
&= (1 << G_LOG_LEVEL_USER_SHIFT
) - 1;
720 /* force errors to be fatal */
721 fatal_mask
|= G_LOG_LEVEL_ERROR
;
722 /* remove bogus flag */
723 fatal_mask
&= ~G_LOG_FLAG_FATAL
;
725 g_mutex_lock (&g_messages_lock
);
726 old_mask
= g_log_always_fatal
;
727 g_log_always_fatal
= fatal_mask
;
728 g_mutex_unlock (&g_messages_lock
);
734 * g_log_set_fatal_mask:
735 * @log_domain: the log domain
736 * @fatal_mask: the new fatal mask
738 * Sets the log levels which are fatal in the given domain.
739 * %G_LOG_LEVEL_ERROR is always fatal.
741 * This has no effect on structured log messages (using g_log_structured() or
742 * g_log_structured_array()). To change the fatal behaviour for specific log
743 * messages, programs must install a custom log writer function using
744 * g_log_set_writer_func(). See
745 * [Using Structured Logging][using-structured-logging].
747 * Returns: the old fatal mask for the log domain
750 g_log_set_fatal_mask (const gchar
*log_domain
,
751 GLogLevelFlags fatal_mask
)
753 GLogLevelFlags old_flags
;
759 /* force errors to be fatal */
760 fatal_mask
|= G_LOG_LEVEL_ERROR
;
761 /* remove bogus flag */
762 fatal_mask
&= ~G_LOG_FLAG_FATAL
;
764 g_mutex_lock (&g_messages_lock
);
766 domain
= g_log_find_domain_L (log_domain
);
768 domain
= g_log_domain_new_L (log_domain
);
769 old_flags
= domain
->fatal_mask
;
771 domain
->fatal_mask
= fatal_mask
;
772 g_log_domain_check_free_L (domain
);
774 g_mutex_unlock (&g_messages_lock
);
781 * @log_domain: (nullable): the log domain, or %NULL for the default ""
783 * @log_levels: the log levels to apply the log handler for.
784 * To handle fatal and recursive messages as well, combine
785 * the log levels with the #G_LOG_FLAG_FATAL and
786 * #G_LOG_FLAG_RECURSION bit flags.
787 * @log_func: the log handler function
788 * @user_data: data passed to the log handler
790 * Sets the log handler for a domain and a set of log levels.
791 * To handle fatal and recursive messages the @log_levels parameter
792 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
795 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
796 * you want to set a handler for this log level you must combine it with
799 * This has no effect if structured logging is enabled; see
800 * [Using Structured Logging][using-structured-logging].
802 * Here is an example for adding a log handler for all warning messages
803 * in the default domain:
804 * |[<!-- language="C" -->
805 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
806 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
809 * This example adds a log handler for all critical messages from GTK+:
810 * |[<!-- language="C" -->
811 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
812 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
815 * This example adds a log handler for all messages from GLib:
816 * |[<!-- language="C" -->
817 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
818 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
821 * Returns: the id of the new handler
824 g_log_set_handler (const gchar
*log_domain
,
825 GLogLevelFlags log_levels
,
829 return g_log_set_handler_full (log_domain
, log_levels
, log_func
, user_data
, NULL
);
833 * g_log_set_handler_full: (rename-to g_log_set_handler)
834 * @log_domain: (nullable): the log domain, or %NULL for the default ""
836 * @log_levels: the log levels to apply the log handler for.
837 * To handle fatal and recursive messages as well, combine
838 * the log levels with the #G_LOG_FLAG_FATAL and
839 * #G_LOG_FLAG_RECURSION bit flags.
840 * @log_func: the log handler function
841 * @user_data: data passed to the log handler
842 * @destroy: destroy notify for @user_data, or %NULL
844 * Like g_log_sets_handler(), but takes a destroy notify for the @user_data.
846 * This has no effect if structured logging is enabled; see
847 * [Using Structured Logging][using-structured-logging].
849 * Returns: the id of the new handler
854 g_log_set_handler_full (const gchar
*log_domain
,
855 GLogLevelFlags log_levels
,
858 GDestroyNotify destroy
)
860 static guint handler_id
= 0;
862 GLogHandler
*handler
;
864 g_return_val_if_fail ((log_levels
& G_LOG_LEVEL_MASK
) != 0, 0);
865 g_return_val_if_fail (log_func
!= NULL
, 0);
870 handler
= g_new (GLogHandler
, 1);
872 g_mutex_lock (&g_messages_lock
);
874 domain
= g_log_find_domain_L (log_domain
);
876 domain
= g_log_domain_new_L (log_domain
);
878 handler
->id
= ++handler_id
;
879 handler
->log_level
= log_levels
;
880 handler
->log_func
= log_func
;
881 handler
->data
= user_data
;
882 handler
->destroy
= destroy
;
883 handler
->next
= domain
->handlers
;
884 domain
->handlers
= handler
;
886 g_mutex_unlock (&g_messages_lock
);
892 * g_log_set_default_handler:
893 * @log_func: the log handler function
894 * @user_data: data passed to the log handler
896 * Installs a default log handler which is used if no
897 * log handler has been set for the particular log domain
898 * and log level combination. By default, GLib uses
899 * g_log_default_handler() as default log handler.
901 * This has no effect if structured logging is enabled; see
902 * [Using Structured Logging][using-structured-logging].
904 * Returns: the previous default log handler
909 g_log_set_default_handler (GLogFunc log_func
,
912 GLogFunc old_log_func
;
914 g_mutex_lock (&g_messages_lock
);
915 old_log_func
= default_log_func
;
916 default_log_func
= log_func
;
917 default_log_data
= user_data
;
918 g_mutex_unlock (&g_messages_lock
);
924 * g_test_log_set_fatal_handler:
925 * @log_func: the log handler function.
926 * @user_data: data passed to the log handler.
928 * Installs a non-error fatal log handler which can be
929 * used to decide whether log messages which are counted
930 * as fatal abort the program.
932 * The use case here is that you are running a test case
933 * that depends on particular libraries or circumstances
934 * and cannot prevent certain known critical or warning
935 * messages. So you install a handler that compares the
936 * domain and message to precisely not abort in such a case.
938 * Note that the handler is reset at the beginning of
939 * any test case, so you have to set it inside each test
940 * function which needs the special behavior.
942 * This handler has no effect on g_error messages.
944 * This handler also has no effect on structured log messages (using
945 * g_log_structured() or g_log_structured_array()). To change the fatal
946 * behaviour for specific log messages, programs must install a custom log
947 * writer function using g_log_set_writer_func().See
948 * [Using Structured Logging][using-structured-logging].
953 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func
,
956 g_mutex_lock (&g_messages_lock
);
957 fatal_log_func
= log_func
;
958 fatal_log_data
= user_data
;
959 g_mutex_unlock (&g_messages_lock
);
963 * g_log_remove_handler:
964 * @log_domain: the log domain
965 * @handler_id: the id of the handler, which was returned
966 * in g_log_set_handler()
968 * Removes the log handler.
970 * This has no effect if structured logging is enabled; see
971 * [Using Structured Logging][using-structured-logging].
974 g_log_remove_handler (const gchar
*log_domain
,
979 g_return_if_fail (handler_id
> 0);
984 g_mutex_lock (&g_messages_lock
);
985 domain
= g_log_find_domain_L (log_domain
);
988 GLogHandler
*work
, *last
;
991 work
= domain
->handlers
;
994 if (work
->id
== handler_id
)
997 last
->next
= work
->next
;
999 domain
->handlers
= work
->next
;
1000 g_log_domain_check_free_L (domain
);
1001 g_mutex_unlock (&g_messages_lock
);
1003 work
->destroy (work
->data
);
1011 g_mutex_unlock (&g_messages_lock
);
1012 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1013 G_STRLOC
, handler_id
, log_domain
);
1016 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1018 (wc >= 0x80 && wc < 0xa0)))
1021 strdup_convert (const gchar
*string
,
1022 const gchar
*charset
)
1024 if (!g_utf8_validate (string
, -1, NULL
))
1026 GString
*gstring
= g_string_new ("[Invalid UTF-8] ");
1029 for (p
= (guchar
*)string
; *p
; p
++)
1031 if (CHAR_IS_SAFE(*p
) &&
1032 !(*p
== '\r' && *(p
+ 1) != '\n') &&
1034 g_string_append_c (gstring
, *p
);
1036 g_string_append_printf (gstring
, "\\x%02x", (guint
)(guchar
)*p
);
1039 return g_string_free (gstring
, FALSE
);
1045 gchar
*result
= g_convert_with_fallback (string
, -1, charset
, "UTF-8", "?", NULL
, NULL
, &err
);
1050 /* Not thread-safe, but doesn't matter if we print the warning twice
1052 static gboolean warned
= FALSE
;
1056 _g_fprintf (stderr
, "GLib: Cannot convert message: %s\n", err
->message
);
1060 return g_strdup (string
);
1065 /* For a radix of 8 we need at most 3 output bytes for 1 input
1066 * byte. Additionally we might need up to 2 output bytes for the
1067 * readix prefix and 1 byte for the trailing NULL.
1069 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1072 format_unsigned (gchar
*buf
,
1080 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1082 if (radix
!= 8 && radix
!= 10 && radix
!= 16)
1100 else if (radix
== 8)
1115 /* Again we can't use g_assert; actually this check should _never_ fail. */
1116 if (n
> FORMAT_UNSIGNED_BUFSIZE
- 3)
1129 buf
[i
] = c
+ 'a' - 10;
1136 /* string size big enough to hold level prefix */
1137 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1139 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1141 /* these are emitted by the default log handler */
1142 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1143 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1144 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1146 static const gchar
*log_level_to_color (GLogLevelFlags log_level
,
1147 gboolean use_color
);
1148 static const gchar
*color_reset (gboolean use_color
);
1151 mklevel_prefix (gchar level_prefix
[STRING_BUFFER_SIZE
],
1152 GLogLevelFlags log_level
,
1155 gboolean to_stdout
= TRUE
;
1157 /* we may not call _any_ GLib functions here */
1159 strcpy (level_prefix
, log_level_to_color (log_level
, use_color
));
1161 switch (log_level
& G_LOG_LEVEL_MASK
)
1163 case G_LOG_LEVEL_ERROR
:
1164 strcat (level_prefix
, "ERROR");
1167 case G_LOG_LEVEL_CRITICAL
:
1168 strcat (level_prefix
, "CRITICAL");
1171 case G_LOG_LEVEL_WARNING
:
1172 strcat (level_prefix
, "WARNING");
1175 case G_LOG_LEVEL_MESSAGE
:
1176 strcat (level_prefix
, "Message");
1179 case G_LOG_LEVEL_INFO
:
1180 strcat (level_prefix
, "INFO");
1182 case G_LOG_LEVEL_DEBUG
:
1183 strcat (level_prefix
, "DEBUG");
1188 strcat (level_prefix
, "LOG-");
1189 format_unsigned (level_prefix
+ 4, log_level
& G_LOG_LEVEL_MASK
, 16);
1192 strcat (level_prefix
, "LOG");
1196 strcat (level_prefix
, color_reset (use_color
));
1198 if (log_level
& G_LOG_FLAG_RECURSION
)
1199 strcat (level_prefix
, " (recursed)");
1200 if (log_level
& ALERT_LEVELS
)
1201 strcat (level_prefix
, " **");
1204 if ((log_level
& G_LOG_FLAG_FATAL
) != 0 && !g_test_initialized ())
1205 win32_keep_fatal_message
= TRUE
;
1207 return to_stdout
? stdout
: stderr
;
1212 GLogLevelFlags log_level
;
1214 } GTestExpectedMessage
;
1216 static GSList
*expected_messages
= NULL
;
1220 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1221 * application domain
1222 * @log_level: the log level
1223 * @format: the message format. See the printf() documentation
1224 * @args: the parameters to insert into the format string
1226 * Logs an error or debugging message.
1228 * If the log level has been set as fatal, the abort()
1229 * function is called to terminate the program.
1231 * If g_log_default_handler() is used as the log handler function, a new-line
1232 * character will automatically be appended to @..., and need not be entered
1235 * If [structured logging is enabled][using-structured-logging] this will
1236 * output via the structured log writer function (see g_log_set_writer_func()).
1239 g_logv (const gchar
*log_domain
,
1240 GLogLevelFlags log_level
,
1241 const gchar
*format
,
1244 gboolean was_fatal
= (log_level
& G_LOG_FLAG_FATAL
) != 0;
1245 gboolean was_recursion
= (log_level
& G_LOG_FLAG_RECURSION
) != 0;
1246 gchar buffer
[1025], *msg
, *msg_alloc
= NULL
;
1249 log_level
&= G_LOG_LEVEL_MASK
;
1253 if (log_level
& G_LOG_FLAG_RECURSION
)
1255 /* we use a stack buffer of fixed size, since we're likely
1256 * in an out-of-memory situation
1258 gsize size G_GNUC_UNUSED
;
1260 size
= _g_vsnprintf (buffer
, 1024, format
, args
);
1264 msg
= msg_alloc
= g_strdup_vprintf (format
, args
);
1266 if (expected_messages
)
1268 GTestExpectedMessage
*expected
= expected_messages
->data
;
1270 if (g_strcmp0 (expected
->log_domain
, log_domain
) == 0 &&
1271 ((log_level
& expected
->log_level
) == expected
->log_level
) &&
1272 g_pattern_match_simple (expected
->pattern
, msg
))
1274 expected_messages
= g_slist_delete_link (expected_messages
,
1276 g_free (expected
->log_domain
);
1277 g_free (expected
->pattern
);
1282 else if ((log_level
& G_LOG_LEVEL_DEBUG
) != G_LOG_LEVEL_DEBUG
)
1284 gchar level_prefix
[STRING_BUFFER_SIZE
];
1285 gchar
*expected_message
;
1287 mklevel_prefix (level_prefix
, expected
->log_level
, FALSE
);
1288 expected_message
= g_strdup_printf ("Did not see expected message %s-%s: %s",
1289 expected
->log_domain
? expected
->log_domain
: "**",
1290 level_prefix
, expected
->pattern
);
1291 g_log_default_handler (G_LOG_DOMAIN
, G_LOG_LEVEL_CRITICAL
, expected_message
, NULL
);
1292 g_free (expected_message
);
1294 log_level
|= G_LOG_FLAG_FATAL
;
1298 for (i
= g_bit_nth_msf (log_level
, -1); i
>= 0; i
= g_bit_nth_msf (log_level
, i
))
1300 GLogLevelFlags test_level
;
1302 test_level
= 1 << i
;
1303 if (log_level
& test_level
)
1307 GLogLevelFlags domain_fatal_mask
;
1308 gpointer data
= NULL
;
1309 gboolean masquerade_fatal
= FALSE
;
1313 test_level
|= G_LOG_FLAG_FATAL
;
1315 test_level
|= G_LOG_FLAG_RECURSION
;
1317 /* check recursion and lookup handler */
1318 g_mutex_lock (&g_messages_lock
);
1319 depth
= GPOINTER_TO_UINT (g_private_get (&g_log_depth
));
1320 domain
= g_log_find_domain_L (log_domain
? log_domain
: "");
1322 test_level
|= G_LOG_FLAG_RECURSION
;
1324 domain_fatal_mask
= domain
? domain
->fatal_mask
: G_LOG_FATAL_MASK
;
1325 if ((domain_fatal_mask
| g_log_always_fatal
) & test_level
)
1326 test_level
|= G_LOG_FLAG_FATAL
;
1327 if (test_level
& G_LOG_FLAG_RECURSION
)
1328 log_func
= _g_log_fallback_handler
;
1330 log_func
= g_log_domain_get_handler_L (domain
, test_level
, &data
);
1332 g_mutex_unlock (&g_messages_lock
);
1334 g_private_set (&g_log_depth
, GUINT_TO_POINTER (depth
));
1336 log_func (log_domain
, test_level
, msg
, data
);
1338 if ((test_level
& G_LOG_FLAG_FATAL
)
1339 && !(test_level
& G_LOG_LEVEL_ERROR
))
1341 masquerade_fatal
= fatal_log_func
1342 && !fatal_log_func (log_domain
, test_level
, msg
, fatal_log_data
);
1345 if ((test_level
& G_LOG_FLAG_FATAL
) && !masquerade_fatal
)
1348 if (win32_keep_fatal_message
)
1350 gchar
*locale_msg
= g_locale_from_utf8 (fatal_msg_buf
, -1, NULL
, NULL
, NULL
);
1352 MessageBox (NULL
, locale_msg
, NULL
,
1353 MB_ICONERROR
|MB_SETFOREGROUND
);
1355 #endif /* !G_OS_WIN32 */
1357 _g_log_abort (!(test_level
& G_LOG_FLAG_RECURSION
));
1361 g_private_set (&g_log_depth
, GUINT_TO_POINTER (depth
));
1370 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1372 * @log_level: the log level, either from #GLogLevelFlags
1373 * or a user-defined level
1374 * @format: the message format. See the printf() documentation
1375 * @...: the parameters to insert into the format string
1377 * Logs an error or debugging message.
1379 * If the log level has been set as fatal, the abort()
1380 * function is called to terminate the program.
1382 * If g_log_default_handler() is used as the log handler function, a new-line
1383 * character will automatically be appended to @..., and need not be entered
1386 * If [structured logging is enabled][using-structured-logging] this will
1387 * output via the structured log writer function (see g_log_set_writer_func()).
1390 g_log (const gchar
*log_domain
,
1391 GLogLevelFlags log_level
,
1392 const gchar
*format
,
1397 va_start (args
, format
);
1398 g_logv (log_domain
, log_level
, format
, args
);
1402 /* Return value must be 1 byte long (plus nul byte).
1403 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1405 static const gchar
*
1406 log_level_to_priority (GLogLevelFlags log_level
)
1408 if (log_level
& G_LOG_LEVEL_ERROR
)
1410 else if (log_level
& G_LOG_LEVEL_CRITICAL
)
1412 else if (log_level
& G_LOG_LEVEL_WARNING
)
1414 else if (log_level
& G_LOG_LEVEL_MESSAGE
)
1416 else if (log_level
& G_LOG_LEVEL_INFO
)
1418 else if (log_level
& G_LOG_LEVEL_DEBUG
)
1421 /* Default to LOG_NOTICE for custom log levels. */
1426 log_level_to_file (GLogLevelFlags log_level
)
1428 if (log_level
& (G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
|
1429 G_LOG_LEVEL_WARNING
| G_LOG_LEVEL_MESSAGE
))
1435 static const gchar
*
1436 log_level_to_color (GLogLevelFlags log_level
,
1439 /* we may not call _any_ GLib functions here */
1444 if (log_level
& G_LOG_LEVEL_ERROR
)
1445 return "\033[1;31m";
1446 else if (log_level
& G_LOG_LEVEL_CRITICAL
)
1447 return "\033[1;35m";
1448 else if (log_level
& G_LOG_LEVEL_WARNING
)
1449 return "\033[1;33m";
1450 else if (log_level
& G_LOG_LEVEL_MESSAGE
)
1451 return "\033[1;32m";
1452 else if (log_level
& G_LOG_LEVEL_INFO
)
1453 return "\033[1;32m";
1454 else if (log_level
& G_LOG_LEVEL_DEBUG
)
1455 return "\033[1;32m";
1457 /* No color for custom log levels. */
1461 static const gchar
*
1462 color_reset (gboolean use_color
)
1464 /* we may not call _any_ GLib functions here */
1474 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1475 * so we need to check the name of the pipe if _isatty (fd) == 0
1479 win32_is_pipe_tty (int fd
)
1481 gboolean result
= FALSE
;
1484 FILE_NAME_INFO
*info
= NULL
;
1485 gint info_size
= sizeof (FILE_NAME_INFO
) + sizeof (WCHAR
) * MAX_PATH
;
1486 wchar_t *name
= NULL
;
1489 /* XXX: Remove once XP support really dropped */
1490 #if _WIN32_WINNT < 0x0600
1491 HANDLE h_kerneldll
= NULL
;
1492 fGetFileInformationByHandleEx
*GetFileInformationByHandleEx
;
1495 h_fd
= (HANDLE
) _get_osfhandle (fd
);
1497 if (h_fd
== INVALID_HANDLE_VALUE
|| GetFileType (h_fd
) != FILE_TYPE_PIPE
)
1500 /* The following check is available on Vista or later, so on XP, no color support */
1501 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1503 /* XXX: Remove once XP support really dropped */
1504 #if _WIN32_WINNT < 0x0600
1505 h_kerneldll
= LoadLibraryW (L
"kernel32.dll");
1507 if (h_kerneldll
== NULL
)
1510 GetFileInformationByHandleEx
=
1511 (fGetFileInformationByHandleEx
*) GetProcAddress (h_kerneldll
, "GetFileInformationByHandleEx");
1513 if (GetFileInformationByHandleEx
== NULL
)
1517 info
= g_try_malloc (info_size
);
1520 !GetFileInformationByHandleEx (h_fd
, FileNameInfo
, info
, info_size
))
1523 info
->FileName
[info
->FileNameLength
/ sizeof (WCHAR
)] = L
'\0';
1524 name
= info
->FileName
;
1526 length
= wcslen (L
"\\cygwin-");
1527 if (wcsncmp (name
, L
"\\cygwin-", length
))
1529 length
= wcslen (L
"\\msys-");
1530 if (wcsncmp (name
, L
"\\msys-", length
))
1535 length
= wcsspn (name
, L
"0123456789abcdefABCDEF");
1540 length
= wcslen (L
"-pty");
1541 if (wcsncmp (name
, L
"-pty", length
))
1545 length
= wcsspn (name
, L
"0123456789");
1550 length
= wcslen (L
"-to-master");
1551 if (wcsncmp (name
, L
"-to-master", length
))
1553 length
= wcslen (L
"-from-master");
1554 if (wcsncmp (name
, L
"-from-master", length
))
1564 /* XXX: Remove once XP support really dropped */
1565 #if _WIN32_WINNT < 0x0600
1566 if (h_kerneldll
!= NULL
)
1567 FreeLibrary (h_kerneldll
);
1574 #pragma GCC diagnostic push
1575 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1579 * @log_domain: log domain, usually %G_LOG_DOMAIN
1580 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1582 * @...: key-value pairs of structured data to add to the log entry, followed
1583 * by the key "MESSAGE", followed by a printf()-style message format,
1584 * followed by parameters to insert in the format string
1586 * Log a message with structured data. The message will be passed through to
1587 * the log writer set by the application using g_log_set_writer_func(). If the
1588 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1589 * be aborted at the end of this function.
1591 * The structured data is provided as key–value pairs, where keys are UTF-8
1592 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1593 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1594 * structured data, use g_log_structured_array(). The keys for structured data
1595 * should follow the [systemd journal
1596 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1597 * specification. It is suggested that custom keys are namespaced according to
1598 * the code which sets them. For example, custom keys from GLib all have a
1601 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1602 * be converted into a
1603 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1604 * field. The format string will have its placeholders substituted for the provided
1605 * values and be converted into a
1606 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1609 * Other fields you may commonly want to pass into this function:
1611 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1612 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1613 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1614 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1615 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1617 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1618 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1619 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1623 * |[<!-- language="C" -->
1624 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1625 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1626 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1627 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1628 * some_pointer, some_integer);
1631 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1632 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1633 * If adding a `MESSAGE_ID`, consider shipping a [message
1634 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1637 * To pass a user data pointer to the log writer function which is specific to
1638 * this logging call, you must use g_log_structured_array() and pass the pointer
1639 * as a field with #GLogField.length set to zero, otherwise it will be
1640 * interpreted as a string.
1643 * |[<!-- language="C" -->
1644 * const GLogField fields[] = {
1645 * { "MESSAGE", "This is a debug message.", -1 },
1646 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1647 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1648 * { "MY_APPLICATION_STATE", state_object, 0 },
1650 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1653 * Note also that, even if no other structured fields are specified, there
1654 * must always be a "MESSAGE" key before the format string. The "MESSAGE"-format
1655 * pair has to be the last of the key-value pairs, and "MESSAGE" is the only
1656 * field for which printf()-style formatting is supported.
1658 * The default writer function for `stdout` and `stderr` will automatically
1659 * append a new-line character after the message, so you should not add one
1660 * manually to the format string.
1665 g_log_structured (const gchar
*log_domain
,
1666 GLogLevelFlags log_level
,
1670 gchar buffer
[1025], *message_allocated
= NULL
;
1672 const gchar
*message
;
1675 GLogField stack_fields
[16];
1676 GLogField
*fields
= stack_fields
;
1677 GLogField
*fields_allocated
= NULL
;
1678 GArray
*array
= NULL
;
1680 va_start (args
, log_level
);
1682 /* MESSAGE and PRIORITY are a given */
1688 for (p
= va_arg (args
, gchar
*), i
= n_fields
;
1689 strcmp (p
, "MESSAGE") != 0;
1690 p
= va_arg (args
, gchar
*), i
++)
1693 const gchar
*key
= p
;
1694 gconstpointer value
= va_arg (args
, gpointer
);
1697 field
.value
= value
;
1701 stack_fields
[i
] = field
;
1704 /* Don't allow dynamic allocation, since we're likely
1705 * in an out-of-memory situation. For lack of a better solution,
1706 * just ignore further key-value pairs.
1708 if (log_level
& G_LOG_FLAG_RECURSION
)
1713 array
= g_array_sized_new (FALSE
, FALSE
, sizeof (GLogField
), 32);
1714 g_array_append_vals (array
, stack_fields
, 16);
1717 g_array_append_val (array
, field
);
1724 fields
= fields_allocated
= (GLogField
*) g_array_free (array
, FALSE
);
1726 format
= va_arg (args
, gchar
*);
1728 if (log_level
& G_LOG_FLAG_RECURSION
)
1730 /* we use a stack buffer of fixed size, since we're likely
1731 * in an out-of-memory situation
1733 gsize size G_GNUC_UNUSED
;
1735 size
= _g_vsnprintf (buffer
, sizeof (buffer
), format
, args
);
1740 message
= message_allocated
= g_strdup_vprintf (format
, args
);
1743 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1744 fields
[0].key
= "MESSAGE";
1745 fields
[0].value
= message
;
1746 fields
[0].length
= -1;
1748 fields
[1].key
= "PRIORITY";
1749 fields
[1].value
= log_level_to_priority (log_level
);
1750 fields
[1].length
= -1;
1754 fields
[2].key
= "GLIB_DOMAIN";
1755 fields
[2].value
= log_domain
;
1756 fields
[2].length
= -1;
1760 g_log_structured_array (log_level
, fields
, n_fields
);
1762 g_free (fields_allocated
);
1763 g_free (message_allocated
);
1770 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1771 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1773 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1774 * containing the key-value pairs of message data.
1776 * Log a message with structured data, accepting the data within a #GVariant. This
1777 * version is especially useful for use in other languages, via introspection.
1779 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1780 * contain the text shown to the user.
1782 * The values in the @fields dictionary are likely to be of type String
1783 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1784 * supported. In this case the message is handled as binary and will be forwarded
1785 * to the log writer as such. The size of the array should not be higher than
1786 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1787 * g_variant_print() will be used to convert the value into a string.
1789 * For more details on its usage and about the parameters, see g_log_structured().
1795 g_log_variant (const gchar
*log_domain
,
1796 GLogLevelFlags log_level
,
1802 GArray
*fields_array
;
1804 GSList
*values_list
, *print_list
;
1806 g_return_if_fail (g_variant_is_of_type (fields
, G_VARIANT_TYPE_VARDICT
));
1808 values_list
= print_list
= NULL
;
1809 fields_array
= g_array_new (FALSE
, FALSE
, sizeof (GLogField
));
1811 field
.key
= "PRIORITY";
1812 field
.value
= log_level_to_priority (log_level
);
1814 g_array_append_val (fields_array
, field
);
1818 field
.key
= "GLIB_DOMAIN";
1819 field
.value
= log_domain
;
1821 g_array_append_val (fields_array
, field
);
1824 g_variant_iter_init (&iter
, fields
);
1825 while (g_variant_iter_next (&iter
, "{&sv}", &key
, &value
))
1827 gboolean defer_unref
= TRUE
;
1832 if (g_variant_is_of_type (value
, G_VARIANT_TYPE_STRING
))
1834 field
.value
= g_variant_get_string (value
, NULL
);
1836 else if (g_variant_is_of_type (value
, G_VARIANT_TYPE_BYTESTRING
))
1839 field
.value
= g_variant_get_fixed_array (value
, &s
, sizeof (guchar
));
1840 if (G_LIKELY (s
<= G_MAXSSIZE
))
1847 "Byte array too large (%" G_GSIZE_FORMAT
" bytes)"
1848 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE
)
1850 field
.length
= G_MAXSSIZE
;
1855 char *s
= g_variant_print (value
, FALSE
);
1857 print_list
= g_slist_prepend (print_list
, s
);
1858 defer_unref
= FALSE
;
1861 g_array_append_val (fields_array
, field
);
1863 if (G_LIKELY (defer_unref
))
1864 values_list
= g_slist_prepend (values_list
, value
);
1866 g_variant_unref (value
);
1870 g_log_structured_array (log_level
, (GLogField
*) fields_array
->data
, fields_array
->len
);
1872 g_array_free (fields_array
, TRUE
);
1873 g_slist_free_full (values_list
, (GDestroyNotify
) g_variant_unref
);
1874 g_slist_free_full (print_list
, g_free
);
1878 #pragma GCC diagnostic pop
1880 static GLogWriterOutput
_g_log_writer_fallback (GLogLevelFlags log_level
,
1881 const GLogField
*fields
,
1883 gpointer user_data
);
1886 * g_log_structured_array:
1887 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1889 * @fields: (array length=n_fields): key–value pairs of structured data to add
1890 * to the log message
1891 * @n_fields: number of elements in the @fields array
1893 * Log a message with structured data. The message will be passed through to the
1894 * log writer set by the application using g_log_set_writer_func(). If the
1895 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1896 * be aborted at the end of this function.
1898 * See g_log_structured() for more documentation.
1900 * This assumes that @log_level is already present in @fields (typically as the
1901 * `PRIORITY` field).
1906 g_log_structured_array (GLogLevelFlags log_level
,
1907 const GLogField
*fields
,
1910 GLogWriterFunc writer_func
;
1911 gpointer writer_user_data
;
1918 /* Check for recursion and look up the writer function. */
1919 depth
= GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth
));
1920 recursion
= (depth
> 0);
1922 g_mutex_lock (&g_messages_lock
);
1924 writer_func
= recursion
? _g_log_writer_fallback
: log_writer_func
;
1925 writer_user_data
= log_writer_user_data
;
1927 g_mutex_unlock (&g_messages_lock
);
1929 /* Write the log entry. */
1930 g_private_set (&g_log_structured_depth
, GUINT_TO_POINTER (++depth
));
1932 g_assert (writer_func
!= NULL
);
1933 writer_func (log_level
, fields
, n_fields
, writer_user_data
);
1935 g_private_set (&g_log_structured_depth
, GUINT_TO_POINTER (--depth
));
1937 /* Abort if the message was fatal. */
1938 if (log_level
& G_LOG_FATAL_MASK
)
1939 _g_log_abort (!(log_level
& G_LOG_FLAG_RECURSION
));
1943 * g_log_set_writer_func:
1944 * @func: log writer function, which must not be %NULL
1945 * @user_data: (closure func): user data to pass to @func
1946 * @user_data_free: (destroy func): function to free @user_data once it’s
1947 * finished with, if non-%NULL
1949 * Set a writer function which will be called to format and write out each log
1950 * message. Each program should set a writer function, or the default writer
1951 * (g_log_writer_default()) will be used.
1953 * Libraries **must not** call this function — only programs are allowed to
1954 * install a writer function, as there must be a single, central point where
1955 * log messages are formatted and outputted.
1957 * There can only be one writer function. It is an error to set more than one.
1962 g_log_set_writer_func (GLogWriterFunc func
,
1964 GDestroyNotify user_data_free
)
1966 g_return_if_fail (func
!= NULL
);
1968 g_mutex_lock (&g_messages_lock
);
1969 log_writer_func
= func
;
1970 log_writer_user_data
= user_data
;
1971 log_writer_user_data_free
= user_data_free
;
1972 g_mutex_unlock (&g_messages_lock
);
1976 * g_log_writer_supports_color:
1977 * @output_fd: output file descriptor to check
1979 * Check whether the given @output_fd file descriptor supports ANSI color
1980 * escape sequences. If so, they can safely be used when formatting log
1983 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
1987 g_log_writer_supports_color (gint output_fd
)
1990 gboolean result
= FALSE
;
1992 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
1993 _invalid_parameter_handler oldHandler
, newHandler
;
1994 int prev_report_mode
= 0;
1999 g_return_val_if_fail (output_fd
>= 0, FALSE
);
2001 /* FIXME: This check could easily be expanded in future to be more robust
2002 * against different types of terminal, which still vary in their color
2003 * support. cmd.exe on Windows, for example, supports ANSI colors only
2004 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2005 * The Windows 10 color support is supported on:
2006 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2007 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2009 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2010 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2012 * On UNIX systems, we probably want to use the functions from terminfo to
2013 * work out whether colors are supported.
2016 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2017 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2018 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2019 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2023 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2024 /* Set up our empty invalid parameter handler, for isatty(),
2025 * in case of bad fd's passed in for isatty(), so that
2026 * msvcrt80.dll+ won't abort the program
2028 newHandler
= myInvalidParameterHandler
;
2029 oldHandler
= _set_invalid_parameter_handler (newHandler
);
2031 /* Disable the message box for assertions. */
2032 prev_report_mode
= _CrtSetReportMode(_CRT_ASSERT
, 0);
2035 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY
))
2040 if (_isatty (output_fd
))
2042 h_output
= (HANDLE
) _get_osfhandle (output_fd
);
2044 if (!GetConsoleMode (h_output
, &dw_mode
))
2045 goto reset_invalid_param_handler
;
2047 if (dw_mode
& ENABLE_VIRTUAL_TERMINAL_PROCESSING
)
2050 if (!SetConsoleMode (h_output
, dw_mode
| ENABLE_VIRTUAL_TERMINAL_PROCESSING
))
2051 goto reset_invalid_param_handler
;
2057 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2058 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2059 * (bug 775468), on standard Windows consoles, such as cmd.exe
2062 result
= win32_is_pipe_tty (output_fd
);
2064 reset_invalid_param_handler
:
2065 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2066 _CrtSetReportMode(_CRT_ASSERT
, prev_report_mode
);
2067 _set_invalid_parameter_handler (oldHandler
);
2072 return isatty (output_fd
);
2076 #if defined(__linux__) && !defined(__BIONIC__)
2077 static int journal_fd
= -1;
2079 #ifndef SOCK_CLOEXEC
2080 #define SOCK_CLOEXEC 0
2082 #define HAVE_SOCK_CLOEXEC 1
2088 if ((journal_fd
= socket (AF_UNIX
, SOCK_DGRAM
| SOCK_CLOEXEC
, 0)) < 0)
2091 #ifndef HAVE_SOCK_CLOEXEC
2092 if (fcntl (journal_fd
, F_SETFD
, FD_CLOEXEC
) < 0)
2102 * g_log_writer_is_journald:
2103 * @output_fd: output file descriptor to check
2105 * Check whether the given @output_fd file descriptor is a connection to the
2106 * systemd journal, or something else (like a log file or `stdout` or
2109 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2113 g_log_writer_is_journald (gint output_fd
)
2115 #if defined(__linux__) && !defined(__BIONIC__)
2116 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2117 * journal. See: https://github.com/systemd/systemd/issues/2473
2119 static gsize initialized
;
2120 static gboolean fd_is_journal
= FALSE
;
2122 g_return_val_if_fail (output_fd
>= 0, FALSE
);
2124 if (g_once_init_enter (&initialized
))
2126 struct sockaddr_storage addr
;
2127 socklen_t addr_len
= sizeof(addr
);
2128 int err
= getpeername (output_fd
, (struct sockaddr
*) &addr
, &addr_len
);
2129 if (err
== 0 && addr
.ss_family
== AF_UNIX
)
2130 fd_is_journal
= g_str_has_prefix (((struct sockaddr_un
*)&addr
)->sun_path
,
2131 "/run/systemd/journal/");
2133 g_once_init_leave (&initialized
, TRUE
);
2136 return fd_is_journal
;
2142 static void escape_string (GString
*string
);
2145 * g_log_writer_format_fields:
2146 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2148 * @fields: (array length=n_fields): key–value pairs of structured data forming
2150 * @n_fields: number of elements in the @fields array
2151 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2152 * message, %FALSE to not
2154 * Format a structured log message as a string suitable for outputting to the
2155 * terminal (or elsewhere). This will include the values of all fields it knows
2156 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2157 * documentation for g_log_structured()). It does not include values from
2160 * The returned string does **not** have a trailing new-line character. It is
2161 * encoded in the character set of the current locale, which is not necessarily
2164 * Returns: (transfer full): string containing the formatted log message, in
2165 * the character set of the current locale
2169 g_log_writer_format_fields (GLogLevelFlags log_level
,
2170 const GLogField
*fields
,
2175 const gchar
*message
= NULL
;
2176 const gchar
*log_domain
= NULL
;
2177 gchar level_prefix
[STRING_BUFFER_SIZE
];
2180 /* Extract some common fields. */
2181 for (i
= 0; (message
== NULL
|| log_domain
== NULL
) && i
< n_fields
; i
++)
2183 const GLogField
*field
= &fields
[i
];
2185 if (g_strcmp0 (field
->key
, "MESSAGE") == 0)
2186 message
= field
->value
;
2187 else if (g_strcmp0 (field
->key
, "GLIB_DOMAIN") == 0)
2188 log_domain
= field
->value
;
2191 /* Format things. */
2192 mklevel_prefix (level_prefix
, log_level
, use_color
);
2194 gstring
= g_string_new (NULL
);
2195 if (log_level
& ALERT_LEVELS
)
2196 g_string_append (gstring
, "\n");
2198 g_string_append (gstring
, "** ");
2200 if ((g_log_msg_prefix
& (log_level
& G_LOG_LEVEL_MASK
)) ==
2201 (log_level
& G_LOG_LEVEL_MASK
))
2203 const gchar
*prg_name
= g_get_prgname ();
2204 gulong pid
= getpid ();
2206 if (prg_name
== NULL
)
2207 g_string_append_printf (gstring
, "(process:%lu): ", pid
);
2209 g_string_append_printf (gstring
, "(%s:%lu): ", prg_name
, pid
);
2212 if (log_domain
!= NULL
)
2214 g_string_append (gstring
, log_domain
);
2215 g_string_append_c (gstring
, '-');
2217 g_string_append (gstring
, level_prefix
);
2219 g_string_append (gstring
, ": ");
2220 if (message
== NULL
)
2222 g_string_append (gstring
, "(NULL) message");
2227 const gchar
*charset
;
2229 msg
= g_string_new (message
);
2230 escape_string (msg
);
2232 if (g_get_charset (&charset
))
2234 /* charset is UTF-8 already */
2235 g_string_append (gstring
, msg
->str
);
2239 gchar
*lstring
= strdup_convert (msg
->str
, charset
);
2240 g_string_append (gstring
, lstring
);
2244 g_string_free (msg
, TRUE
);
2247 return g_string_free (gstring
, FALSE
);
2250 #if defined(__linux__) && !defined(__BIONIC__)
2252 journal_sendv (struct iovec
*iov
,
2257 struct sockaddr_un sa
;
2259 struct cmsghdr cmsghdr
;
2260 guint8 buf
[CMSG_SPACE(sizeof(int))];
2262 struct cmsghdr
*cmsg
;
2263 char path
[] = "/dev/shm/journal.XXXXXX";
2271 memset (&sa
, 0, sizeof (sa
));
2272 sa
.sun_family
= AF_UNIX
;
2273 if (g_strlcpy (sa
.sun_path
, "/run/systemd/journal/socket", sizeof (sa
.sun_path
)) >= sizeof (sa
.sun_path
))
2276 memset (&mh
, 0, sizeof (mh
));
2278 mh
.msg_namelen
= offsetof (struct sockaddr_un
, sun_path
) + strlen (sa
.sun_path
);
2280 mh
.msg_iovlen
= iovlen
;
2283 if (sendmsg (journal_fd
, &mh
, MSG_NOSIGNAL
) >= 0)
2289 if (errno
!= EMSGSIZE
&& errno
!= ENOBUFS
)
2292 /* Message was too large, so dump to temporary file
2293 * and pass an FD to the journal
2295 if ((buf_fd
= mkostemp (path
, O_CLOEXEC
|O_RDWR
)) < 0)
2298 if (unlink (path
) < 0)
2304 if (writev (buf_fd
, iov
, iovlen
) < 0)
2313 memset (&control
, 0, sizeof (control
));
2314 mh
.msg_control
= &control
;
2315 mh
.msg_controllen
= sizeof (control
);
2317 cmsg
= CMSG_FIRSTHDR (&mh
);
2318 cmsg
->cmsg_level
= SOL_SOCKET
;
2319 cmsg
->cmsg_type
= SCM_RIGHTS
;
2320 cmsg
->cmsg_len
= CMSG_LEN (sizeof (int));
2321 memcpy (CMSG_DATA (cmsg
), &buf_fd
, sizeof (int));
2323 mh
.msg_controllen
= cmsg
->cmsg_len
;
2326 if (sendmsg (journal_fd
, &mh
, MSG_NOSIGNAL
) >= 0)
2337 * g_log_writer_journald:
2338 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2340 * @fields: (array length=n_fields): key–value pairs of structured data forming
2342 * @n_fields: number of elements in the @fields array
2343 * @user_data: user data passed to g_log_set_writer_func()
2345 * Format a structured log message and send it to the systemd journal as a set
2346 * of key–value pairs. All fields are sent to the journal, but if a field has
2347 * length zero (indicating program-specific data) then only its key will be
2350 * This is suitable for use as a #GLogWriterFunc.
2352 * If GLib has been compiled without systemd support, this function is still
2353 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2355 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2359 g_log_writer_journald (GLogLevelFlags log_level
,
2360 const GLogField
*fields
,
2364 #if defined(__linux__) && !defined(__BIONIC__)
2365 const char equals
= '=';
2366 const char newline
= '\n';
2368 struct iovec
*iov
, *v
;
2372 g_return_val_if_fail (fields
!= NULL
, G_LOG_WRITER_UNHANDLED
);
2373 g_return_val_if_fail (n_fields
> 0, G_LOG_WRITER_UNHANDLED
);
2375 /* According to systemd.journal-fields(7), the journal allows fields in any
2376 * format (including arbitrary binary), but expects text fields to be UTF-8.
2377 * This is great, because we require input strings to be in UTF-8, so no
2378 * conversion is necessary and we don’t need to care about the current
2379 * locale’s character set.
2382 iov
= g_alloca (sizeof (struct iovec
) * 5 * n_fields
);
2383 buf
= g_alloca (32 * n_fields
);
2387 for (i
= 0; i
< n_fields
; i
++)
2392 if (fields
[i
].length
< 0)
2394 length
= strlen (fields
[i
].value
);
2395 binary
= strchr (fields
[i
].value
, '\n') != NULL
;
2399 length
= fields
[i
].length
;
2407 v
[0].iov_base
= (gpointer
)fields
[i
].key
;
2408 v
[0].iov_len
= strlen (fields
[i
].key
);
2410 v
[1].iov_base
= (gpointer
)&newline
;
2413 nstr
= GUINT64_TO_LE(length
);
2414 memcpy (&buf
[k
], &nstr
, sizeof (nstr
));
2416 v
[2].iov_base
= &buf
[k
];
2417 v
[2].iov_len
= sizeof (nstr
);
2423 v
[0].iov_base
= (gpointer
)fields
[i
].key
;
2424 v
[0].iov_len
= strlen (fields
[i
].key
);
2426 v
[1].iov_base
= (gpointer
)&equals
;
2431 v
[0].iov_base
= (gpointer
)fields
[i
].value
;
2432 v
[0].iov_len
= length
;
2434 v
[1].iov_base
= (gpointer
)&newline
;
2439 retval
= journal_sendv (iov
, v
- iov
);
2441 return retval
== 0 ? G_LOG_WRITER_HANDLED
: G_LOG_WRITER_UNHANDLED
;
2443 return G_LOG_WRITER_UNHANDLED
;
2448 * g_log_writer_standard_streams:
2449 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2451 * @fields: (array length=n_fields): key–value pairs of structured data forming
2453 * @n_fields: number of elements in the @fields array
2454 * @user_data: user data passed to g_log_set_writer_func()
2456 * Format a structured log message and print it to either `stdout` or `stderr`,
2457 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2458 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2459 * which are understood by this function are included in the formatted string
2462 * If the output stream supports ANSI color escape sequences, they will be used
2465 * A trailing new-line character is added to the log message when it is printed.
2467 * This is suitable for use as a #GLogWriterFunc.
2469 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2473 g_log_writer_standard_streams (GLogLevelFlags log_level
,
2474 const GLogField
*fields
,
2479 gchar
*out
= NULL
; /* in the current locale’s character set */
2481 g_return_val_if_fail (fields
!= NULL
, G_LOG_WRITER_UNHANDLED
);
2482 g_return_val_if_fail (n_fields
> 0, G_LOG_WRITER_UNHANDLED
);
2484 stream
= log_level_to_file (log_level
);
2485 if (!stream
|| fileno (stream
) < 0)
2486 return G_LOG_WRITER_UNHANDLED
;
2488 out
= g_log_writer_format_fields (log_level
, fields
, n_fields
,
2489 g_log_writer_supports_color (fileno (stream
)));
2490 _g_fprintf (stream
, "%s\n", out
);
2493 return G_LOG_WRITER_HANDLED
;
2496 /* The old g_log() API is implemented in terms of the new structured log API.
2497 * However, some of the checks do not line up between the two APIs: the
2498 * structured API only handles fatalness of messages for log levels; the old API
2499 * handles it per-domain as well. Consequently, we need to disable fatalness
2500 * handling in the structured log API when called from the old g_log() API.
2502 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2503 * the first field to g_log_structured_array(), if that is the case.
2506 log_is_old_api (const GLogField
*fields
,
2509 return (n_fields
>= 1 &&
2510 g_strcmp0 (fields
[0].key
, "GLIB_OLD_LOG_API") == 0 &&
2511 g_strcmp0 (fields
[0].value
, "1") == 0);
2515 * g_log_writer_default:
2516 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2518 * @fields: (array length=n_fields): key–value pairs of structured data forming
2520 * @n_fields: number of elements in the @fields array
2521 * @user_data: user data passed to g_log_set_writer_func()
2523 * Format a structured log message and output it to the default log destination
2524 * for the platform. On Linux, this is typically the systemd journal, falling
2525 * back to `stdout` or `stderr` if running from the terminal or if output is
2526 * being redirected to a file.
2528 * Support for other platform-specific logging mechanisms may be added in
2529 * future. Distributors of GLib may modify this function to impose their own
2530 * (documented) platform-specific log writing policies.
2532 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2533 * if no other is set using g_log_set_writer_func().
2535 * As with g_log_default_handler(), this function drops debug and informational
2536 * messages unless their log domain (or `all`) is listed in the space-separated
2537 * `G_MESSAGES_DEBUG` environment variable.
2539 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2543 g_log_writer_default (GLogLevelFlags log_level
,
2544 const GLogField
*fields
,
2548 g_return_val_if_fail (fields
!= NULL
, G_LOG_WRITER_UNHANDLED
);
2549 g_return_val_if_fail (n_fields
> 0, G_LOG_WRITER_UNHANDLED
);
2551 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2552 if (!(log_level
& DEFAULT_LEVELS
) && !(log_level
>> G_LOG_LEVEL_USER_SHIFT
))
2554 const gchar
*domains
, *log_domain
= NULL
;
2557 domains
= g_getenv ("G_MESSAGES_DEBUG");
2559 if ((log_level
& INFO_LEVELS
) == 0 ||
2561 return G_LOG_WRITER_HANDLED
;
2563 for (i
= 0; i
< n_fields
; i
++)
2565 if (g_strcmp0 (fields
[i
].key
, "GLIB_DOMAIN") == 0)
2567 log_domain
= fields
[i
].value
;
2572 if (strcmp (domains
, "all") != 0 &&
2573 (log_domain
== NULL
|| !strstr (domains
, log_domain
)))
2574 return G_LOG_WRITER_HANDLED
;
2577 /* Mark messages as fatal if they have a level set in
2578 * g_log_set_always_fatal().
2580 if ((log_level
& g_log_always_fatal
) && !log_is_old_api (fields
, n_fields
))
2581 log_level
|= G_LOG_FLAG_FATAL
;
2583 /* Try logging to the systemd journal as first choice. */
2584 if (g_log_writer_is_journald (fileno (stderr
)) &&
2585 g_log_writer_journald (log_level
, fields
, n_fields
, user_data
) ==
2586 G_LOG_WRITER_HANDLED
)
2589 /* FIXME: Add support for the Windows log. */
2591 if (g_log_writer_standard_streams (log_level
, fields
, n_fields
, user_data
) ==
2592 G_LOG_WRITER_HANDLED
)
2595 return G_LOG_WRITER_UNHANDLED
;
2598 /* Abort if the message was fatal. */
2599 if (log_level
& G_LOG_FLAG_FATAL
)
2602 if (!g_test_initialized ())
2604 gchar
*locale_msg
= NULL
;
2606 locale_msg
= g_locale_from_utf8 (fatal_msg_buf
, -1, NULL
, NULL
, NULL
);
2607 MessageBox (NULL
, locale_msg
, NULL
,
2608 MB_ICONERROR
| MB_SETFOREGROUND
);
2609 g_free (locale_msg
);
2611 #endif /* !G_OS_WIN32 */
2613 _g_log_abort (!(log_level
& G_LOG_FLAG_RECURSION
));
2616 return G_LOG_WRITER_HANDLED
;
2619 static GLogWriterOutput
2620 _g_log_writer_fallback (GLogLevelFlags log_level
,
2621 const GLogField
*fields
,
2628 /* we cannot call _any_ GLib functions in this fallback handler,
2629 * which is why we skip UTF-8 conversion, etc.
2630 * since we either recursed or ran out of memory, we're in a pretty
2631 * pathologic situation anyways, what we can do is giving the
2632 * the process ID unconditionally however.
2635 stream
= log_level_to_file (log_level
);
2637 for (i
= 0; i
< n_fields
; i
++)
2639 const GLogField
*field
= &fields
[i
];
2641 /* Only print fields we definitely recognise, otherwise we could end up
2642 * printing a random non-string pointer provided by the user to be
2643 * interpreted by their writer function.
2645 if (strcmp (field
->key
, "MESSAGE") != 0 &&
2646 strcmp (field
->key
, "MESSAGE_ID") != 0 &&
2647 strcmp (field
->key
, "PRIORITY") != 0 &&
2648 strcmp (field
->key
, "CODE_FILE") != 0 &&
2649 strcmp (field
->key
, "CODE_LINE") != 0 &&
2650 strcmp (field
->key
, "CODE_FUNC") != 0 &&
2651 strcmp (field
->key
, "ERRNO") != 0 &&
2652 strcmp (field
->key
, "SYSLOG_FACILITY") != 0 &&
2653 strcmp (field
->key
, "SYSLOG_IDENTIFIER") != 0 &&
2654 strcmp (field
->key
, "SYSLOG_PID") != 0 &&
2655 strcmp (field
->key
, "GLIB_DOMAIN") != 0)
2658 write_string (stream
, field
->key
);
2659 write_string (stream
, "=");
2660 write_string_sized (stream
, field
->value
, field
->length
);
2665 gchar pid_string
[FORMAT_UNSIGNED_BUFSIZE
];
2667 format_unsigned (pid_string
, getpid (), 10);
2668 write_string (stream
, "_PID=");
2669 write_string (stream
, pid_string
);
2673 return G_LOG_WRITER_HANDLED
;
2677 * g_return_if_fail_warning: (skip)
2678 * @log_domain: (nullable):
2680 * @expression: (nullable):
2683 g_return_if_fail_warning (const char *log_domain
,
2684 const char *pretty_function
,
2685 const char *expression
)
2688 G_LOG_LEVEL_CRITICAL
,
2689 "%s: assertion '%s' failed",
2695 * g_warn_message: (skip)
2696 * @domain: (nullable):
2700 * @warnexpr: (nullable):
2703 g_warn_message (const char *domain
,
2707 const char *warnexpr
)
2710 g_snprintf (lstr
, 32, "%d", line
);
2712 s
= g_strconcat ("(", file
, ":", lstr
, "):",
2713 func
, func
[0] ? ":" : "",
2714 " runtime check failed: (", warnexpr
, ")", NULL
);
2716 s
= g_strconcat ("(", file
, ":", lstr
, "):",
2717 func
, func
[0] ? ":" : "",
2718 " ", "code should not be reached", NULL
);
2719 g_log (domain
, G_LOG_LEVEL_WARNING
, "%s", s
);
2724 g_assert_warning (const char *log_domain
,
2727 const char *pretty_function
,
2728 const char *expression
)
2733 "file %s: line %d (%s): assertion failed: (%s)",
2741 "file %s: line %d (%s): should not be reached",
2745 _g_log_abort (FALSE
);
2750 * g_test_expect_message:
2751 * @log_domain: (nullable): the log domain of the message
2752 * @log_level: the log level of the message
2753 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2755 * Indicates that a message with the given @log_domain and @log_level,
2756 * with text matching @pattern, is expected to be logged. When this
2757 * message is logged, it will not be printed, and the test case will
2760 * This API may only be used with the old logging API (g_log() without
2761 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2762 * API. See [Testing for Messages][testing-for-messages].
2764 * Use g_test_assert_expected_messages() to assert that all
2765 * previously-expected messages have been seen and suppressed.
2767 * You can call this multiple times in a row, if multiple messages are
2768 * expected as a result of a single call. (The messages must appear in
2769 * the same order as the calls to g_test_expect_message().)
2773 * |[<!-- language="C" -->
2774 * // g_main_context_push_thread_default() should fail if the
2775 * // context is already owned by another thread.
2776 * g_test_expect_message (G_LOG_DOMAIN,
2777 * G_LOG_LEVEL_CRITICAL,
2778 * "assertion*acquired_context*failed");
2779 * g_main_context_push_thread_default (bad_context);
2780 * g_test_assert_expected_messages ();
2783 * Note that you cannot use this to test g_error() messages, since
2784 * g_error() intentionally never returns even if the program doesn't
2785 * abort; use g_test_trap_subprocess() in this case.
2787 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2788 * expected via g_test_expect_message() then they will be ignored.
2793 g_test_expect_message (const gchar
*log_domain
,
2794 GLogLevelFlags log_level
,
2795 const gchar
*pattern
)
2797 GTestExpectedMessage
*expected
;
2799 g_return_if_fail (log_level
!= 0);
2800 g_return_if_fail (pattern
!= NULL
);
2801 g_return_if_fail (~log_level
& G_LOG_LEVEL_ERROR
);
2803 expected
= g_new (GTestExpectedMessage
, 1);
2804 expected
->log_domain
= g_strdup (log_domain
);
2805 expected
->log_level
= log_level
;
2806 expected
->pattern
= g_strdup (pattern
);
2808 expected_messages
= g_slist_append (expected_messages
, expected
);
2812 g_test_assert_expected_messages_internal (const char *domain
,
2817 if (expected_messages
)
2819 GTestExpectedMessage
*expected
;
2820 gchar level_prefix
[STRING_BUFFER_SIZE
];
2823 expected
= expected_messages
->data
;
2825 mklevel_prefix (level_prefix
, expected
->log_level
, FALSE
);
2826 message
= g_strdup_printf ("Did not see expected message %s-%s: %s",
2827 expected
->log_domain
? expected
->log_domain
: "**",
2828 level_prefix
, expected
->pattern
);
2829 g_assertion_message (G_LOG_DOMAIN
, file
, line
, func
, message
);
2835 * g_test_assert_expected_messages:
2837 * Asserts that all messages previously indicated via
2838 * g_test_expect_message() have been seen and suppressed.
2840 * This API may only be used with the old logging API (g_log() without
2841 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2842 * API. See [Testing for Messages][testing-for-messages].
2844 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2845 * expected via g_test_expect_message() then they will be ignored.
2851 _g_log_fallback_handler (const gchar
*log_domain
,
2852 GLogLevelFlags log_level
,
2853 const gchar
*message
,
2854 gpointer unused_data
)
2856 gchar level_prefix
[STRING_BUFFER_SIZE
];
2858 gchar pid_string
[FORMAT_UNSIGNED_BUFSIZE
];
2862 /* we cannot call _any_ GLib functions in this fallback handler,
2863 * which is why we skip UTF-8 conversion, etc.
2864 * since we either recursed or ran out of memory, we're in a pretty
2865 * pathologic situation anyways, what we can do is giving the
2866 * the process ID unconditionally however.
2869 stream
= mklevel_prefix (level_prefix
, log_level
, FALSE
);
2871 message
= "(NULL) message";
2874 format_unsigned (pid_string
, getpid (), 10);
2878 write_string (stream
, "\n");
2880 write_string (stream
, "\n** ");
2883 write_string (stream
, "(process:");
2884 write_string (stream
, pid_string
);
2885 write_string (stream
, "): ");
2890 write_string (stream
, log_domain
);
2891 write_string (stream
, "-");
2893 write_string (stream
, level_prefix
);
2894 write_string (stream
, ": ");
2895 write_string (stream
, message
);
2899 escape_string (GString
*string
)
2901 const char *p
= string
->str
;
2904 while (p
< string
->str
+ string
->len
)
2908 wc
= g_utf8_get_char_validated (p
, -1);
2909 if (wc
== (gunichar
)-1 || wc
== (gunichar
)-2)
2914 pos
= p
- string
->str
;
2916 /* Emit invalid UTF-8 as hex escapes
2918 tmp
= g_strdup_printf ("\\x%02x", (guint
)(guchar
)*p
);
2919 g_string_erase (string
, pos
, 1);
2920 g_string_insert (string
, pos
, tmp
);
2922 p
= string
->str
+ (pos
+ 4); /* Skip over escape sequence */
2929 safe
= *(p
+ 1) == '\n';
2933 safe
= CHAR_IS_SAFE (wc
);
2941 pos
= p
- string
->str
;
2943 /* Largest char we escape is 0x0a, so we don't have to worry
2944 * about 8-digit \Uxxxxyyyy
2946 tmp
= g_strdup_printf ("\\u%04x", wc
);
2947 g_string_erase (string
, pos
, g_utf8_next_char (p
) - p
);
2948 g_string_insert (string
, pos
, tmp
);
2951 p
= string
->str
+ (pos
+ 6); /* Skip over escape sequence */
2954 p
= g_utf8_next_char (p
);
2959 * g_log_default_handler:
2960 * @log_domain: (nullable): the log domain of the message, or %NULL for the
2961 * default "" application domain
2962 * @log_level: the level of the message
2963 * @message: (nullable): the message
2964 * @unused_data: (nullable): data passed from g_log() which is unused
2966 * The default log handler set up by GLib; g_log_set_default_handler()
2967 * allows to install an alternate default log handler.
2968 * This is used if no log handler has been set for the particular log
2969 * domain and log level combination. It outputs the message to stderr
2970 * or stdout and if the log level is fatal it calls abort(). It automatically
2971 * prints a new-line character after the message, so one does not need to be
2972 * manually included in @message.
2974 * The behavior of this log handler can be influenced by a number of
2975 * environment variables:
2977 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
2978 * messages should be prefixed by the program name and PID of the
2981 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
2982 * which debug and informational messages are printed. By default
2983 * these messages are not printed.
2985 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
2986 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
2989 * This has no effect if structured logging is enabled; see
2990 * [Using Structured Logging][using-structured-logging].
2993 g_log_default_handler (const gchar
*log_domain
,
2994 GLogLevelFlags log_level
,
2995 const gchar
*message
,
2996 gpointer unused_data
)
2998 const gchar
*domains
;
2999 GLogField fields
[4];
3002 if ((log_level
& DEFAULT_LEVELS
) || (log_level
>> G_LOG_LEVEL_USER_SHIFT
))
3005 domains
= g_getenv ("G_MESSAGES_DEBUG");
3006 if (((log_level
& INFO_LEVELS
) == 0) ||
3008 (strcmp (domains
, "all") != 0 && (!log_domain
|| !strstr (domains
, log_domain
))))
3012 /* we can be called externally with recursion for whatever reason */
3013 if (log_level
& G_LOG_FLAG_RECURSION
)
3015 _g_log_fallback_handler (log_domain
, log_level
, message
, unused_data
);
3019 fields
[0].key
= "GLIB_OLD_LOG_API";
3020 fields
[0].value
= "1";
3021 fields
[0].length
= -1;
3024 fields
[1].key
= "MESSAGE";
3025 fields
[1].value
= message
;
3026 fields
[1].length
= -1;
3029 fields
[2].key
= "PRIORITY";
3030 fields
[2].value
= log_level_to_priority (log_level
);
3031 fields
[2].length
= -1;
3036 fields
[3].key
= "GLIB_DOMAIN";
3037 fields
[3].value
= log_domain
;
3038 fields
[3].length
= -1;
3042 /* Print out via the structured log API, but drop any fatal flags since we
3043 * have already handled them. The fatal handling in the structured logging
3044 * API is more coarse-grained than in the old g_log() API, so we don't want
3047 g_log_structured_array (log_level
& ~G_LOG_FLAG_FATAL
, fields
, n_fields
);
3051 * g_set_print_handler:
3052 * @func: the new print handler
3054 * Sets the print handler.
3056 * Any messages passed to g_print() will be output via
3057 * the new handler. The default handler simply outputs
3058 * the message to stdout. By providing your own handler
3059 * you can redirect the output, to a GTK+ widget or a
3060 * log file for example.
3062 * Returns: the old print handler
3065 g_set_print_handler (GPrintFunc func
)
3067 GPrintFunc old_print_func
;
3069 g_mutex_lock (&g_messages_lock
);
3070 old_print_func
= glib_print_func
;
3071 glib_print_func
= func
;
3072 g_mutex_unlock (&g_messages_lock
);
3074 return old_print_func
;
3079 * @format: the message format. See the printf() documentation
3080 * @...: the parameters to insert into the format string
3082 * Outputs a formatted message via the print handler.
3083 * The default print handler simply outputs the message to stdout, without
3084 * appending a trailing new-line character. Typically, @format should end with
3085 * its own new-line character.
3087 * g_print() should not be used from within libraries for debugging
3088 * messages, since it may be redirected by applications to special
3089 * purpose message windows or even files. Instead, libraries should
3090 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3091 * g_warning() and g_error().
3094 g_print (const gchar
*format
,
3099 GPrintFunc local_glib_print_func
;
3101 g_return_if_fail (format
!= NULL
);
3103 va_start (args
, format
);
3104 string
= g_strdup_vprintf (format
, args
);
3107 g_mutex_lock (&g_messages_lock
);
3108 local_glib_print_func
= glib_print_func
;
3109 g_mutex_unlock (&g_messages_lock
);
3111 if (local_glib_print_func
)
3112 local_glib_print_func (string
);
3115 const gchar
*charset
;
3117 if (g_get_charset (&charset
))
3118 fputs (string
, stdout
); /* charset is UTF-8 already */
3121 gchar
*lstring
= strdup_convert (string
, charset
);
3123 fputs (lstring
, stdout
);
3132 * g_set_printerr_handler:
3133 * @func: the new error message handler
3135 * Sets the handler for printing error messages.
3137 * Any messages passed to g_printerr() will be output via
3138 * the new handler. The default handler simply outputs the
3139 * message to stderr. By providing your own handler you can
3140 * redirect the output, to a GTK+ widget or a log file for
3143 * Returns: the old error message handler
3146 g_set_printerr_handler (GPrintFunc func
)
3148 GPrintFunc old_printerr_func
;
3150 g_mutex_lock (&g_messages_lock
);
3151 old_printerr_func
= glib_printerr_func
;
3152 glib_printerr_func
= func
;
3153 g_mutex_unlock (&g_messages_lock
);
3155 return old_printerr_func
;
3160 * @format: the message format. See the printf() documentation
3161 * @...: the parameters to insert into the format string
3163 * Outputs a formatted message via the error message handler.
3164 * The default handler simply outputs the message to stderr, without appending
3165 * a trailing new-line character. Typically, @format should end with its own
3166 * new-line character.
3168 * g_printerr() should not be used from within libraries.
3169 * Instead g_log() or g_log_structured() should be used, or the convenience
3170 * macros g_message(), g_warning() and g_error().
3173 g_printerr (const gchar
*format
,
3178 GPrintFunc local_glib_printerr_func
;
3180 g_return_if_fail (format
!= NULL
);
3182 va_start (args
, format
);
3183 string
= g_strdup_vprintf (format
, args
);
3186 g_mutex_lock (&g_messages_lock
);
3187 local_glib_printerr_func
= glib_printerr_func
;
3188 g_mutex_unlock (&g_messages_lock
);
3190 if (local_glib_printerr_func
)
3191 local_glib_printerr_func (string
);
3194 const gchar
*charset
;
3196 if (g_get_charset (&charset
))
3197 fputs (string
, stderr
); /* charset is UTF-8 already */
3200 gchar
*lstring
= strdup_convert (string
, charset
);
3202 fputs (lstring
, stderr
);
3211 * g_printf_string_upper_bound:
3212 * @format: the format string. See the printf() documentation
3213 * @args: the parameters to be inserted into the format string
3215 * Calculates the maximum space needed to store the output
3216 * of the sprintf() function.
3218 * Returns: the maximum space needed to store the formatted string
3221 g_printf_string_upper_bound (const gchar
*format
,
3225 return _g_vsnprintf (&c
, 1, format
, args
) + 1;