Merge branch 'macosx-remove-fixme' into 'master'
[glib.git] / glib / gmessages.c
blobeaca783876b9b61f5c1618cb74650c759dfa1b6c
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.1 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/.
26 * MT safe
29 /**
30 * SECTION:messages
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
51 * format.
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
89 * function.
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 ## {#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.
107 * ## Log Domains ## {#log-domains}
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 ## {#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
125 * `all`).
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
130 * projects.
132 * ## Testing for Messages ## {#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
138 * reasons:
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).
168 #include "config.h"
170 #include <stdlib.h>
171 #include <stdarg.h>
172 #include <stdio.h>
173 #include <string.h>
174 #include <signal.h>
175 #include <locale.h>
176 #include <errno.h>
178 #if defined(__linux__) && !defined(__BIONIC__)
179 #include <sys/types.h>
180 #include <sys/socket.h>
181 #include <sys/un.h>
182 #include <fcntl.h>
183 #include <sys/uio.h>
184 #endif
186 #include "glib-init.h"
187 #include "galloca.h"
188 #include "gbacktrace.h"
189 #include "gcharset.h"
190 #include "gconvert.h"
191 #include "genviron.h"
192 #include "gmain.h"
193 #include "gmem.h"
194 #include "gprintfint.h"
195 #include "gtestutils.h"
196 #include "gthread.h"
197 #include "gstrfuncs.h"
198 #include "gstring.h"
199 #include "gpattern.h"
201 #ifdef G_OS_UNIX
202 #include <unistd.h>
203 #endif
205 #ifdef G_OS_WIN32
206 #include <process.h> /* For getpid() */
207 #include <io.h>
208 # include <windows.h>
210 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
211 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
212 #endif
214 /* XXX: Remove once XP support really dropped */
215 #if _WIN32_WINNT < 0x0600
217 typedef enum _FILE_INFO_BY_HANDLE_CLASS
219 FileBasicInfo = 0,
220 FileStandardInfo = 1,
221 FileNameInfo = 2,
222 FileRenameInfo = 3,
223 FileDispositionInfo = 4,
224 FileAllocationInfo = 5,
225 FileEndOfFileInfo = 6,
226 FileStreamInfo = 7,
227 FileCompressionInfo = 8,
228 FileAttributeTagInfo = 9,
229 FileIdBothDirectoryInfo = 10,
230 FileIdBothDirectoryRestartInfo = 11,
231 FileIoPriorityHintInfo = 12,
232 FileRemoteProtocolInfo = 13,
233 FileFullDirectoryInfo = 14,
234 FileFullDirectoryRestartInfo = 15,
235 FileStorageInfo = 16,
236 FileAlignmentInfo = 17,
237 FileIdInfo = 18,
238 FileIdExtdDirectoryInfo = 19,
239 FileIdExtdDirectoryRestartInfo = 20,
240 MaximumFileInfoByHandlesClass
241 } FILE_INFO_BY_HANDLE_CLASS;
243 typedef struct _FILE_NAME_INFO
245 DWORD FileNameLength;
246 WCHAR FileName[1];
247 } FILE_NAME_INFO;
249 typedef BOOL (WINAPI fGetFileInformationByHandleEx) (HANDLE,
250 FILE_INFO_BY_HANDLE_CLASS,
251 LPVOID,
252 DWORD);
253 #endif
255 #if defined (_MSC_VER) && (_MSC_VER >=1400)
256 /* This is ugly, but we need it for isatty() in case we have bad fd's,
257 * otherwise Windows will abort() the program on msvcrt80.dll and later
259 #include <crtdbg.h>
261 _GLIB_EXTERN void
262 myInvalidParameterHandler(const wchar_t *expression,
263 const wchar_t *function,
264 const wchar_t *file,
265 unsigned int line,
266 uintptr_t pReserved)
269 #endif
271 #include "gwin32.h"
272 #endif
275 * G_LOG_DOMAIN:
277 * Defines the log domain. See [Log Domains](#log-domains).
279 * 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 * Log domains must be unique, and it is recommended that they are the
285 * application or library name, optionally followed by a hyphen and a sub-domain
286 * name. For example, `bloatpad` or `bloatpad-io`.
288 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
289 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
290 * environment variable.
292 * For example, GTK+ uses this in its `Makefile.am`:
293 * |[
294 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
295 * ]|
297 * Applications can choose to leave it as the default %NULL (or `""`)
298 * domain. However, defining the domain offers the same advantages as
299 * above.
305 * G_LOG_FATAL_MASK:
307 * GLib log levels that are considered fatal by default.
309 * This is not used if structured logging is enabled; see
310 * [Using Structured Logging][using-structured-logging].
314 * GLogFunc:
315 * @log_domain: the log domain of the message
316 * @log_level: the log level of the message (including the
317 * fatal and recursion flags)
318 * @message: the message to process
319 * @user_data: user data, set in g_log_set_handler()
321 * Specifies the prototype of log handler functions.
323 * The default log handler, g_log_default_handler(), automatically appends a
324 * new-line character to @message when printing it. It is advised that any
325 * custom log handler functions behave similarly, so that logging calls in user
326 * code do not need modifying to add a new-line character to the message if the
327 * log handler is changed.
329 * This is not used if structured logging is enabled; see
330 * [Using Structured Logging][using-structured-logging].
334 * GLogLevelFlags:
335 * @G_LOG_FLAG_RECURSION: internal flag
336 * @G_LOG_FLAG_FATAL: internal flag
337 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
338 * This level is also used for messages produced by g_assert().
339 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
340 * g_critical().
341 * This level is also used for messages produced by g_return_if_fail()
342 * and g_return_val_if_fail().
343 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
344 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
345 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
346 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
347 * @G_LOG_LEVEL_MASK: a mask including all log levels
349 * Flags specifying the level of log messages.
351 * It is possible to change how GLib treats messages of the various
352 * levels using g_log_set_handler() and g_log_set_fatal_mask().
356 * G_LOG_LEVEL_USER_SHIFT:
358 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
359 * Higher bits can be used for user-defined log levels.
363 * g_message:
364 * @...: format string, followed by parameters to insert
365 * into the format string (as with printf())
367 * A convenience function/macro to log a normal message.
369 * If g_log_default_handler() is used as the log handler function, a new-line
370 * character will automatically be appended to @..., and need not be entered
371 * manually.
373 * If structured logging is enabled, this will use g_log_structured();
374 * otherwise it will use g_log(). See
375 * [Using Structured Logging][using-structured-logging].
379 * g_warning:
380 * @...: format string, followed by parameters to insert
381 * into the format string (as with printf())
383 * A convenience function/macro to log a warning message. The message should
384 * typically *not* be translated to the user's language.
386 * This is not intended for end user error reporting. Use of #GError is
387 * preferred for that instead, as it allows calling functions to perform actions
388 * conditional on the type of error.
390 * Warning messages are intended to be used in the event of unexpected
391 * external conditions (system misconfiguration, missing files,
392 * other trusted programs violating protocol, invalid contents in
393 * trusted files, etc.)
395 * If attempting to deal with programmer errors (for example, incorrect function
396 * parameters) then you should use %G_LOG_LEVEL_CRITICAL instead.
398 * g_warn_if_reached() and g_warn_if_fail() log at %G_LOG_LEVEL_WARNING.
400 * You can make warnings fatal at runtime by setting the `G_DEBUG`
401 * environment variable (see
402 * [Running GLib Applications](glib-running.html)):
404 * |[
405 * G_DEBUG=fatal-warnings gdb ./my-program
406 * ]|
408 * Any unrelated failures can be skipped over in
409 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
411 * If g_log_default_handler() is used as the log handler function,
412 * a newline character will automatically be appended to @..., and
413 * need not be entered manually.
415 * If structured logging is enabled, this will use g_log_structured();
416 * otherwise it will use g_log(). See
417 * [Using Structured Logging][using-structured-logging].
421 * g_critical:
422 * @...: format string, followed by parameters to insert
423 * into the format string (as with printf())
425 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
427 * Critical warnings are intended to be used in the event of an error
428 * that originated in the current process (a programmer error).
429 * Logging of a critical error is by definition an indication of a bug
430 * somewhere in the current program (or its libraries).
432 * g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and
433 * g_return_val_if_reached() log at %G_LOG_LEVEL_CRITICAL.
435 * You can make critical warnings fatal at runtime by
436 * setting the `G_DEBUG` environment variable (see
437 * [Running GLib Applications](glib-running.html)):
439 * |[
440 * G_DEBUG=fatal-warnings gdb ./my-program
441 * ]|
443 * You can also use g_log_set_always_fatal().
445 * Any unrelated failures can be skipped over in
446 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
448 * The message should typically *not* be translated to the
449 * user's language.
451 * If g_log_default_handler() is used as the log handler function, a new-line
452 * character will automatically be appended to @..., and need not be entered
453 * manually.
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].
461 * g_error:
462 * @...: format string, followed by parameters to insert
463 * into the format string (as with printf())
465 * A convenience function/macro to log an error message. The message should
466 * typically *not* be translated to the user's language.
468 * This is not intended for end user error reporting. Use of #GError is
469 * preferred for that instead, as it allows calling functions to perform actions
470 * conditional on the type of error.
472 * Error messages are always fatal, resulting in a call to
473 * abort() to terminate the application. This function will
474 * result in a core dump; don't use it for errors you expect.
475 * Using this function indicates a bug in your program, i.e.
476 * an assertion failure.
478 * If g_log_default_handler() is used as the log handler function, a new-line
479 * character will automatically be appended to @..., and need not be entered
480 * manually.
482 * If structured logging is enabled, this will use g_log_structured();
483 * otherwise it will use g_log(). See
484 * [Using Structured Logging][using-structured-logging].
488 * g_info:
489 * @...: format string, followed by parameters to insert
490 * into the format string (as with printf())
492 * A convenience function/macro to log an informational message. Seldom used.
494 * If g_log_default_handler() is used as the log handler function, a new-line
495 * character will automatically be appended to @..., and need not be entered
496 * manually.
498 * Such messages are suppressed by the g_log_default_handler() and
499 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
500 * set appropriately.
502 * If structured logging is enabled, this will use g_log_structured();
503 * otherwise it will use g_log(). See
504 * [Using Structured Logging][using-structured-logging].
506 * Since: 2.40
510 * g_debug:
511 * @...: format string, followed by parameters to insert
512 * into the format string (as with printf())
514 * A convenience function/macro to log a debug message. The message should
515 * typically *not* be translated to the user's language.
517 * If g_log_default_handler() is used as the log handler function, a new-line
518 * character will automatically be appended to @..., and need not be entered
519 * manually.
521 * Such messages are suppressed by the g_log_default_handler() and
522 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
523 * set appropriately.
525 * If structured logging is enabled, this will use g_log_structured();
526 * otherwise it will use g_log(). See
527 * [Using Structured Logging][using-structured-logging].
529 * Since: 2.6
532 /* --- structures --- */
533 typedef struct _GLogDomain GLogDomain;
534 typedef struct _GLogHandler GLogHandler;
535 struct _GLogDomain
537 gchar *log_domain;
538 GLogLevelFlags fatal_mask;
539 GLogHandler *handlers;
540 GLogDomain *next;
542 struct _GLogHandler
544 guint id;
545 GLogLevelFlags log_level;
546 GLogFunc log_func;
547 gpointer data;
548 GDestroyNotify destroy;
549 GLogHandler *next;
553 /* --- variables --- */
554 static GMutex g_messages_lock;
555 static GLogDomain *g_log_domains = NULL;
556 static GPrintFunc glib_print_func = NULL;
557 static GPrintFunc glib_printerr_func = NULL;
558 static GPrivate g_log_depth;
559 static GPrivate g_log_structured_depth;
560 static GLogFunc default_log_func = g_log_default_handler;
561 static gpointer default_log_data = NULL;
562 static GTestLogFatalFunc fatal_log_func = NULL;
563 static gpointer fatal_log_data;
564 static GLogWriterFunc log_writer_func = g_log_writer_default;
565 static gpointer log_writer_user_data = NULL;
566 static GDestroyNotify log_writer_user_data_free = NULL;
568 /* --- functions --- */
570 static void _g_log_abort (gboolean breakpoint);
572 static void
573 _g_log_abort (gboolean breakpoint)
575 gboolean debugger_present;
577 if (g_test_subprocess ())
579 /* If this is a test case subprocess then it probably caused
580 * this error message on purpose, so just exit() rather than
581 * abort()ing, to avoid triggering any system crash-reporting
582 * daemon.
584 _exit (1);
587 #ifdef G_OS_WIN32
588 debugger_present = IsDebuggerPresent ();
589 #else
590 /* Assume GDB is attached. */
591 debugger_present = TRUE;
592 #endif /* !G_OS_WIN32 */
594 if (debugger_present && breakpoint)
595 G_BREAKPOINT ();
596 else
597 g_abort ();
600 #ifdef G_OS_WIN32
601 static gboolean win32_keep_fatal_message = FALSE;
603 /* This default message will usually be overwritten. */
604 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
605 * called with huge strings, is it?
607 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
608 static gchar *fatal_msg_ptr = fatal_msg_buf;
610 #undef write
611 static inline int
612 dowrite (int fd,
613 const void *buf,
614 unsigned int len)
616 if (win32_keep_fatal_message)
618 memcpy (fatal_msg_ptr, buf, len);
619 fatal_msg_ptr += len;
620 *fatal_msg_ptr = 0;
621 return len;
624 write (fd, buf, len);
626 return len;
628 #define write(fd, buf, len) dowrite(fd, buf, len)
630 #endif
632 static void
633 write_string (FILE *stream,
634 const gchar *string)
636 fputs (string, stream);
639 static void
640 write_string_sized (FILE *stream,
641 const gchar *string,
642 gssize length)
644 /* Is it nul-terminated? */
645 if (length < 0)
646 write_string (stream, string);
647 else
648 fwrite (string, 1, length, stream);
651 static GLogDomain*
652 g_log_find_domain_L (const gchar *log_domain)
654 GLogDomain *domain;
656 domain = g_log_domains;
657 while (domain)
659 if (strcmp (domain->log_domain, log_domain) == 0)
660 return domain;
661 domain = domain->next;
663 return NULL;
666 static GLogDomain*
667 g_log_domain_new_L (const gchar *log_domain)
669 GLogDomain *domain;
671 domain = g_new (GLogDomain, 1);
672 domain->log_domain = g_strdup (log_domain);
673 domain->fatal_mask = G_LOG_FATAL_MASK;
674 domain->handlers = NULL;
676 domain->next = g_log_domains;
677 g_log_domains = domain;
679 return domain;
682 static void
683 g_log_domain_check_free_L (GLogDomain *domain)
685 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
686 domain->handlers == NULL)
688 GLogDomain *last, *work;
690 last = NULL;
692 work = g_log_domains;
693 while (work)
695 if (work == domain)
697 if (last)
698 last->next = domain->next;
699 else
700 g_log_domains = domain->next;
701 g_free (domain->log_domain);
702 g_free (domain);
703 break;
705 last = work;
706 work = last->next;
711 static GLogFunc
712 g_log_domain_get_handler_L (GLogDomain *domain,
713 GLogLevelFlags log_level,
714 gpointer *data)
716 if (domain && log_level)
718 GLogHandler *handler;
720 handler = domain->handlers;
721 while (handler)
723 if ((handler->log_level & log_level) == log_level)
725 *data = handler->data;
726 return handler->log_func;
728 handler = handler->next;
732 *data = default_log_data;
733 return default_log_func;
737 * g_log_set_always_fatal:
738 * @fatal_mask: the mask containing bits set for each level
739 * of error which is to be fatal
741 * Sets the message levels which are always fatal, in any log domain.
742 * When a message with any of these levels is logged the program terminates.
743 * You can only set the levels defined by GLib to be fatal.
744 * %G_LOG_LEVEL_ERROR is always fatal.
746 * You can also make some message levels fatal at runtime by setting
747 * the `G_DEBUG` environment variable (see
748 * [Running GLib Applications](glib-running.html)).
750 * Libraries should not call this function, as it affects all messages logged
751 * by a process, including those from other libraries.
753 * Structured log messages (using g_log_structured() and
754 * g_log_structured_array()) are fatal only if the default log writer is used;
755 * otherwise it is up to the writer function to determine which log messages
756 * are fatal. See [Using Structured Logging][using-structured-logging].
758 * Returns: the old fatal mask
760 GLogLevelFlags
761 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
763 GLogLevelFlags old_mask;
765 /* restrict the global mask to levels that are known to glib
766 * since this setting applies to all domains
768 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
769 /* force errors to be fatal */
770 fatal_mask |= G_LOG_LEVEL_ERROR;
771 /* remove bogus flag */
772 fatal_mask &= ~G_LOG_FLAG_FATAL;
774 g_mutex_lock (&g_messages_lock);
775 old_mask = g_log_always_fatal;
776 g_log_always_fatal = fatal_mask;
777 g_mutex_unlock (&g_messages_lock);
779 return old_mask;
783 * g_log_set_fatal_mask:
784 * @log_domain: the log domain
785 * @fatal_mask: the new fatal mask
787 * Sets the log levels which are fatal in the given domain.
788 * %G_LOG_LEVEL_ERROR is always fatal.
790 * This has no effect on structured log messages (using g_log_structured() or
791 * g_log_structured_array()). To change the fatal behaviour for specific log
792 * messages, programs must install a custom log writer function using
793 * g_log_set_writer_func(). See
794 * [Using Structured Logging][using-structured-logging].
796 * This function is mostly intended to be used with
797 * %G_LOG_LEVEL_CRITICAL. You should typically not set
798 * %G_LOG_LEVEL_WARNING, %G_LOG_LEVEL_MESSAGE, %G_LOG_LEVEL_INFO or
799 * %G_LOG_LEVEL_DEBUG as fatal except inside of test programs.
801 * Returns: the old fatal mask for the log domain
803 GLogLevelFlags
804 g_log_set_fatal_mask (const gchar *log_domain,
805 GLogLevelFlags fatal_mask)
807 GLogLevelFlags old_flags;
808 GLogDomain *domain;
810 if (!log_domain)
811 log_domain = "";
813 /* force errors to be fatal */
814 fatal_mask |= G_LOG_LEVEL_ERROR;
815 /* remove bogus flag */
816 fatal_mask &= ~G_LOG_FLAG_FATAL;
818 g_mutex_lock (&g_messages_lock);
820 domain = g_log_find_domain_L (log_domain);
821 if (!domain)
822 domain = g_log_domain_new_L (log_domain);
823 old_flags = domain->fatal_mask;
825 domain->fatal_mask = fatal_mask;
826 g_log_domain_check_free_L (domain);
828 g_mutex_unlock (&g_messages_lock);
830 return old_flags;
834 * g_log_set_handler:
835 * @log_domain: (nullable): the log domain, or %NULL for the default ""
836 * application domain
837 * @log_levels: the log levels to apply the log handler for.
838 * To handle fatal and recursive messages as well, combine
839 * the log levels with the #G_LOG_FLAG_FATAL and
840 * #G_LOG_FLAG_RECURSION bit flags.
841 * @log_func: the log handler function
842 * @user_data: data passed to the log handler
844 * Sets the log handler for a domain and a set of log levels.
845 * To handle fatal and recursive messages the @log_levels parameter
846 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
847 * bit flags.
849 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
850 * you want to set a handler for this log level you must combine it with
851 * #G_LOG_FLAG_FATAL.
853 * This has no effect if structured logging is enabled; see
854 * [Using Structured Logging][using-structured-logging].
856 * Here is an example for adding a log handler for all warning messages
857 * in the default domain:
858 * |[<!-- language="C" -->
859 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
860 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
861 * ]|
863 * This example adds a log handler for all critical messages from GTK+:
864 * |[<!-- language="C" -->
865 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
866 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
867 * ]|
869 * This example adds a log handler for all messages from GLib:
870 * |[<!-- language="C" -->
871 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
872 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
873 * ]|
875 * Returns: the id of the new handler
877 guint
878 g_log_set_handler (const gchar *log_domain,
879 GLogLevelFlags log_levels,
880 GLogFunc log_func,
881 gpointer user_data)
883 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
887 * g_log_set_handler_full: (rename-to g_log_set_handler)
888 * @log_domain: (nullable): the log domain, or %NULL for the default ""
889 * application domain
890 * @log_levels: the log levels to apply the log handler for.
891 * To handle fatal and recursive messages as well, combine
892 * the log levels with the #G_LOG_FLAG_FATAL and
893 * #G_LOG_FLAG_RECURSION bit flags.
894 * @log_func: the log handler function
895 * @user_data: data passed to the log handler
896 * @destroy: destroy notify for @user_data, or %NULL
898 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
900 * This has no effect if structured logging is enabled; see
901 * [Using Structured Logging][using-structured-logging].
903 * Returns: the id of the new handler
905 * Since: 2.46
907 guint
908 g_log_set_handler_full (const gchar *log_domain,
909 GLogLevelFlags log_levels,
910 GLogFunc log_func,
911 gpointer user_data,
912 GDestroyNotify destroy)
914 static guint handler_id = 0;
915 GLogDomain *domain;
916 GLogHandler *handler;
918 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
919 g_return_val_if_fail (log_func != NULL, 0);
921 if (!log_domain)
922 log_domain = "";
924 handler = g_new (GLogHandler, 1);
926 g_mutex_lock (&g_messages_lock);
928 domain = g_log_find_domain_L (log_domain);
929 if (!domain)
930 domain = g_log_domain_new_L (log_domain);
932 handler->id = ++handler_id;
933 handler->log_level = log_levels;
934 handler->log_func = log_func;
935 handler->data = user_data;
936 handler->destroy = destroy;
937 handler->next = domain->handlers;
938 domain->handlers = handler;
940 g_mutex_unlock (&g_messages_lock);
942 return handler_id;
946 * g_log_set_default_handler:
947 * @log_func: the log handler function
948 * @user_data: data passed to the log handler
950 * Installs a default log handler which is used if no
951 * log handler has been set for the particular log domain
952 * and log level combination. By default, GLib uses
953 * g_log_default_handler() as default log handler.
955 * This has no effect if structured logging is enabled; see
956 * [Using Structured Logging][using-structured-logging].
958 * Returns: the previous default log handler
960 * Since: 2.6
962 GLogFunc
963 g_log_set_default_handler (GLogFunc log_func,
964 gpointer user_data)
966 GLogFunc old_log_func;
968 g_mutex_lock (&g_messages_lock);
969 old_log_func = default_log_func;
970 default_log_func = log_func;
971 default_log_data = user_data;
972 g_mutex_unlock (&g_messages_lock);
974 return old_log_func;
978 * g_test_log_set_fatal_handler:
979 * @log_func: the log handler function.
980 * @user_data: data passed to the log handler.
982 * Installs a non-error fatal log handler which can be
983 * used to decide whether log messages which are counted
984 * as fatal abort the program.
986 * The use case here is that you are running a test case
987 * that depends on particular libraries or circumstances
988 * and cannot prevent certain known critical or warning
989 * messages. So you install a handler that compares the
990 * domain and message to precisely not abort in such a case.
992 * Note that the handler is reset at the beginning of
993 * any test case, so you have to set it inside each test
994 * function which needs the special behavior.
996 * This handler has no effect on g_error messages.
998 * This handler also has no effect on structured log messages (using
999 * g_log_structured() or g_log_structured_array()). To change the fatal
1000 * behaviour for specific log messages, programs must install a custom log
1001 * writer function using g_log_set_writer_func().See
1002 * [Using Structured Logging][using-structured-logging].
1004 * Since: 2.22
1006 void
1007 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
1008 gpointer user_data)
1010 g_mutex_lock (&g_messages_lock);
1011 fatal_log_func = log_func;
1012 fatal_log_data = user_data;
1013 g_mutex_unlock (&g_messages_lock);
1017 * g_log_remove_handler:
1018 * @log_domain: the log domain
1019 * @handler_id: the id of the handler, which was returned
1020 * in g_log_set_handler()
1022 * Removes the log handler.
1024 * This has no effect if structured logging is enabled; see
1025 * [Using Structured Logging][using-structured-logging].
1027 void
1028 g_log_remove_handler (const gchar *log_domain,
1029 guint handler_id)
1031 GLogDomain *domain;
1033 g_return_if_fail (handler_id > 0);
1035 if (!log_domain)
1036 log_domain = "";
1038 g_mutex_lock (&g_messages_lock);
1039 domain = g_log_find_domain_L (log_domain);
1040 if (domain)
1042 GLogHandler *work, *last;
1044 last = NULL;
1045 work = domain->handlers;
1046 while (work)
1048 if (work->id == handler_id)
1050 if (last)
1051 last->next = work->next;
1052 else
1053 domain->handlers = work->next;
1054 g_log_domain_check_free_L (domain);
1055 g_mutex_unlock (&g_messages_lock);
1056 if (work->destroy)
1057 work->destroy (work->data);
1058 g_free (work);
1059 return;
1061 last = work;
1062 work = last->next;
1065 g_mutex_unlock (&g_messages_lock);
1066 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1067 G_STRLOC, handler_id, log_domain);
1070 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1071 (wc == 0x7f) || \
1072 (wc >= 0x80 && wc < 0xa0)))
1074 static gchar*
1075 strdup_convert (const gchar *string,
1076 const gchar *charset)
1078 if (!g_utf8_validate (string, -1, NULL))
1080 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1081 guchar *p;
1083 for (p = (guchar *)string; *p; p++)
1085 if (CHAR_IS_SAFE(*p) &&
1086 !(*p == '\r' && *(p + 1) != '\n') &&
1087 *p < 0x80)
1088 g_string_append_c (gstring, *p);
1089 else
1090 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1093 return g_string_free (gstring, FALSE);
1095 else
1097 GError *err = NULL;
1099 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1100 if (result)
1101 return result;
1102 else
1104 /* Not thread-safe, but doesn't matter if we print the warning twice
1106 static gboolean warned = FALSE;
1107 if (!warned)
1109 warned = TRUE;
1110 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1112 g_error_free (err);
1114 return g_strdup (string);
1119 /* For a radix of 8 we need at most 3 output bytes for 1 input
1120 * byte. Additionally we might need up to 2 output bytes for the
1121 * readix prefix and 1 byte for the trailing NULL.
1123 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1125 static void
1126 format_unsigned (gchar *buf,
1127 gulong num,
1128 guint radix)
1130 gulong tmp;
1131 gchar c;
1132 gint i, n;
1134 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1136 if (radix != 8 && radix != 10 && radix != 16)
1138 *buf = '\000';
1139 return;
1142 if (!num)
1144 *buf++ = '0';
1145 *buf = '\000';
1146 return;
1149 if (radix == 16)
1151 *buf++ = '0';
1152 *buf++ = 'x';
1154 else if (radix == 8)
1156 *buf++ = '0';
1159 n = 0;
1160 tmp = num;
1161 while (tmp)
1163 tmp /= radix;
1164 n++;
1167 i = n;
1169 /* Again we can't use g_assert; actually this check should _never_ fail. */
1170 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1172 *buf = '\000';
1173 return;
1176 while (num)
1178 i--;
1179 c = (num % radix);
1180 if (c < 10)
1181 buf[i] = c + '0';
1182 else
1183 buf[i] = c + 'a' - 10;
1184 num /= radix;
1187 buf[n] = '\000';
1190 /* string size big enough to hold level prefix */
1191 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1193 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1195 /* these are emitted by the default log handler */
1196 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1197 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1198 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1200 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1201 gboolean use_color);
1202 static const gchar *color_reset (gboolean use_color);
1204 static FILE *
1205 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1206 GLogLevelFlags log_level,
1207 gboolean use_color)
1209 gboolean to_stdout = TRUE;
1211 /* we may not call _any_ GLib functions here */
1213 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1215 switch (log_level & G_LOG_LEVEL_MASK)
1217 case G_LOG_LEVEL_ERROR:
1218 strcat (level_prefix, "ERROR");
1219 to_stdout = FALSE;
1220 break;
1221 case G_LOG_LEVEL_CRITICAL:
1222 strcat (level_prefix, "CRITICAL");
1223 to_stdout = FALSE;
1224 break;
1225 case G_LOG_LEVEL_WARNING:
1226 strcat (level_prefix, "WARNING");
1227 to_stdout = FALSE;
1228 break;
1229 case G_LOG_LEVEL_MESSAGE:
1230 strcat (level_prefix, "Message");
1231 to_stdout = FALSE;
1232 break;
1233 case G_LOG_LEVEL_INFO:
1234 strcat (level_prefix, "INFO");
1235 break;
1236 case G_LOG_LEVEL_DEBUG:
1237 strcat (level_prefix, "DEBUG");
1238 break;
1239 default:
1240 if (log_level)
1242 strcat (level_prefix, "LOG-");
1243 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1245 else
1246 strcat (level_prefix, "LOG");
1247 break;
1250 strcat (level_prefix, color_reset (use_color));
1252 if (log_level & G_LOG_FLAG_RECURSION)
1253 strcat (level_prefix, " (recursed)");
1254 if (log_level & ALERT_LEVELS)
1255 strcat (level_prefix, " **");
1257 #ifdef G_OS_WIN32
1258 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1259 win32_keep_fatal_message = TRUE;
1260 #endif
1261 return to_stdout ? stdout : stderr;
1264 typedef struct {
1265 gchar *log_domain;
1266 GLogLevelFlags log_level;
1267 gchar *pattern;
1268 } GTestExpectedMessage;
1270 static GSList *expected_messages = NULL;
1273 * g_logv:
1274 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1275 * application domain
1276 * @log_level: the log level
1277 * @format: the message format. See the printf() documentation
1278 * @args: the parameters to insert into the format string
1280 * Logs an error or debugging message.
1282 * If the log level has been set as fatal, the abort()
1283 * function is called to terminate the program.
1285 * If g_log_default_handler() is used as the log handler function, a new-line
1286 * character will automatically be appended to @..., and need not be entered
1287 * manually.
1289 * If [structured logging is enabled][using-structured-logging] this will
1290 * output via the structured log writer function (see g_log_set_writer_func()).
1292 void
1293 g_logv (const gchar *log_domain,
1294 GLogLevelFlags log_level,
1295 const gchar *format,
1296 va_list args)
1298 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1299 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1300 gchar buffer[1025], *msg, *msg_alloc = NULL;
1301 gint i;
1303 log_level &= G_LOG_LEVEL_MASK;
1304 if (!log_level)
1305 return;
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);
1315 msg = buffer;
1317 else
1318 msg = msg_alloc = g_strdup_vprintf (format, args);
1320 if (expected_messages)
1322 GTestExpectedMessage *expected = expected_messages->data;
1324 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1325 ((log_level & expected->log_level) == expected->log_level) &&
1326 g_pattern_match_simple (expected->pattern, msg))
1328 expected_messages = g_slist_delete_link (expected_messages,
1329 expected_messages);
1330 g_free (expected->log_domain);
1331 g_free (expected->pattern);
1332 g_free (expected);
1333 g_free (msg_alloc);
1334 return;
1336 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1338 gchar level_prefix[STRING_BUFFER_SIZE];
1339 gchar *expected_message;
1341 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1342 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1343 expected->log_domain ? expected->log_domain : "**",
1344 level_prefix, expected->pattern);
1345 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1346 g_free (expected_message);
1348 log_level |= G_LOG_FLAG_FATAL;
1352 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1354 GLogLevelFlags test_level;
1356 test_level = 1 << i;
1357 if (log_level & test_level)
1359 GLogDomain *domain;
1360 GLogFunc log_func;
1361 GLogLevelFlags domain_fatal_mask;
1362 gpointer data = NULL;
1363 gboolean masquerade_fatal = FALSE;
1364 guint depth;
1366 if (was_fatal)
1367 test_level |= G_LOG_FLAG_FATAL;
1368 if (was_recursion)
1369 test_level |= G_LOG_FLAG_RECURSION;
1371 /* check recursion and lookup handler */
1372 g_mutex_lock (&g_messages_lock);
1373 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1374 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1375 if (depth)
1376 test_level |= G_LOG_FLAG_RECURSION;
1377 depth++;
1378 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1379 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1380 test_level |= G_LOG_FLAG_FATAL;
1381 if (test_level & G_LOG_FLAG_RECURSION)
1382 log_func = _g_log_fallback_handler;
1383 else
1384 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1385 domain = NULL;
1386 g_mutex_unlock (&g_messages_lock);
1388 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1390 log_func (log_domain, test_level, msg, data);
1392 if ((test_level & G_LOG_FLAG_FATAL)
1393 && !(test_level & G_LOG_LEVEL_ERROR))
1395 masquerade_fatal = fatal_log_func
1396 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1399 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1401 #ifdef G_OS_WIN32
1402 if (win32_keep_fatal_message)
1404 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1406 MessageBox (NULL, locale_msg, NULL,
1407 MB_ICONERROR|MB_SETFOREGROUND);
1409 #endif /* !G_OS_WIN32 */
1411 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1414 depth--;
1415 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1419 g_free (msg_alloc);
1423 * g_log:
1424 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1425 * for the default
1426 * @log_level: the log level, either from #GLogLevelFlags
1427 * or a user-defined level
1428 * @format: the message format. See the printf() documentation
1429 * @...: the parameters to insert into the format string
1431 * Logs an error or debugging message.
1433 * If the log level has been set as fatal, the abort()
1434 * function is called to terminate the program.
1436 * If g_log_default_handler() is used as the log handler function, a new-line
1437 * character will automatically be appended to @..., and need not be entered
1438 * manually.
1440 * If [structured logging is enabled][using-structured-logging] this will
1441 * output via the structured log writer function (see g_log_set_writer_func()).
1443 void
1444 g_log (const gchar *log_domain,
1445 GLogLevelFlags log_level,
1446 const gchar *format,
1447 ...)
1449 va_list args;
1451 va_start (args, format);
1452 g_logv (log_domain, log_level, format, args);
1453 va_end (args);
1456 /* Return value must be 1 byte long (plus nul byte).
1457 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1459 static const gchar *
1460 log_level_to_priority (GLogLevelFlags log_level)
1462 if (log_level & G_LOG_LEVEL_ERROR)
1463 return "3";
1464 else if (log_level & G_LOG_LEVEL_CRITICAL)
1465 return "4";
1466 else if (log_level & G_LOG_LEVEL_WARNING)
1467 return "4";
1468 else if (log_level & G_LOG_LEVEL_MESSAGE)
1469 return "5";
1470 else if (log_level & G_LOG_LEVEL_INFO)
1471 return "6";
1472 else if (log_level & G_LOG_LEVEL_DEBUG)
1473 return "7";
1475 /* Default to LOG_NOTICE for custom log levels. */
1476 return "5";
1479 static FILE *
1480 log_level_to_file (GLogLevelFlags log_level)
1482 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1483 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1484 return stderr;
1485 else
1486 return stdout;
1489 static const gchar *
1490 log_level_to_color (GLogLevelFlags log_level,
1491 gboolean use_color)
1493 /* we may not call _any_ GLib functions here */
1495 if (!use_color)
1496 return "";
1498 if (log_level & G_LOG_LEVEL_ERROR)
1499 return "\033[1;31m"; /* red */
1500 else if (log_level & G_LOG_LEVEL_CRITICAL)
1501 return "\033[1;35m"; /* magenta */
1502 else if (log_level & G_LOG_LEVEL_WARNING)
1503 return "\033[1;33m"; /* yellow */
1504 else if (log_level & G_LOG_LEVEL_MESSAGE)
1505 return "\033[1;32m"; /* green */
1506 else if (log_level & G_LOG_LEVEL_INFO)
1507 return "\033[1;32m"; /* green */
1508 else if (log_level & G_LOG_LEVEL_DEBUG)
1509 return "\033[1;32m"; /* green */
1511 /* No color for custom log levels. */
1512 return "";
1515 static const gchar *
1516 color_reset (gboolean use_color)
1518 /* we may not call _any_ GLib functions here */
1520 if (!use_color)
1521 return "";
1523 return "\033[0m";
1526 #ifdef G_OS_WIN32
1528 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1529 * so we need to check the name of the pipe if _isatty (fd) == 0
1532 static gboolean
1533 win32_is_pipe_tty (int fd)
1535 gboolean result = FALSE;
1536 HANDLE h_fd;
1537 FILE_NAME_INFO *info = NULL;
1538 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1539 wchar_t *name = NULL;
1540 gint length;
1542 /* XXX: Remove once XP support really dropped */
1543 #if _WIN32_WINNT < 0x0600
1544 HANDLE h_kerneldll = NULL;
1545 fGetFileInformationByHandleEx *GetFileInformationByHandleEx;
1546 #endif
1548 h_fd = (HANDLE) _get_osfhandle (fd);
1550 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1551 goto done_query;
1553 /* The following check is available on Vista or later, so on XP, no color support */
1554 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1556 /* XXX: Remove once XP support really dropped */
1557 #if _WIN32_WINNT < 0x0600
1558 h_kerneldll = LoadLibraryW (L"kernel32.dll");
1560 if (h_kerneldll == NULL)
1561 goto done_query;
1563 GetFileInformationByHandleEx =
1564 (fGetFileInformationByHandleEx *) GetProcAddress (h_kerneldll, "GetFileInformationByHandleEx");
1566 if (GetFileInformationByHandleEx == NULL)
1567 goto done_query;
1568 #endif
1570 info = g_try_malloc (info_size);
1572 if (info == NULL ||
1573 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1574 goto done_query;
1576 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1577 name = info->FileName;
1579 length = wcslen (L"\\cygwin-");
1580 if (wcsncmp (name, L"\\cygwin-", length))
1582 length = wcslen (L"\\msys-");
1583 if (wcsncmp (name, L"\\msys-", length))
1584 goto done_query;
1587 name += length;
1588 length = wcsspn (name, L"0123456789abcdefABCDEF");
1589 if (length != 16)
1590 goto done_query;
1592 name += length;
1593 length = wcslen (L"-pty");
1594 if (wcsncmp (name, L"-pty", length))
1595 goto done_query;
1597 name += length;
1598 length = wcsspn (name, L"0123456789");
1599 if (length != 1)
1600 goto done_query;
1602 name += length;
1603 length = wcslen (L"-to-master");
1604 if (wcsncmp (name, L"-to-master", length))
1606 length = wcslen (L"-from-master");
1607 if (wcsncmp (name, L"-from-master", length))
1608 goto done_query;
1611 result = TRUE;
1613 done_query:
1614 if (info != NULL)
1615 g_free (info);
1617 /* XXX: Remove once XP support really dropped */
1618 #if _WIN32_WINNT < 0x0600
1619 if (h_kerneldll != NULL)
1620 FreeLibrary (h_kerneldll);
1621 #endif
1623 return result;
1625 #endif
1627 #pragma GCC diagnostic push
1628 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1631 * g_log_structured:
1632 * @log_domain: log domain, usually %G_LOG_DOMAIN
1633 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1634 * level
1635 * @...: key-value pairs of structured data to add to the log entry, followed
1636 * by the key "MESSAGE", followed by a printf()-style message format,
1637 * followed by parameters to insert in the format string
1639 * Log a message with structured data. The message will be passed through to
1640 * the log writer set by the application using g_log_set_writer_func(). If the
1641 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1642 * be aborted at the end of this function. If the log writer returns
1643 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1644 * See the documentation for #GLogWriterFunc for information on chaining
1645 * writers.
1647 * The structured data is provided as key–value pairs, where keys are UTF-8
1648 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1649 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1650 * structured data, use g_log_structured_array(). The keys for structured data
1651 * should follow the [systemd journal
1652 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1653 * specification. It is suggested that custom keys are namespaced according to
1654 * the code which sets them. For example, custom keys from GLib all have a
1655 * `GLIB_` prefix.
1657 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1658 * be converted into a
1659 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1660 * field. The format string will have its placeholders substituted for the provided
1661 * values and be converted into a
1662 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1663 * field.
1665 * Other fields you may commonly want to pass into this function:
1667 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1668 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1669 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1670 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1671 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1673 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1674 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1675 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1676 * glib.h.
1678 * For example:
1679 * |[<!-- language="C" -->
1680 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1681 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1682 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1683 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1684 * some_pointer, some_integer);
1685 * ]|
1687 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1688 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1689 * If adding a `MESSAGE_ID`, consider shipping a [message
1690 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1691 * your software.
1693 * To pass a user data pointer to the log writer function which is specific to
1694 * this logging call, you must use g_log_structured_array() and pass the pointer
1695 * as a field with #GLogField.length set to zero, otherwise it will be
1696 * interpreted as a string.
1698 * For example:
1699 * |[<!-- language="C" -->
1700 * const GLogField fields[] = {
1701 * { "MESSAGE", "This is a debug message.", -1 },
1702 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1703 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1704 * { "MY_APPLICATION_STATE", state_object, 0 },
1705 * };
1706 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1707 * ]|
1709 * Note also that, even if no other structured fields are specified, there
1710 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1711 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1712 * field for which printf()-style formatting is supported.
1714 * The default writer function for `stdout` and `stderr` will automatically
1715 * append a new-line character after the message, so you should not add one
1716 * manually to the format string.
1718 * Since: 2.50
1720 void
1721 g_log_structured (const gchar *log_domain,
1722 GLogLevelFlags log_level,
1723 ...)
1725 va_list args;
1726 gchar buffer[1025], *message_allocated = NULL;
1727 const char *format;
1728 const gchar *message;
1729 gpointer p;
1730 gsize n_fields, i;
1731 GLogField stack_fields[16];
1732 GLogField *fields = stack_fields;
1733 GLogField *fields_allocated = NULL;
1734 GArray *array = NULL;
1736 va_start (args, log_level);
1738 /* MESSAGE and PRIORITY are a given */
1739 n_fields = 2;
1741 if (log_domain)
1742 n_fields++;
1744 for (p = va_arg (args, gchar *), i = n_fields;
1745 strcmp (p, "MESSAGE") != 0;
1746 p = va_arg (args, gchar *), i++)
1748 GLogField field;
1749 const gchar *key = p;
1750 gconstpointer value = va_arg (args, gpointer);
1752 field.key = key;
1753 field.value = value;
1754 field.length = -1;
1756 if (i < 16)
1757 stack_fields[i] = field;
1758 else
1760 /* Don't allow dynamic allocation, since we're likely
1761 * in an out-of-memory situation. For lack of a better solution,
1762 * just ignore further key-value pairs.
1764 if (log_level & G_LOG_FLAG_RECURSION)
1765 continue;
1767 if (i == 16)
1769 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1770 g_array_append_vals (array, stack_fields, 16);
1773 g_array_append_val (array, field);
1777 n_fields = i;
1779 if (array)
1780 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1782 format = va_arg (args, gchar *);
1784 if (log_level & G_LOG_FLAG_RECURSION)
1786 /* we use a stack buffer of fixed size, since we're likely
1787 * in an out-of-memory situation
1789 gsize size G_GNUC_UNUSED;
1791 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1792 message = buffer;
1794 else
1796 message = message_allocated = g_strdup_vprintf (format, args);
1799 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1800 fields[0].key = "MESSAGE";
1801 fields[0].value = message;
1802 fields[0].length = -1;
1804 fields[1].key = "PRIORITY";
1805 fields[1].value = log_level_to_priority (log_level);
1806 fields[1].length = -1;
1808 if (log_domain)
1810 fields[2].key = "GLIB_DOMAIN";
1811 fields[2].value = log_domain;
1812 fields[2].length = -1;
1815 /* Log it. */
1816 g_log_structured_array (log_level, fields, n_fields);
1818 g_free (fields_allocated);
1819 g_free (message_allocated);
1821 va_end (args);
1825 * g_log_variant:
1826 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1827 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1828 * level
1829 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1830 * containing the key-value pairs of message data.
1832 * Log a message with structured data, accepting the data within a #GVariant. This
1833 * version is especially useful for use in other languages, via introspection.
1835 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1836 * contain the text shown to the user.
1838 * The values in the @fields dictionary are likely to be of type String
1839 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1840 * supported. In this case the message is handled as binary and will be forwarded
1841 * to the log writer as such. The size of the array should not be higher than
1842 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1843 * g_variant_print() will be used to convert the value into a string.
1845 * For more details on its usage and about the parameters, see g_log_structured().
1847 * Since: 2.50
1850 void
1851 g_log_variant (const gchar *log_domain,
1852 GLogLevelFlags log_level,
1853 GVariant *fields)
1855 GVariantIter iter;
1856 GVariant *value;
1857 gchar *key;
1858 GArray *fields_array;
1859 GLogField field;
1860 GSList *values_list, *print_list;
1862 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1864 values_list = print_list = NULL;
1865 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1867 field.key = "PRIORITY";
1868 field.value = log_level_to_priority (log_level);
1869 field.length = -1;
1870 g_array_append_val (fields_array, field);
1872 if (log_domain)
1874 field.key = "GLIB_DOMAIN";
1875 field.value = log_domain;
1876 field.length = -1;
1877 g_array_append_val (fields_array, field);
1880 g_variant_iter_init (&iter, fields);
1881 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1883 gboolean defer_unref = TRUE;
1885 field.key = key;
1886 field.length = -1;
1888 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1890 field.value = g_variant_get_string (value, NULL);
1892 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1894 gsize s;
1895 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1896 if (G_LIKELY (s <= G_MAXSSIZE))
1898 field.length = s;
1900 else
1902 _g_fprintf (stderr,
1903 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1904 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1905 " bytes.", s);
1906 field.length = G_MAXSSIZE;
1909 else
1911 char *s = g_variant_print (value, FALSE);
1912 field.value = s;
1913 print_list = g_slist_prepend (print_list, s);
1914 defer_unref = FALSE;
1917 g_array_append_val (fields_array, field);
1919 if (G_LIKELY (defer_unref))
1920 values_list = g_slist_prepend (values_list, value);
1921 else
1922 g_variant_unref (value);
1925 /* Log it. */
1926 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1928 g_array_free (fields_array, TRUE);
1929 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1930 g_slist_free_full (print_list, g_free);
1934 #pragma GCC diagnostic pop
1936 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1937 const GLogField *fields,
1938 gsize n_fields,
1939 gpointer user_data);
1942 * g_log_structured_array:
1943 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1944 * level
1945 * @fields: (array length=n_fields): key–value pairs of structured data to add
1946 * to the log message
1947 * @n_fields: number of elements in the @fields array
1949 * Log a message with structured data. The message will be passed through to the
1950 * log writer set by the application using g_log_set_writer_func(). If the
1951 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1952 * be aborted at the end of this function.
1954 * See g_log_structured() for more documentation.
1956 * This assumes that @log_level is already present in @fields (typically as the
1957 * `PRIORITY` field).
1959 * Since: 2.50
1961 void
1962 g_log_structured_array (GLogLevelFlags log_level,
1963 const GLogField *fields,
1964 gsize n_fields)
1966 GLogWriterFunc writer_func;
1967 gpointer writer_user_data;
1968 gboolean recursion;
1969 guint depth;
1971 if (n_fields == 0)
1972 return;
1974 /* Check for recursion and look up the writer function. */
1975 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1976 recursion = (depth > 0);
1978 g_mutex_lock (&g_messages_lock);
1980 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1981 writer_user_data = log_writer_user_data;
1983 g_mutex_unlock (&g_messages_lock);
1985 /* Write the log entry. */
1986 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1988 g_assert (writer_func != NULL);
1989 writer_func (log_level, fields, n_fields, writer_user_data);
1991 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1993 /* Abort if the message was fatal. */
1994 if (log_level & G_LOG_FATAL_MASK)
1995 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1998 /* Semi-private helper function to implement the g_message() (etc.) macros
1999 * with support for G_GNUC_PRINTF so that @message_format can be checked
2000 * with -Wformat. */
2001 void
2002 g_log_structured_standard (const gchar *log_domain,
2003 GLogLevelFlags log_level,
2004 const gchar *file,
2005 const gchar *line,
2006 const gchar *func,
2007 const gchar *message_format,
2008 ...)
2010 GLogField fields[] =
2012 { "PRIORITY", log_level_to_priority (log_level), -1 },
2013 { "CODE_FILE", file, -1 },
2014 { "CODE_LINE", line, -1 },
2015 { "CODE_FUNC", func, -1 },
2016 /* Filled in later: */
2017 { "MESSAGE", NULL, -1 },
2018 /* If @log_domain is %NULL, we will not pass this field: */
2019 { "GLIB_DOMAIN", log_domain, -1 },
2021 gsize n_fields;
2022 gchar *message_allocated = NULL;
2023 gchar buffer[1025];
2024 va_list args;
2026 va_start (args, message_format);
2028 if (log_level & G_LOG_FLAG_RECURSION)
2030 /* we use a stack buffer of fixed size, since we're likely
2031 * in an out-of-memory situation
2033 gsize size G_GNUC_UNUSED;
2035 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
2036 fields[4].value = buffer;
2038 else
2040 fields[4].value = message_allocated = g_strdup_vprintf (message_format, args);
2043 va_end (args);
2045 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
2046 g_log_structured_array (log_level, fields, n_fields);
2048 g_free (message_allocated);
2052 * g_log_set_writer_func:
2053 * @func: log writer function, which must not be %NULL
2054 * @user_data: (closure func): user data to pass to @func
2055 * @user_data_free: (destroy func): function to free @user_data once it’s
2056 * finished with, if non-%NULL
2058 * Set a writer function which will be called to format and write out each log
2059 * message. Each program should set a writer function, or the default writer
2060 * (g_log_writer_default()) will be used.
2062 * Libraries **must not** call this function — only programs are allowed to
2063 * install a writer function, as there must be a single, central point where
2064 * log messages are formatted and outputted.
2066 * There can only be one writer function. It is an error to set more than one.
2068 * Since: 2.50
2070 void
2071 g_log_set_writer_func (GLogWriterFunc func,
2072 gpointer user_data,
2073 GDestroyNotify user_data_free)
2075 g_return_if_fail (func != NULL);
2077 g_mutex_lock (&g_messages_lock);
2078 log_writer_func = func;
2079 log_writer_user_data = user_data;
2080 log_writer_user_data_free = user_data_free;
2081 g_mutex_unlock (&g_messages_lock);
2085 * g_log_writer_supports_color:
2086 * @output_fd: output file descriptor to check
2088 * Check whether the given @output_fd file descriptor supports ANSI color
2089 * escape sequences. If so, they can safely be used when formatting log
2090 * messages.
2092 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2093 * Since: 2.50
2095 gboolean
2096 g_log_writer_supports_color (gint output_fd)
2098 #ifdef G_OS_WIN32
2099 gboolean result = FALSE;
2101 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2102 _invalid_parameter_handler oldHandler, newHandler;
2103 int prev_report_mode = 0;
2104 #endif
2106 #endif
2108 g_return_val_if_fail (output_fd >= 0, FALSE);
2110 /* FIXME: This check could easily be expanded in future to be more robust
2111 * against different types of terminal, which still vary in their color
2112 * support. cmd.exe on Windows, for example, supports ANSI colors only
2113 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2114 * The Windows 10 color support is supported on:
2115 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2116 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2117 * but not:
2118 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2119 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2121 * On UNIX systems, we probably want to use the functions from terminfo to
2122 * work out whether colors are supported.
2124 * Some examples:
2125 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2126 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2127 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2128 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2130 #ifdef G_OS_WIN32
2132 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2133 /* Set up our empty invalid parameter handler, for isatty(),
2134 * in case of bad fd's passed in for isatty(), so that
2135 * msvcrt80.dll+ won't abort the program
2137 newHandler = myInvalidParameterHandler;
2138 oldHandler = _set_invalid_parameter_handler (newHandler);
2140 /* Disable the message box for assertions. */
2141 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2142 #endif
2144 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2146 HANDLE h_output;
2147 DWORD dw_mode;
2149 if (_isatty (output_fd))
2151 h_output = (HANDLE) _get_osfhandle (output_fd);
2153 if (!GetConsoleMode (h_output, &dw_mode))
2154 goto reset_invalid_param_handler;
2156 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2157 result = TRUE;
2159 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2160 goto reset_invalid_param_handler;
2162 result = TRUE;
2166 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2167 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2168 * (bug 775468), on standard Windows consoles, such as cmd.exe
2170 if (!result)
2171 result = win32_is_pipe_tty (output_fd);
2173 reset_invalid_param_handler:
2174 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2175 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2176 _set_invalid_parameter_handler (oldHandler);
2177 #endif
2179 return result;
2180 #else
2181 return isatty (output_fd);
2182 #endif
2185 #if defined(__linux__) && !defined(__BIONIC__)
2186 static int journal_fd = -1;
2188 #ifndef SOCK_CLOEXEC
2189 #define SOCK_CLOEXEC 0
2190 #else
2191 #define HAVE_SOCK_CLOEXEC 1
2192 #endif
2194 static void
2195 open_journal (void)
2197 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2198 return;
2200 #ifndef HAVE_SOCK_CLOEXEC
2201 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2203 close (journal_fd);
2204 journal_fd = -1;
2206 #endif
2208 #endif
2211 * g_log_writer_is_journald:
2212 * @output_fd: output file descriptor to check
2214 * Check whether the given @output_fd file descriptor is a connection to the
2215 * systemd journal, or something else (like a log file or `stdout` or
2216 * `stderr`).
2218 * Invalid file descriptors are accepted and return %FALSE, which allows for
2219 * the following construct without needing any additional error handling:
2220 * |[<!-- language="C" -->
2221 * is_journald = g_log_writer_is_journald (fileno (stderr));
2222 * ]|
2224 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2225 * Since: 2.50
2227 gboolean
2228 g_log_writer_is_journald (gint output_fd)
2230 #if defined(__linux__) && !defined(__BIONIC__)
2231 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2232 * journal. See: https://github.com/systemd/systemd/issues/2473
2234 static gsize initialized;
2235 static gboolean fd_is_journal = FALSE;
2237 if (output_fd < 0)
2238 return FALSE;
2240 if (g_once_init_enter (&initialized))
2242 union {
2243 struct sockaddr_storage storage;
2244 struct sockaddr sa;
2245 struct sockaddr_un un;
2246 } addr;
2247 socklen_t addr_len = sizeof(addr);
2248 int err = getpeername (output_fd, &addr.sa, &addr_len);
2249 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2250 fd_is_journal = g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2252 g_once_init_leave (&initialized, TRUE);
2255 return fd_is_journal;
2256 #else
2257 return FALSE;
2258 #endif
2261 static void escape_string (GString *string);
2264 * g_log_writer_format_fields:
2265 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2266 * level
2267 * @fields: (array length=n_fields): key–value pairs of structured data forming
2268 * the log message
2269 * @n_fields: number of elements in the @fields array
2270 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2271 * message, %FALSE to not
2273 * Format a structured log message as a string suitable for outputting to the
2274 * terminal (or elsewhere). This will include the values of all fields it knows
2275 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2276 * documentation for g_log_structured()). It does not include values from
2277 * unknown fields.
2279 * The returned string does **not** have a trailing new-line character. It is
2280 * encoded in the character set of the current locale, which is not necessarily
2281 * UTF-8.
2283 * Returns: (transfer full): string containing the formatted log message, in
2284 * the character set of the current locale
2285 * Since: 2.50
2287 gchar *
2288 g_log_writer_format_fields (GLogLevelFlags log_level,
2289 const GLogField *fields,
2290 gsize n_fields,
2291 gboolean use_color)
2293 gsize i;
2294 const gchar *message = NULL;
2295 const gchar *log_domain = NULL;
2296 gchar level_prefix[STRING_BUFFER_SIZE];
2297 GString *gstring;
2298 gint64 now;
2299 time_t now_secs;
2300 struct tm *now_tm;
2301 gchar time_buf[128];
2303 /* Extract some common fields. */
2304 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2306 const GLogField *field = &fields[i];
2308 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2309 message = field->value;
2310 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2311 log_domain = field->value;
2314 /* Format things. */
2315 mklevel_prefix (level_prefix, log_level, use_color);
2317 gstring = g_string_new (NULL);
2318 if (log_level & ALERT_LEVELS)
2319 g_string_append (gstring, "\n");
2320 if (!log_domain)
2321 g_string_append (gstring, "** ");
2323 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2324 (log_level & G_LOG_LEVEL_MASK))
2326 const gchar *prg_name = g_get_prgname ();
2327 gulong pid = getpid ();
2329 if (prg_name == NULL)
2330 g_string_append_printf (gstring, "(process:%lu): ", pid);
2331 else
2332 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2335 if (log_domain != NULL)
2337 g_string_append (gstring, log_domain);
2338 g_string_append_c (gstring, '-');
2340 g_string_append (gstring, level_prefix);
2342 g_string_append (gstring, ": ");
2344 /* Timestamp */
2345 now = g_get_real_time ();
2346 now_secs = (time_t) (now / 1000000);
2347 now_tm = localtime (&now_secs);
2348 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2350 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2351 use_color ? "\033[34m" : "",
2352 time_buf, (gint) ((now / 1000) % 1000),
2353 color_reset (use_color));
2355 if (message == NULL)
2357 g_string_append (gstring, "(NULL) message");
2359 else
2361 GString *msg;
2362 const gchar *charset;
2364 msg = g_string_new (message);
2365 escape_string (msg);
2367 if (g_get_charset (&charset))
2369 /* charset is UTF-8 already */
2370 g_string_append (gstring, msg->str);
2372 else
2374 gchar *lstring = strdup_convert (msg->str, charset);
2375 g_string_append (gstring, lstring);
2376 g_free (lstring);
2379 g_string_free (msg, TRUE);
2382 return g_string_free (gstring, FALSE);
2385 /* Enable support for the journal if we're on a recent enough Linux */
2386 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2387 #define ENABLE_JOURNAL_SENDV
2388 #endif
2390 #ifdef ENABLE_JOURNAL_SENDV
2391 static int
2392 journal_sendv (struct iovec *iov,
2393 gsize iovlen)
2395 int buf_fd = -1;
2396 struct msghdr mh;
2397 struct sockaddr_un sa;
2398 union {
2399 struct cmsghdr cmsghdr;
2400 guint8 buf[CMSG_SPACE(sizeof(int))];
2401 } control;
2402 struct cmsghdr *cmsg;
2403 char path[] = "/dev/shm/journal.XXXXXX";
2405 if (journal_fd < 0)
2406 open_journal ();
2408 if (journal_fd < 0)
2409 return -1;
2411 memset (&sa, 0, sizeof (sa));
2412 sa.sun_family = AF_UNIX;
2413 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2414 return -1;
2416 memset (&mh, 0, sizeof (mh));
2417 mh.msg_name = &sa;
2418 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2419 mh.msg_iov = iov;
2420 mh.msg_iovlen = iovlen;
2422 retry:
2423 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2424 return 0;
2426 if (errno == EINTR)
2427 goto retry;
2429 if (errno != EMSGSIZE && errno != ENOBUFS)
2430 return -1;
2432 /* Message was too large, so dump to temporary file
2433 * and pass an FD to the journal
2435 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2436 return -1;
2438 if (unlink (path) < 0)
2440 close (buf_fd);
2441 return -1;
2444 if (writev (buf_fd, iov, iovlen) < 0)
2446 close (buf_fd);
2447 return -1;
2450 mh.msg_iov = NULL;
2451 mh.msg_iovlen = 0;
2453 memset (&control, 0, sizeof (control));
2454 mh.msg_control = &control;
2455 mh.msg_controllen = sizeof (control);
2457 cmsg = CMSG_FIRSTHDR (&mh);
2458 cmsg->cmsg_level = SOL_SOCKET;
2459 cmsg->cmsg_type = SCM_RIGHTS;
2460 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2461 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2463 mh.msg_controllen = cmsg->cmsg_len;
2465 retry2:
2466 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2467 return 0;
2469 if (errno == EINTR)
2470 goto retry2;
2472 return -1;
2474 #endif /* ENABLE_JOURNAL_SENDV */
2477 * g_log_writer_journald:
2478 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2479 * level
2480 * @fields: (array length=n_fields): key–value pairs of structured data forming
2481 * the log message
2482 * @n_fields: number of elements in the @fields array
2483 * @user_data: user data passed to g_log_set_writer_func()
2485 * Format a structured log message and send it to the systemd journal as a set
2486 * of key–value pairs. All fields are sent to the journal, but if a field has
2487 * length zero (indicating program-specific data) then only its key will be
2488 * sent.
2490 * This is suitable for use as a #GLogWriterFunc.
2492 * If GLib has been compiled without systemd support, this function is still
2493 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2495 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2496 * Since: 2.50
2498 GLogWriterOutput
2499 g_log_writer_journald (GLogLevelFlags log_level,
2500 const GLogField *fields,
2501 gsize n_fields,
2502 gpointer user_data)
2504 #ifdef ENABLE_JOURNAL_SENDV
2505 const char equals = '=';
2506 const char newline = '\n';
2507 gsize i, k;
2508 struct iovec *iov, *v;
2509 char *buf;
2510 gint retval;
2512 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2513 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2515 /* According to systemd.journal-fields(7), the journal allows fields in any
2516 * format (including arbitrary binary), but expects text fields to be UTF-8.
2517 * This is great, because we require input strings to be in UTF-8, so no
2518 * conversion is necessary and we don’t need to care about the current
2519 * locale’s character set.
2522 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2523 buf = g_alloca (32 * n_fields);
2525 k = 0;
2526 v = iov;
2527 for (i = 0; i < n_fields; i++)
2529 guint64 length;
2530 gboolean binary;
2532 if (fields[i].length < 0)
2534 length = strlen (fields[i].value);
2535 binary = strchr (fields[i].value, '\n') != NULL;
2537 else
2539 length = fields[i].length;
2540 binary = TRUE;
2543 if (binary)
2545 guint64 nstr;
2547 v[0].iov_base = (gpointer)fields[i].key;
2548 v[0].iov_len = strlen (fields[i].key);
2550 v[1].iov_base = (gpointer)&newline;
2551 v[1].iov_len = 1;
2553 nstr = GUINT64_TO_LE(length);
2554 memcpy (&buf[k], &nstr, sizeof (nstr));
2556 v[2].iov_base = &buf[k];
2557 v[2].iov_len = sizeof (nstr);
2558 v += 3;
2559 k += sizeof (nstr);
2561 else
2563 v[0].iov_base = (gpointer)fields[i].key;
2564 v[0].iov_len = strlen (fields[i].key);
2566 v[1].iov_base = (gpointer)&equals;
2567 v[1].iov_len = 1;
2568 v += 2;
2571 v[0].iov_base = (gpointer)fields[i].value;
2572 v[0].iov_len = length;
2574 v[1].iov_base = (gpointer)&newline;
2575 v[1].iov_len = 1;
2576 v += 2;
2579 retval = journal_sendv (iov, v - iov);
2581 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2582 #else
2583 return G_LOG_WRITER_UNHANDLED;
2584 #endif /* ENABLE_JOURNAL_SENDV */
2588 * g_log_writer_standard_streams:
2589 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2590 * level
2591 * @fields: (array length=n_fields): key–value pairs of structured data forming
2592 * the log message
2593 * @n_fields: number of elements in the @fields array
2594 * @user_data: user data passed to g_log_set_writer_func()
2596 * Format a structured log message and print it to either `stdout` or `stderr`,
2597 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2598 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2599 * which are understood by this function are included in the formatted string
2600 * which is printed.
2602 * If the output stream supports ANSI color escape sequences, they will be used
2603 * in the output.
2605 * A trailing new-line character is added to the log message when it is printed.
2607 * This is suitable for use as a #GLogWriterFunc.
2609 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2610 * Since: 2.50
2612 GLogWriterOutput
2613 g_log_writer_standard_streams (GLogLevelFlags log_level,
2614 const GLogField *fields,
2615 gsize n_fields,
2616 gpointer user_data)
2618 FILE *stream;
2619 gchar *out = NULL; /* in the current locale’s character set */
2621 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2622 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2624 stream = log_level_to_file (log_level);
2625 if (!stream || fileno (stream) < 0)
2626 return G_LOG_WRITER_UNHANDLED;
2628 out = g_log_writer_format_fields (log_level, fields, n_fields,
2629 g_log_writer_supports_color (fileno (stream)));
2630 _g_fprintf (stream, "%s\n", out);
2631 fflush (stream);
2632 g_free (out);
2634 return G_LOG_WRITER_HANDLED;
2637 /* The old g_log() API is implemented in terms of the new structured log API.
2638 * However, some of the checks do not line up between the two APIs: the
2639 * structured API only handles fatalness of messages for log levels; the old API
2640 * handles it per-domain as well. Consequently, we need to disable fatalness
2641 * handling in the structured log API when called from the old g_log() API.
2643 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2644 * the first field to g_log_structured_array(), if that is the case.
2646 static gboolean
2647 log_is_old_api (const GLogField *fields,
2648 gsize n_fields)
2650 return (n_fields >= 1 &&
2651 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2652 g_strcmp0 (fields[0].value, "1") == 0);
2656 * g_log_writer_default:
2657 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2658 * level
2659 * @fields: (array length=n_fields): key–value pairs of structured data forming
2660 * the log message
2661 * @n_fields: number of elements in the @fields array
2662 * @user_data: user data passed to g_log_set_writer_func()
2664 * Format a structured log message and output it to the default log destination
2665 * for the platform. On Linux, this is typically the systemd journal, falling
2666 * back to `stdout` or `stderr` if running from the terminal or if output is
2667 * being redirected to a file.
2669 * Support for other platform-specific logging mechanisms may be added in
2670 * future. Distributors of GLib may modify this function to impose their own
2671 * (documented) platform-specific log writing policies.
2673 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2674 * if no other is set using g_log_set_writer_func().
2676 * As with g_log_default_handler(), this function drops debug and informational
2677 * messages unless their log domain (or `all`) is listed in the space-separated
2678 * `G_MESSAGES_DEBUG` environment variable.
2680 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2681 * Since: 2.50
2683 GLogWriterOutput
2684 g_log_writer_default (GLogLevelFlags log_level,
2685 const GLogField *fields,
2686 gsize n_fields,
2687 gpointer user_data)
2689 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2690 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2692 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2693 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2695 const gchar *domains, *log_domain = NULL;
2696 gsize i;
2698 domains = g_getenv ("G_MESSAGES_DEBUG");
2700 if ((log_level & INFO_LEVELS) == 0 ||
2701 domains == NULL)
2702 return G_LOG_WRITER_HANDLED;
2704 for (i = 0; i < n_fields; i++)
2706 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2708 log_domain = fields[i].value;
2709 break;
2713 if (strcmp (domains, "all") != 0 &&
2714 (log_domain == NULL || !strstr (domains, log_domain)))
2715 return G_LOG_WRITER_HANDLED;
2718 /* Mark messages as fatal if they have a level set in
2719 * g_log_set_always_fatal().
2721 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2722 log_level |= G_LOG_FLAG_FATAL;
2724 /* Try logging to the systemd journal as first choice. */
2725 if (g_log_writer_is_journald (fileno (stderr)) &&
2726 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2727 G_LOG_WRITER_HANDLED)
2728 goto handled;
2730 /* FIXME: Add support for the Windows log. */
2732 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2733 G_LOG_WRITER_HANDLED)
2734 goto handled;
2736 return G_LOG_WRITER_UNHANDLED;
2738 handled:
2739 /* Abort if the message was fatal. */
2740 if (log_level & G_LOG_FLAG_FATAL)
2742 #ifdef G_OS_WIN32
2743 if (!g_test_initialized ())
2745 gchar *locale_msg = NULL;
2747 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2748 MessageBox (NULL, locale_msg, NULL,
2749 MB_ICONERROR | MB_SETFOREGROUND);
2750 g_free (locale_msg);
2752 #endif /* !G_OS_WIN32 */
2754 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2757 return G_LOG_WRITER_HANDLED;
2760 static GLogWriterOutput
2761 _g_log_writer_fallback (GLogLevelFlags log_level,
2762 const GLogField *fields,
2763 gsize n_fields,
2764 gpointer user_data)
2766 FILE *stream;
2767 gsize i;
2769 /* we cannot call _any_ GLib functions in this fallback handler,
2770 * which is why we skip UTF-8 conversion, etc.
2771 * since we either recursed or ran out of memory, we're in a pretty
2772 * pathologic situation anyways, what we can do is giving the
2773 * the process ID unconditionally however.
2776 stream = log_level_to_file (log_level);
2778 for (i = 0; i < n_fields; i++)
2780 const GLogField *field = &fields[i];
2782 /* Only print fields we definitely recognise, otherwise we could end up
2783 * printing a random non-string pointer provided by the user to be
2784 * interpreted by their writer function.
2786 if (strcmp (field->key, "MESSAGE") != 0 &&
2787 strcmp (field->key, "MESSAGE_ID") != 0 &&
2788 strcmp (field->key, "PRIORITY") != 0 &&
2789 strcmp (field->key, "CODE_FILE") != 0 &&
2790 strcmp (field->key, "CODE_LINE") != 0 &&
2791 strcmp (field->key, "CODE_FUNC") != 0 &&
2792 strcmp (field->key, "ERRNO") != 0 &&
2793 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2794 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2795 strcmp (field->key, "SYSLOG_PID") != 0 &&
2796 strcmp (field->key, "GLIB_DOMAIN") != 0)
2797 continue;
2799 write_string (stream, field->key);
2800 write_string (stream, "=");
2801 write_string_sized (stream, field->value, field->length);
2804 #ifndef G_OS_WIN32
2806 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2808 format_unsigned (pid_string, getpid (), 10);
2809 write_string (stream, "_PID=");
2810 write_string (stream, pid_string);
2812 #endif
2814 return G_LOG_WRITER_HANDLED;
2818 * g_return_if_fail_warning: (skip)
2819 * @log_domain: (nullable):
2820 * @pretty_function:
2821 * @expression: (nullable):
2823 void
2824 g_return_if_fail_warning (const char *log_domain,
2825 const char *pretty_function,
2826 const char *expression)
2828 g_log (log_domain,
2829 G_LOG_LEVEL_CRITICAL,
2830 "%s: assertion '%s' failed",
2831 pretty_function,
2832 expression);
2836 * g_warn_message: (skip)
2837 * @domain: (nullable):
2838 * @file:
2839 * @line:
2840 * @func:
2841 * @warnexpr: (nullable):
2843 void
2844 g_warn_message (const char *domain,
2845 const char *file,
2846 int line,
2847 const char *func,
2848 const char *warnexpr)
2850 char *s, lstr[32];
2851 g_snprintf (lstr, 32, "%d", line);
2852 if (warnexpr)
2853 s = g_strconcat ("(", file, ":", lstr, "):",
2854 func, func[0] ? ":" : "",
2855 " runtime check failed: (", warnexpr, ")", NULL);
2856 else
2857 s = g_strconcat ("(", file, ":", lstr, "):",
2858 func, func[0] ? ":" : "",
2859 " ", "code should not be reached", NULL);
2860 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2861 g_free (s);
2864 void
2865 g_assert_warning (const char *log_domain,
2866 const char *file,
2867 const int line,
2868 const char *pretty_function,
2869 const char *expression)
2871 if (expression)
2872 g_log (log_domain,
2873 G_LOG_LEVEL_ERROR,
2874 "file %s: line %d (%s): assertion failed: (%s)",
2875 file,
2876 line,
2877 pretty_function,
2878 expression);
2879 else
2880 g_log (log_domain,
2881 G_LOG_LEVEL_ERROR,
2882 "file %s: line %d (%s): should not be reached",
2883 file,
2884 line,
2885 pretty_function);
2886 _g_log_abort (FALSE);
2887 g_abort ();
2891 * g_test_expect_message:
2892 * @log_domain: (nullable): the log domain of the message
2893 * @log_level: the log level of the message
2894 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2896 * Indicates that a message with the given @log_domain and @log_level,
2897 * with text matching @pattern, is expected to be logged. When this
2898 * message is logged, it will not be printed, and the test case will
2899 * not abort.
2901 * This API may only be used with the old logging API (g_log() without
2902 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2903 * API. See [Testing for Messages][testing-for-messages].
2905 * Use g_test_assert_expected_messages() to assert that all
2906 * previously-expected messages have been seen and suppressed.
2908 * You can call this multiple times in a row, if multiple messages are
2909 * expected as a result of a single call. (The messages must appear in
2910 * the same order as the calls to g_test_expect_message().)
2912 * For example:
2914 * |[<!-- language="C" -->
2915 * // g_main_context_push_thread_default() should fail if the
2916 * // context is already owned by another thread.
2917 * g_test_expect_message (G_LOG_DOMAIN,
2918 * G_LOG_LEVEL_CRITICAL,
2919 * "assertion*acquired_context*failed");
2920 * g_main_context_push_thread_default (bad_context);
2921 * g_test_assert_expected_messages ();
2922 * ]|
2924 * Note that you cannot use this to test g_error() messages, since
2925 * g_error() intentionally never returns even if the program doesn't
2926 * abort; use g_test_trap_subprocess() in this case.
2928 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2929 * expected via g_test_expect_message() then they will be ignored.
2931 * Since: 2.34
2933 void
2934 g_test_expect_message (const gchar *log_domain,
2935 GLogLevelFlags log_level,
2936 const gchar *pattern)
2938 GTestExpectedMessage *expected;
2940 g_return_if_fail (log_level != 0);
2941 g_return_if_fail (pattern != NULL);
2942 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2944 expected = g_new (GTestExpectedMessage, 1);
2945 expected->log_domain = g_strdup (log_domain);
2946 expected->log_level = log_level;
2947 expected->pattern = g_strdup (pattern);
2949 expected_messages = g_slist_append (expected_messages, expected);
2952 void
2953 g_test_assert_expected_messages_internal (const char *domain,
2954 const char *file,
2955 int line,
2956 const char *func)
2958 if (expected_messages)
2960 GTestExpectedMessage *expected;
2961 gchar level_prefix[STRING_BUFFER_SIZE];
2962 gchar *message;
2964 expected = expected_messages->data;
2966 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2967 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2968 expected->log_domain ? expected->log_domain : "**",
2969 level_prefix, expected->pattern);
2970 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2971 g_free (message);
2976 * g_test_assert_expected_messages:
2978 * Asserts that all messages previously indicated via
2979 * g_test_expect_message() have been seen and suppressed.
2981 * This API may only be used with the old logging API (g_log() without
2982 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2983 * API. See [Testing for Messages][testing-for-messages].
2985 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2986 * expected via g_test_expect_message() then they will be ignored.
2988 * Since: 2.34
2991 void
2992 _g_log_fallback_handler (const gchar *log_domain,
2993 GLogLevelFlags log_level,
2994 const gchar *message,
2995 gpointer unused_data)
2997 gchar level_prefix[STRING_BUFFER_SIZE];
2998 #ifndef G_OS_WIN32
2999 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
3000 #endif
3001 FILE *stream;
3003 /* we cannot call _any_ GLib functions in this fallback handler,
3004 * which is why we skip UTF-8 conversion, etc.
3005 * since we either recursed or ran out of memory, we're in a pretty
3006 * pathologic situation anyways, what we can do is giving the
3007 * the process ID unconditionally however.
3010 stream = mklevel_prefix (level_prefix, log_level, FALSE);
3011 if (!message)
3012 message = "(NULL) message";
3014 #ifndef G_OS_WIN32
3015 format_unsigned (pid_string, getpid (), 10);
3016 #endif
3018 if (log_domain)
3019 write_string (stream, "\n");
3020 else
3021 write_string (stream, "\n** ");
3023 #ifndef G_OS_WIN32
3024 write_string (stream, "(process:");
3025 write_string (stream, pid_string);
3026 write_string (stream, "): ");
3027 #endif
3029 if (log_domain)
3031 write_string (stream, log_domain);
3032 write_string (stream, "-");
3034 write_string (stream, level_prefix);
3035 write_string (stream, ": ");
3036 write_string (stream, message);
3039 static void
3040 escape_string (GString *string)
3042 const char *p = string->str;
3043 gunichar wc;
3045 while (p < string->str + string->len)
3047 gboolean safe;
3049 wc = g_utf8_get_char_validated (p, -1);
3050 if (wc == (gunichar)-1 || wc == (gunichar)-2)
3052 gchar *tmp;
3053 guint pos;
3055 pos = p - string->str;
3057 /* Emit invalid UTF-8 as hex escapes
3059 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
3060 g_string_erase (string, pos, 1);
3061 g_string_insert (string, pos, tmp);
3063 p = string->str + (pos + 4); /* Skip over escape sequence */
3065 g_free (tmp);
3066 continue;
3068 if (wc == '\r')
3070 safe = *(p + 1) == '\n';
3072 else
3074 safe = CHAR_IS_SAFE (wc);
3077 if (!safe)
3079 gchar *tmp;
3080 guint pos;
3082 pos = p - string->str;
3084 /* Largest char we escape is 0x0a, so we don't have to worry
3085 * about 8-digit \Uxxxxyyyy
3087 tmp = g_strdup_printf ("\\u%04x", wc);
3088 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3089 g_string_insert (string, pos, tmp);
3090 g_free (tmp);
3092 p = string->str + (pos + 6); /* Skip over escape sequence */
3094 else
3095 p = g_utf8_next_char (p);
3100 * g_log_default_handler:
3101 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3102 * default "" application domain
3103 * @log_level: the level of the message
3104 * @message: (nullable): the message
3105 * @unused_data: (nullable): data passed from g_log() which is unused
3107 * The default log handler set up by GLib; g_log_set_default_handler()
3108 * allows to install an alternate default log handler.
3109 * This is used if no log handler has been set for the particular log
3110 * domain and log level combination. It outputs the message to stderr
3111 * or stdout and if the log level is fatal it calls abort(). It automatically
3112 * prints a new-line character after the message, so one does not need to be
3113 * manually included in @message.
3115 * The behavior of this log handler can be influenced by a number of
3116 * environment variables:
3118 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3119 * messages should be prefixed by the program name and PID of the
3120 * aplication.
3122 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3123 * which debug and informational messages are printed. By default
3124 * these messages are not printed.
3126 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3127 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3128 * the rest.
3130 * This has no effect if structured logging is enabled; see
3131 * [Using Structured Logging][using-structured-logging].
3133 void
3134 g_log_default_handler (const gchar *log_domain,
3135 GLogLevelFlags log_level,
3136 const gchar *message,
3137 gpointer unused_data)
3139 GLogField fields[4];
3140 int n_fields = 0;
3142 /* we can be called externally with recursion for whatever reason */
3143 if (log_level & G_LOG_FLAG_RECURSION)
3145 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3146 return;
3149 fields[0].key = "GLIB_OLD_LOG_API";
3150 fields[0].value = "1";
3151 fields[0].length = -1;
3152 n_fields++;
3154 fields[1].key = "MESSAGE";
3155 fields[1].value = message;
3156 fields[1].length = -1;
3157 n_fields++;
3159 fields[2].key = "PRIORITY";
3160 fields[2].value = log_level_to_priority (log_level);
3161 fields[2].length = -1;
3162 n_fields++;
3164 if (log_domain)
3166 fields[3].key = "GLIB_DOMAIN";
3167 fields[3].value = log_domain;
3168 fields[3].length = -1;
3169 n_fields++;
3172 /* Print out via the structured log API, but drop any fatal flags since we
3173 * have already handled them. The fatal handling in the structured logging
3174 * API is more coarse-grained than in the old g_log() API, so we don't want
3175 * to use it here.
3177 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3181 * g_set_print_handler:
3182 * @func: the new print handler
3184 * Sets the print handler.
3186 * Any messages passed to g_print() will be output via
3187 * the new handler. The default handler simply outputs
3188 * the message to stdout. By providing your own handler
3189 * you can redirect the output, to a GTK+ widget or a
3190 * log file for example.
3192 * Returns: the old print handler
3194 GPrintFunc
3195 g_set_print_handler (GPrintFunc func)
3197 GPrintFunc old_print_func;
3199 g_mutex_lock (&g_messages_lock);
3200 old_print_func = glib_print_func;
3201 glib_print_func = func;
3202 g_mutex_unlock (&g_messages_lock);
3204 return old_print_func;
3208 * g_print:
3209 * @format: the message format. See the printf() documentation
3210 * @...: the parameters to insert into the format string
3212 * Outputs a formatted message via the print handler.
3213 * The default print handler simply outputs the message to stdout, without
3214 * appending a trailing new-line character. Typically, @format should end with
3215 * its own new-line character.
3217 * g_print() should not be used from within libraries for debugging
3218 * messages, since it may be redirected by applications to special
3219 * purpose message windows or even files. Instead, libraries should
3220 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3221 * g_warning() and g_error().
3223 void
3224 g_print (const gchar *format,
3225 ...)
3227 va_list args;
3228 gchar *string;
3229 GPrintFunc local_glib_print_func;
3231 g_return_if_fail (format != NULL);
3233 va_start (args, format);
3234 string = g_strdup_vprintf (format, args);
3235 va_end (args);
3237 g_mutex_lock (&g_messages_lock);
3238 local_glib_print_func = glib_print_func;
3239 g_mutex_unlock (&g_messages_lock);
3241 if (local_glib_print_func)
3242 local_glib_print_func (string);
3243 else
3245 const gchar *charset;
3247 if (g_get_charset (&charset))
3248 fputs (string, stdout); /* charset is UTF-8 already */
3249 else
3251 gchar *lstring = strdup_convert (string, charset);
3253 fputs (lstring, stdout);
3254 g_free (lstring);
3256 fflush (stdout);
3258 g_free (string);
3262 * g_set_printerr_handler:
3263 * @func: the new error message handler
3265 * Sets the handler for printing error messages.
3267 * Any messages passed to g_printerr() will be output via
3268 * the new handler. The default handler simply outputs the
3269 * message to stderr. By providing your own handler you can
3270 * redirect the output, to a GTK+ widget or a log file for
3271 * example.
3273 * Returns: the old error message handler
3275 GPrintFunc
3276 g_set_printerr_handler (GPrintFunc func)
3278 GPrintFunc old_printerr_func;
3280 g_mutex_lock (&g_messages_lock);
3281 old_printerr_func = glib_printerr_func;
3282 glib_printerr_func = func;
3283 g_mutex_unlock (&g_messages_lock);
3285 return old_printerr_func;
3289 * g_printerr:
3290 * @format: the message format. See the printf() documentation
3291 * @...: the parameters to insert into the format string
3293 * Outputs a formatted message via the error message handler.
3294 * The default handler simply outputs the message to stderr, without appending
3295 * a trailing new-line character. Typically, @format should end with its own
3296 * new-line character.
3298 * g_printerr() should not be used from within libraries.
3299 * Instead g_log() or g_log_structured() should be used, or the convenience
3300 * macros g_message(), g_warning() and g_error().
3302 void
3303 g_printerr (const gchar *format,
3304 ...)
3306 va_list args;
3307 gchar *string;
3308 GPrintFunc local_glib_printerr_func;
3310 g_return_if_fail (format != NULL);
3312 va_start (args, format);
3313 string = g_strdup_vprintf (format, args);
3314 va_end (args);
3316 g_mutex_lock (&g_messages_lock);
3317 local_glib_printerr_func = glib_printerr_func;
3318 g_mutex_unlock (&g_messages_lock);
3320 if (local_glib_printerr_func)
3321 local_glib_printerr_func (string);
3322 else
3324 const gchar *charset;
3326 if (g_get_charset (&charset))
3327 fputs (string, stderr); /* charset is UTF-8 already */
3328 else
3330 gchar *lstring = strdup_convert (string, charset);
3332 fputs (lstring, stderr);
3333 g_free (lstring);
3335 fflush (stderr);
3337 g_free (string);
3341 * g_printf_string_upper_bound:
3342 * @format: the format string. See the printf() documentation
3343 * @args: the parameters to be inserted into the format string
3345 * Calculates the maximum space needed to store the output
3346 * of the sprintf() function.
3348 * Returns: the maximum space needed to store the formatted string
3350 gsize
3351 g_printf_string_upper_bound (const gchar *format,
3352 va_list args)
3354 gchar c;
3355 return _g_vsnprintf (&c, 1, format, args) + 1;