Merge branch 'g-clear-pointer-no-side-effects' into 'master'
[glib.git] / glib / gmessages.c
blob569fe2cf882598eda768036721b45d9ffb6e7347
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 #if defined (_MSC_VER) && (_MSC_VER >=1400)
215 /* This is ugly, but we need it for isatty() in case we have bad fd's,
216 * otherwise Windows will abort() the program on msvcrt80.dll and later
218 #include <crtdbg.h>
220 _GLIB_EXTERN void
221 myInvalidParameterHandler(const wchar_t *expression,
222 const wchar_t *function,
223 const wchar_t *file,
224 unsigned int line,
225 uintptr_t pReserved)
228 #endif
230 #include "gwin32.h"
231 #endif
234 * G_LOG_DOMAIN:
236 * Defines the log domain. See [Log Domains](#log-domains).
238 * Libraries should define this so that any messages
239 * which they log can be differentiated from messages from other
240 * libraries and application code. But be careful not to define
241 * it in any public header files.
243 * Log domains must be unique, and it is recommended that they are the
244 * application or library name, optionally followed by a hyphen and a sub-domain
245 * name. For example, `bloatpad` or `bloatpad-io`.
247 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
248 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
249 * environment variable.
251 * For example, GTK+ uses this in its `Makefile.am`:
252 * |[
253 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
254 * ]|
256 * Applications can choose to leave it as the default %NULL (or `""`)
257 * domain. However, defining the domain offers the same advantages as
258 * above.
264 * G_LOG_FATAL_MASK:
266 * GLib log levels that are considered fatal by default.
268 * This is not used if structured logging is enabled; see
269 * [Using Structured Logging][using-structured-logging].
273 * GLogFunc:
274 * @log_domain: the log domain of the message
275 * @log_level: the log level of the message (including the
276 * fatal and recursion flags)
277 * @message: the message to process
278 * @user_data: user data, set in g_log_set_handler()
280 * Specifies the prototype of log handler functions.
282 * The default log handler, g_log_default_handler(), automatically appends a
283 * new-line character to @message when printing it. It is advised that any
284 * custom log handler functions behave similarly, so that logging calls in user
285 * code do not need modifying to add a new-line character to the message if the
286 * log handler is changed.
288 * This is not used if structured logging is enabled; see
289 * [Using Structured Logging][using-structured-logging].
293 * GLogLevelFlags:
294 * @G_LOG_FLAG_RECURSION: internal flag
295 * @G_LOG_FLAG_FATAL: internal flag
296 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
297 * This level is also used for messages produced by g_assert().
298 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
299 * g_critical().
300 * This level is also used for messages produced by g_return_if_fail()
301 * and g_return_val_if_fail().
302 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
303 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
304 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
305 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
306 * @G_LOG_LEVEL_MASK: a mask including all log levels
308 * Flags specifying the level of log messages.
310 * It is possible to change how GLib treats messages of the various
311 * levels using g_log_set_handler() and g_log_set_fatal_mask().
315 * G_LOG_LEVEL_USER_SHIFT:
317 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
318 * Higher bits can be used for user-defined log levels.
322 * g_message:
323 * @...: format string, followed by parameters to insert
324 * into the format string (as with printf())
326 * A convenience function/macro to log a normal message.
328 * If g_log_default_handler() is used as the log handler function, a new-line
329 * character will automatically be appended to @..., and need not be entered
330 * manually.
332 * If structured logging is enabled, this will use g_log_structured();
333 * otherwise it will use g_log(). See
334 * [Using Structured Logging][using-structured-logging].
338 * g_warning:
339 * @...: format string, followed by parameters to insert
340 * into the format string (as with printf())
342 * A convenience function/macro to log a warning message. The message should
343 * typically *not* be translated to the user's language.
345 * This is not intended for end user error reporting. Use of #GError is
346 * preferred for that instead, as it allows calling functions to perform actions
347 * conditional on the type of error.
349 * Warning messages are intended to be used in the event of unexpected
350 * external conditions (system misconfiguration, missing files,
351 * other trusted programs violating protocol, invalid contents in
352 * trusted files, etc.)
354 * If attempting to deal with programmer errors (for example, incorrect function
355 * parameters) then you should use %G_LOG_LEVEL_CRITICAL instead.
357 * g_warn_if_reached() and g_warn_if_fail() log at %G_LOG_LEVEL_WARNING.
359 * You can make warnings fatal at runtime by setting the `G_DEBUG`
360 * environment variable (see
361 * [Running GLib Applications](glib-running.html)):
363 * |[
364 * G_DEBUG=fatal-warnings gdb ./my-program
365 * ]|
367 * Any unrelated failures can be skipped over in
368 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
370 * If g_log_default_handler() is used as the log handler function,
371 * a newline character will automatically be appended to @..., and
372 * need not be entered manually.
374 * If structured logging is enabled, this will use g_log_structured();
375 * otherwise it will use g_log(). See
376 * [Using Structured Logging][using-structured-logging].
380 * g_critical:
381 * @...: format string, followed by parameters to insert
382 * into the format string (as with printf())
384 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
386 * Critical warnings are intended to be used in the event of an error
387 * that originated in the current process (a programmer error).
388 * Logging of a critical error is by definition an indication of a bug
389 * somewhere in the current program (or its libraries).
391 * g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and
392 * g_return_val_if_reached() log at %G_LOG_LEVEL_CRITICAL.
394 * You can make critical warnings fatal at runtime by
395 * setting the `G_DEBUG` environment variable (see
396 * [Running GLib Applications](glib-running.html)):
398 * |[
399 * G_DEBUG=fatal-warnings gdb ./my-program
400 * ]|
402 * You can also use g_log_set_always_fatal().
404 * Any unrelated failures can be skipped over in
405 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
407 * The message should typically *not* be translated to the
408 * user's language.
410 * If g_log_default_handler() is used as the log handler function, a new-line
411 * character will automatically be appended to @..., and need not be entered
412 * manually.
414 * If structured logging is enabled, this will use g_log_structured();
415 * otherwise it will use g_log(). See
416 * [Using Structured Logging][using-structured-logging].
420 * g_error:
421 * @...: format string, followed by parameters to insert
422 * into the format string (as with printf())
424 * A convenience function/macro to log an error message. The message should
425 * typically *not* be translated to the user's language.
427 * This is not intended for end user error reporting. Use of #GError is
428 * preferred for that instead, as it allows calling functions to perform actions
429 * conditional on the type of error.
431 * Error messages are always fatal, resulting in a call to G_BREAKPOINT()
432 * to terminate the application. This function will
433 * result in a core dump; don't use it for errors you expect.
434 * Using this function indicates a bug in your program, i.e.
435 * an assertion failure.
437 * If g_log_default_handler() is used as the log handler function, a new-line
438 * character will automatically be appended to @..., and need not be entered
439 * manually.
441 * If structured logging is enabled, this will use g_log_structured();
442 * otherwise it will use g_log(). See
443 * [Using Structured Logging][using-structured-logging].
447 * g_info:
448 * @...: format string, followed by parameters to insert
449 * into the format string (as with printf())
451 * A convenience function/macro to log an informational message. Seldom used.
453 * If g_log_default_handler() is used as the log handler function, a new-line
454 * character will automatically be appended to @..., and need not be entered
455 * manually.
457 * Such messages are suppressed by the g_log_default_handler() and
458 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
459 * set appropriately.
461 * If structured logging is enabled, this will use g_log_structured();
462 * otherwise it will use g_log(). See
463 * [Using Structured Logging][using-structured-logging].
465 * Since: 2.40
469 * g_debug:
470 * @...: format string, followed by parameters to insert
471 * into the format string (as with printf())
473 * A convenience function/macro to log a debug message. The message should
474 * typically *not* be translated to the user's language.
476 * If g_log_default_handler() is used as the log handler function, a new-line
477 * character will automatically be appended to @..., and need not be entered
478 * manually.
480 * Such messages are suppressed by the g_log_default_handler() and
481 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
482 * set appropriately.
484 * If structured logging is enabled, this will use g_log_structured();
485 * otherwise it will use g_log(). See
486 * [Using Structured Logging][using-structured-logging].
488 * Since: 2.6
491 /* --- structures --- */
492 typedef struct _GLogDomain GLogDomain;
493 typedef struct _GLogHandler GLogHandler;
494 struct _GLogDomain
496 gchar *log_domain;
497 GLogLevelFlags fatal_mask;
498 GLogHandler *handlers;
499 GLogDomain *next;
501 struct _GLogHandler
503 guint id;
504 GLogLevelFlags log_level;
505 GLogFunc log_func;
506 gpointer data;
507 GDestroyNotify destroy;
508 GLogHandler *next;
512 /* --- variables --- */
513 static GMutex g_messages_lock;
514 static GLogDomain *g_log_domains = NULL;
515 static GPrintFunc glib_print_func = NULL;
516 static GPrintFunc glib_printerr_func = NULL;
517 static GPrivate g_log_depth;
518 static GPrivate g_log_structured_depth;
519 static GLogFunc default_log_func = g_log_default_handler;
520 static gpointer default_log_data = NULL;
521 static GTestLogFatalFunc fatal_log_func = NULL;
522 static gpointer fatal_log_data;
523 static GLogWriterFunc log_writer_func = g_log_writer_default;
524 static gpointer log_writer_user_data = NULL;
525 static GDestroyNotify log_writer_user_data_free = NULL;
527 /* --- functions --- */
529 static void _g_log_abort (gboolean breakpoint);
531 static void
532 _g_log_abort (gboolean breakpoint)
534 gboolean debugger_present;
536 if (g_test_subprocess ())
538 /* If this is a test case subprocess then it probably caused
539 * this error message on purpose, so just exit() rather than
540 * abort()ing, to avoid triggering any system crash-reporting
541 * daemon.
543 _exit (1);
546 #ifdef G_OS_WIN32
547 debugger_present = IsDebuggerPresent ();
548 #else
549 /* Assume GDB is attached. */
550 debugger_present = TRUE;
551 #endif /* !G_OS_WIN32 */
553 if (debugger_present && breakpoint)
554 G_BREAKPOINT ();
555 else
556 g_abort ();
559 #ifdef G_OS_WIN32
560 static gboolean win32_keep_fatal_message = FALSE;
562 /* This default message will usually be overwritten. */
563 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
564 * called with huge strings, is it?
566 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
567 static gchar *fatal_msg_ptr = fatal_msg_buf;
569 #undef write
570 static inline int
571 dowrite (int fd,
572 const void *buf,
573 unsigned int len)
575 if (win32_keep_fatal_message)
577 memcpy (fatal_msg_ptr, buf, len);
578 fatal_msg_ptr += len;
579 *fatal_msg_ptr = 0;
580 return len;
583 write (fd, buf, len);
585 return len;
587 #define write(fd, buf, len) dowrite(fd, buf, len)
589 #endif
591 static void
592 write_string (FILE *stream,
593 const gchar *string)
595 fputs (string, stream);
598 static void
599 write_string_sized (FILE *stream,
600 const gchar *string,
601 gssize length)
603 /* Is it nul-terminated? */
604 if (length < 0)
605 write_string (stream, string);
606 else
607 fwrite (string, 1, length, stream);
610 static GLogDomain*
611 g_log_find_domain_L (const gchar *log_domain)
613 GLogDomain *domain;
615 domain = g_log_domains;
616 while (domain)
618 if (strcmp (domain->log_domain, log_domain) == 0)
619 return domain;
620 domain = domain->next;
622 return NULL;
625 static GLogDomain*
626 g_log_domain_new_L (const gchar *log_domain)
628 GLogDomain *domain;
630 domain = g_new (GLogDomain, 1);
631 domain->log_domain = g_strdup (log_domain);
632 domain->fatal_mask = G_LOG_FATAL_MASK;
633 domain->handlers = NULL;
635 domain->next = g_log_domains;
636 g_log_domains = domain;
638 return domain;
641 static void
642 g_log_domain_check_free_L (GLogDomain *domain)
644 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
645 domain->handlers == NULL)
647 GLogDomain *last, *work;
649 last = NULL;
651 work = g_log_domains;
652 while (work)
654 if (work == domain)
656 if (last)
657 last->next = domain->next;
658 else
659 g_log_domains = domain->next;
660 g_free (domain->log_domain);
661 g_free (domain);
662 break;
664 last = work;
665 work = last->next;
670 static GLogFunc
671 g_log_domain_get_handler_L (GLogDomain *domain,
672 GLogLevelFlags log_level,
673 gpointer *data)
675 if (domain && log_level)
677 GLogHandler *handler;
679 handler = domain->handlers;
680 while (handler)
682 if ((handler->log_level & log_level) == log_level)
684 *data = handler->data;
685 return handler->log_func;
687 handler = handler->next;
691 *data = default_log_data;
692 return default_log_func;
696 * g_log_set_always_fatal:
697 * @fatal_mask: the mask containing bits set for each level
698 * of error which is to be fatal
700 * Sets the message levels which are always fatal, in any log domain.
701 * When a message with any of these levels is logged the program terminates.
702 * You can only set the levels defined by GLib to be fatal.
703 * %G_LOG_LEVEL_ERROR is always fatal.
705 * You can also make some message levels fatal at runtime by setting
706 * the `G_DEBUG` environment variable (see
707 * [Running GLib Applications](glib-running.html)).
709 * Libraries should not call this function, as it affects all messages logged
710 * by a process, including those from other libraries.
712 * Structured log messages (using g_log_structured() and
713 * g_log_structured_array()) are fatal only if the default log writer is used;
714 * otherwise it is up to the writer function to determine which log messages
715 * are fatal. See [Using Structured Logging][using-structured-logging].
717 * Returns: the old fatal mask
719 GLogLevelFlags
720 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
722 GLogLevelFlags old_mask;
724 /* restrict the global mask to levels that are known to glib
725 * since this setting applies to all domains
727 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
728 /* force errors to be fatal */
729 fatal_mask |= G_LOG_LEVEL_ERROR;
730 /* remove bogus flag */
731 fatal_mask &= ~G_LOG_FLAG_FATAL;
733 g_mutex_lock (&g_messages_lock);
734 old_mask = g_log_always_fatal;
735 g_log_always_fatal = fatal_mask;
736 g_mutex_unlock (&g_messages_lock);
738 return old_mask;
742 * g_log_set_fatal_mask:
743 * @log_domain: the log domain
744 * @fatal_mask: the new fatal mask
746 * Sets the log levels which are fatal in the given domain.
747 * %G_LOG_LEVEL_ERROR is always fatal.
749 * This has no effect on structured log messages (using g_log_structured() or
750 * g_log_structured_array()). To change the fatal behaviour for specific log
751 * messages, programs must install a custom log writer function using
752 * g_log_set_writer_func(). See
753 * [Using Structured Logging][using-structured-logging].
755 * This function is mostly intended to be used with
756 * %G_LOG_LEVEL_CRITICAL. You should typically not set
757 * %G_LOG_LEVEL_WARNING, %G_LOG_LEVEL_MESSAGE, %G_LOG_LEVEL_INFO or
758 * %G_LOG_LEVEL_DEBUG as fatal except inside of test programs.
760 * Returns: the old fatal mask for the log domain
762 GLogLevelFlags
763 g_log_set_fatal_mask (const gchar *log_domain,
764 GLogLevelFlags fatal_mask)
766 GLogLevelFlags old_flags;
767 GLogDomain *domain;
769 if (!log_domain)
770 log_domain = "";
772 /* force errors to be fatal */
773 fatal_mask |= G_LOG_LEVEL_ERROR;
774 /* remove bogus flag */
775 fatal_mask &= ~G_LOG_FLAG_FATAL;
777 g_mutex_lock (&g_messages_lock);
779 domain = g_log_find_domain_L (log_domain);
780 if (!domain)
781 domain = g_log_domain_new_L (log_domain);
782 old_flags = domain->fatal_mask;
784 domain->fatal_mask = fatal_mask;
785 g_log_domain_check_free_L (domain);
787 g_mutex_unlock (&g_messages_lock);
789 return old_flags;
793 * g_log_set_handler:
794 * @log_domain: (nullable): the log domain, or %NULL for the default ""
795 * application domain
796 * @log_levels: the log levels to apply the log handler for.
797 * To handle fatal and recursive messages as well, combine
798 * the log levels with the #G_LOG_FLAG_FATAL and
799 * #G_LOG_FLAG_RECURSION bit flags.
800 * @log_func: the log handler function
801 * @user_data: data passed to the log handler
803 * Sets the log handler for a domain and a set of log levels.
804 * To handle fatal and recursive messages the @log_levels parameter
805 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
806 * bit flags.
808 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
809 * you want to set a handler for this log level you must combine it with
810 * #G_LOG_FLAG_FATAL.
812 * This has no effect if structured logging is enabled; see
813 * [Using Structured Logging][using-structured-logging].
815 * Here is an example for adding a log handler for all warning messages
816 * in the default domain:
817 * |[<!-- language="C" -->
818 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
819 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
820 * ]|
822 * This example adds a log handler for all critical messages from GTK+:
823 * |[<!-- language="C" -->
824 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
825 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
826 * ]|
828 * This example adds a log handler for all messages from GLib:
829 * |[<!-- language="C" -->
830 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
831 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
832 * ]|
834 * Returns: the id of the new handler
836 guint
837 g_log_set_handler (const gchar *log_domain,
838 GLogLevelFlags log_levels,
839 GLogFunc log_func,
840 gpointer user_data)
842 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
846 * g_log_set_handler_full: (rename-to g_log_set_handler)
847 * @log_domain: (nullable): the log domain, or %NULL for the default ""
848 * application domain
849 * @log_levels: the log levels to apply the log handler for.
850 * To handle fatal and recursive messages as well, combine
851 * the log levels with the #G_LOG_FLAG_FATAL and
852 * #G_LOG_FLAG_RECURSION bit flags.
853 * @log_func: the log handler function
854 * @user_data: data passed to the log handler
855 * @destroy: destroy notify for @user_data, or %NULL
857 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
859 * This has no effect if structured logging is enabled; see
860 * [Using Structured Logging][using-structured-logging].
862 * Returns: the id of the new handler
864 * Since: 2.46
866 guint
867 g_log_set_handler_full (const gchar *log_domain,
868 GLogLevelFlags log_levels,
869 GLogFunc log_func,
870 gpointer user_data,
871 GDestroyNotify destroy)
873 static guint handler_id = 0;
874 GLogDomain *domain;
875 GLogHandler *handler;
877 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
878 g_return_val_if_fail (log_func != NULL, 0);
880 if (!log_domain)
881 log_domain = "";
883 handler = g_new (GLogHandler, 1);
885 g_mutex_lock (&g_messages_lock);
887 domain = g_log_find_domain_L (log_domain);
888 if (!domain)
889 domain = g_log_domain_new_L (log_domain);
891 handler->id = ++handler_id;
892 handler->log_level = log_levels;
893 handler->log_func = log_func;
894 handler->data = user_data;
895 handler->destroy = destroy;
896 handler->next = domain->handlers;
897 domain->handlers = handler;
899 g_mutex_unlock (&g_messages_lock);
901 return handler_id;
905 * g_log_set_default_handler:
906 * @log_func: the log handler function
907 * @user_data: data passed to the log handler
909 * Installs a default log handler which is used if no
910 * log handler has been set for the particular log domain
911 * and log level combination. By default, GLib uses
912 * g_log_default_handler() as default log handler.
914 * This has no effect if structured logging is enabled; see
915 * [Using Structured Logging][using-structured-logging].
917 * Returns: the previous default log handler
919 * Since: 2.6
921 GLogFunc
922 g_log_set_default_handler (GLogFunc log_func,
923 gpointer user_data)
925 GLogFunc old_log_func;
927 g_mutex_lock (&g_messages_lock);
928 old_log_func = default_log_func;
929 default_log_func = log_func;
930 default_log_data = user_data;
931 g_mutex_unlock (&g_messages_lock);
933 return old_log_func;
937 * g_test_log_set_fatal_handler:
938 * @log_func: the log handler function.
939 * @user_data: data passed to the log handler.
941 * Installs a non-error fatal log handler which can be
942 * used to decide whether log messages which are counted
943 * as fatal abort the program.
945 * The use case here is that you are running a test case
946 * that depends on particular libraries or circumstances
947 * and cannot prevent certain known critical or warning
948 * messages. So you install a handler that compares the
949 * domain and message to precisely not abort in such a case.
951 * Note that the handler is reset at the beginning of
952 * any test case, so you have to set it inside each test
953 * function which needs the special behavior.
955 * This handler has no effect on g_error messages.
957 * This handler also has no effect on structured log messages (using
958 * g_log_structured() or g_log_structured_array()). To change the fatal
959 * behaviour for specific log messages, programs must install a custom log
960 * writer function using g_log_set_writer_func().See
961 * [Using Structured Logging][using-structured-logging].
963 * Since: 2.22
965 void
966 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
967 gpointer user_data)
969 g_mutex_lock (&g_messages_lock);
970 fatal_log_func = log_func;
971 fatal_log_data = user_data;
972 g_mutex_unlock (&g_messages_lock);
976 * g_log_remove_handler:
977 * @log_domain: the log domain
978 * @handler_id: the id of the handler, which was returned
979 * in g_log_set_handler()
981 * Removes the log handler.
983 * This has no effect if structured logging is enabled; see
984 * [Using Structured Logging][using-structured-logging].
986 void
987 g_log_remove_handler (const gchar *log_domain,
988 guint handler_id)
990 GLogDomain *domain;
992 g_return_if_fail (handler_id > 0);
994 if (!log_domain)
995 log_domain = "";
997 g_mutex_lock (&g_messages_lock);
998 domain = g_log_find_domain_L (log_domain);
999 if (domain)
1001 GLogHandler *work, *last;
1003 last = NULL;
1004 work = domain->handlers;
1005 while (work)
1007 if (work->id == handler_id)
1009 if (last)
1010 last->next = work->next;
1011 else
1012 domain->handlers = work->next;
1013 g_log_domain_check_free_L (domain);
1014 g_mutex_unlock (&g_messages_lock);
1015 if (work->destroy)
1016 work->destroy (work->data);
1017 g_free (work);
1018 return;
1020 last = work;
1021 work = last->next;
1024 g_mutex_unlock (&g_messages_lock);
1025 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1026 G_STRLOC, handler_id, log_domain);
1029 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1030 (wc == 0x7f) || \
1031 (wc >= 0x80 && wc < 0xa0)))
1033 static gchar*
1034 strdup_convert (const gchar *string,
1035 const gchar *charset)
1037 if (!g_utf8_validate (string, -1, NULL))
1039 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1040 guchar *p;
1042 for (p = (guchar *)string; *p; p++)
1044 if (CHAR_IS_SAFE(*p) &&
1045 !(*p == '\r' && *(p + 1) != '\n') &&
1046 *p < 0x80)
1047 g_string_append_c (gstring, *p);
1048 else
1049 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1052 return g_string_free (gstring, FALSE);
1054 else
1056 GError *err = NULL;
1058 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1059 if (result)
1060 return result;
1061 else
1063 /* Not thread-safe, but doesn't matter if we print the warning twice
1065 static gboolean warned = FALSE;
1066 if (!warned)
1068 warned = TRUE;
1069 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1071 g_error_free (err);
1073 return g_strdup (string);
1078 /* For a radix of 8 we need at most 3 output bytes for 1 input
1079 * byte. Additionally we might need up to 2 output bytes for the
1080 * readix prefix and 1 byte for the trailing NULL.
1082 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1084 static void
1085 format_unsigned (gchar *buf,
1086 gulong num,
1087 guint radix)
1089 gulong tmp;
1090 gchar c;
1091 gint i, n;
1093 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1095 if (radix != 8 && radix != 10 && radix != 16)
1097 *buf = '\000';
1098 return;
1101 if (!num)
1103 *buf++ = '0';
1104 *buf = '\000';
1105 return;
1108 if (radix == 16)
1110 *buf++ = '0';
1111 *buf++ = 'x';
1113 else if (radix == 8)
1115 *buf++ = '0';
1118 n = 0;
1119 tmp = num;
1120 while (tmp)
1122 tmp /= radix;
1123 n++;
1126 i = n;
1128 /* Again we can't use g_assert; actually this check should _never_ fail. */
1129 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1131 *buf = '\000';
1132 return;
1135 while (num)
1137 i--;
1138 c = (num % radix);
1139 if (c < 10)
1140 buf[i] = c + '0';
1141 else
1142 buf[i] = c + 'a' - 10;
1143 num /= radix;
1146 buf[n] = '\000';
1149 /* string size big enough to hold level prefix */
1150 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1152 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1154 /* these are emitted by the default log handler */
1155 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1156 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1157 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1159 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1160 gboolean use_color);
1161 static const gchar *color_reset (gboolean use_color);
1163 static FILE *
1164 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1165 GLogLevelFlags log_level,
1166 gboolean use_color)
1168 gboolean to_stdout = TRUE;
1170 /* we may not call _any_ GLib functions here */
1172 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1174 switch (log_level & G_LOG_LEVEL_MASK)
1176 case G_LOG_LEVEL_ERROR:
1177 strcat (level_prefix, "ERROR");
1178 to_stdout = FALSE;
1179 break;
1180 case G_LOG_LEVEL_CRITICAL:
1181 strcat (level_prefix, "CRITICAL");
1182 to_stdout = FALSE;
1183 break;
1184 case G_LOG_LEVEL_WARNING:
1185 strcat (level_prefix, "WARNING");
1186 to_stdout = FALSE;
1187 break;
1188 case G_LOG_LEVEL_MESSAGE:
1189 strcat (level_prefix, "Message");
1190 to_stdout = FALSE;
1191 break;
1192 case G_LOG_LEVEL_INFO:
1193 strcat (level_prefix, "INFO");
1194 break;
1195 case G_LOG_LEVEL_DEBUG:
1196 strcat (level_prefix, "DEBUG");
1197 break;
1198 default:
1199 if (log_level)
1201 strcat (level_prefix, "LOG-");
1202 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1204 else
1205 strcat (level_prefix, "LOG");
1206 break;
1209 strcat (level_prefix, color_reset (use_color));
1211 if (log_level & G_LOG_FLAG_RECURSION)
1212 strcat (level_prefix, " (recursed)");
1213 if (log_level & ALERT_LEVELS)
1214 strcat (level_prefix, " **");
1216 #ifdef G_OS_WIN32
1217 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1218 win32_keep_fatal_message = TRUE;
1219 #endif
1220 return to_stdout ? stdout : stderr;
1223 typedef struct {
1224 gchar *log_domain;
1225 GLogLevelFlags log_level;
1226 gchar *pattern;
1227 } GTestExpectedMessage;
1229 static GSList *expected_messages = NULL;
1232 * g_logv:
1233 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1234 * application domain
1235 * @log_level: the log level
1236 * @format: the message format. See the printf() documentation
1237 * @args: the parameters to insert into the format string
1239 * Logs an error or debugging message.
1241 * If the log level has been set as fatal, G_BREAKPOINT() is called
1242 * to terminate the program. See the documentation for G_BREAKPOINT() for
1243 * details of the debugging options this provides.
1245 * If g_log_default_handler() is used as the log handler function, a new-line
1246 * character will automatically be appended to @..., and need not be entered
1247 * manually.
1249 * If [structured logging is enabled][using-structured-logging] this will
1250 * output via the structured log writer function (see g_log_set_writer_func()).
1252 void
1253 g_logv (const gchar *log_domain,
1254 GLogLevelFlags log_level,
1255 const gchar *format,
1256 va_list args)
1258 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1259 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1260 gchar buffer[1025], *msg, *msg_alloc = NULL;
1261 gint i;
1263 log_level &= G_LOG_LEVEL_MASK;
1264 if (!log_level)
1265 return;
1267 if (log_level & G_LOG_FLAG_RECURSION)
1269 /* we use a stack buffer of fixed size, since we're likely
1270 * in an out-of-memory situation
1272 gsize size G_GNUC_UNUSED;
1274 size = _g_vsnprintf (buffer, 1024, format, args);
1275 msg = buffer;
1277 else
1278 msg = msg_alloc = g_strdup_vprintf (format, args);
1280 if (expected_messages)
1282 GTestExpectedMessage *expected = expected_messages->data;
1284 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1285 ((log_level & expected->log_level) == expected->log_level) &&
1286 g_pattern_match_simple (expected->pattern, msg))
1288 expected_messages = g_slist_delete_link (expected_messages,
1289 expected_messages);
1290 g_free (expected->log_domain);
1291 g_free (expected->pattern);
1292 g_free (expected);
1293 g_free (msg_alloc);
1294 return;
1296 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1298 gchar level_prefix[STRING_BUFFER_SIZE];
1299 gchar *expected_message;
1301 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1302 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1303 expected->log_domain ? expected->log_domain : "**",
1304 level_prefix, expected->pattern);
1305 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1306 g_free (expected_message);
1308 log_level |= G_LOG_FLAG_FATAL;
1312 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1314 GLogLevelFlags test_level;
1316 test_level = 1 << i;
1317 if (log_level & test_level)
1319 GLogDomain *domain;
1320 GLogFunc log_func;
1321 GLogLevelFlags domain_fatal_mask;
1322 gpointer data = NULL;
1323 gboolean masquerade_fatal = FALSE;
1324 guint depth;
1326 if (was_fatal)
1327 test_level |= G_LOG_FLAG_FATAL;
1328 if (was_recursion)
1329 test_level |= G_LOG_FLAG_RECURSION;
1331 /* check recursion and lookup handler */
1332 g_mutex_lock (&g_messages_lock);
1333 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1334 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1335 if (depth)
1336 test_level |= G_LOG_FLAG_RECURSION;
1337 depth++;
1338 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1339 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1340 test_level |= G_LOG_FLAG_FATAL;
1341 if (test_level & G_LOG_FLAG_RECURSION)
1342 log_func = _g_log_fallback_handler;
1343 else
1344 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1345 domain = NULL;
1346 g_mutex_unlock (&g_messages_lock);
1348 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1350 log_func (log_domain, test_level, msg, data);
1352 if ((test_level & G_LOG_FLAG_FATAL)
1353 && !(test_level & G_LOG_LEVEL_ERROR))
1355 masquerade_fatal = fatal_log_func
1356 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1359 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1361 #ifdef G_OS_WIN32
1362 if (win32_keep_fatal_message)
1364 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1366 MessageBox (NULL, locale_msg, NULL,
1367 MB_ICONERROR|MB_SETFOREGROUND);
1369 #endif /* !G_OS_WIN32 */
1371 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1374 depth--;
1375 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1379 g_free (msg_alloc);
1383 * g_log:
1384 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1385 * for the default
1386 * @log_level: the log level, either from #GLogLevelFlags
1387 * or a user-defined level
1388 * @format: the message format. See the printf() documentation
1389 * @...: the parameters to insert into the format string
1391 * Logs an error or debugging message.
1393 * If the log level has been set as fatal, G_BREAKPOINT() is called
1394 * to terminate the program. See the documentation for G_BREAKPOINT() for
1395 * details of the debugging options this provides.
1397 * If g_log_default_handler() is used as the log handler function, a new-line
1398 * character will automatically be appended to @..., and need not be entered
1399 * manually.
1401 * If [structured logging is enabled][using-structured-logging] this will
1402 * output via the structured log writer function (see g_log_set_writer_func()).
1404 void
1405 g_log (const gchar *log_domain,
1406 GLogLevelFlags log_level,
1407 const gchar *format,
1408 ...)
1410 va_list args;
1412 va_start (args, format);
1413 g_logv (log_domain, log_level, format, args);
1414 va_end (args);
1417 /* Return value must be 1 byte long (plus nul byte).
1418 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1420 static const gchar *
1421 log_level_to_priority (GLogLevelFlags log_level)
1423 if (log_level & G_LOG_LEVEL_ERROR)
1424 return "3";
1425 else if (log_level & G_LOG_LEVEL_CRITICAL)
1426 return "4";
1427 else if (log_level & G_LOG_LEVEL_WARNING)
1428 return "4";
1429 else if (log_level & G_LOG_LEVEL_MESSAGE)
1430 return "5";
1431 else if (log_level & G_LOG_LEVEL_INFO)
1432 return "6";
1433 else if (log_level & G_LOG_LEVEL_DEBUG)
1434 return "7";
1436 /* Default to LOG_NOTICE for custom log levels. */
1437 return "5";
1440 static FILE *
1441 log_level_to_file (GLogLevelFlags log_level)
1443 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1444 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1445 return stderr;
1446 else
1447 return stdout;
1450 static const gchar *
1451 log_level_to_color (GLogLevelFlags log_level,
1452 gboolean use_color)
1454 /* we may not call _any_ GLib functions here */
1456 if (!use_color)
1457 return "";
1459 if (log_level & G_LOG_LEVEL_ERROR)
1460 return "\033[1;31m"; /* red */
1461 else if (log_level & G_LOG_LEVEL_CRITICAL)
1462 return "\033[1;35m"; /* magenta */
1463 else if (log_level & G_LOG_LEVEL_WARNING)
1464 return "\033[1;33m"; /* yellow */
1465 else if (log_level & G_LOG_LEVEL_MESSAGE)
1466 return "\033[1;32m"; /* green */
1467 else if (log_level & G_LOG_LEVEL_INFO)
1468 return "\033[1;32m"; /* green */
1469 else if (log_level & G_LOG_LEVEL_DEBUG)
1470 return "\033[1;32m"; /* green */
1472 /* No color for custom log levels. */
1473 return "";
1476 static const gchar *
1477 color_reset (gboolean use_color)
1479 /* we may not call _any_ GLib functions here */
1481 if (!use_color)
1482 return "";
1484 return "\033[0m";
1487 #ifdef G_OS_WIN32
1489 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1490 * so we need to check the name of the pipe if _isatty (fd) == 0
1493 static gboolean
1494 win32_is_pipe_tty (int fd)
1496 gboolean result = FALSE;
1497 HANDLE h_fd;
1498 FILE_NAME_INFO *info = NULL;
1499 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1500 wchar_t *name = NULL;
1501 gint length;
1503 h_fd = (HANDLE) _get_osfhandle (fd);
1505 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1506 goto done_query;
1508 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1510 info = g_try_malloc (info_size);
1512 if (info == NULL ||
1513 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1514 goto done_query;
1516 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1517 name = info->FileName;
1519 length = wcslen (L"\\cygwin-");
1520 if (wcsncmp (name, L"\\cygwin-", length))
1522 length = wcslen (L"\\msys-");
1523 if (wcsncmp (name, L"\\msys-", length))
1524 goto done_query;
1527 name += length;
1528 length = wcsspn (name, L"0123456789abcdefABCDEF");
1529 if (length != 16)
1530 goto done_query;
1532 name += length;
1533 length = wcslen (L"-pty");
1534 if (wcsncmp (name, L"-pty", length))
1535 goto done_query;
1537 name += length;
1538 length = wcsspn (name, L"0123456789");
1539 if (length != 1)
1540 goto done_query;
1542 name += length;
1543 length = wcslen (L"-to-master");
1544 if (wcsncmp (name, L"-to-master", length))
1546 length = wcslen (L"-from-master");
1547 if (wcsncmp (name, L"-from-master", length))
1548 goto done_query;
1551 result = TRUE;
1553 done_query:
1554 if (info != NULL)
1555 g_free (info);
1557 return result;
1559 #endif
1561 #pragma GCC diagnostic push
1562 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1565 * g_log_structured:
1566 * @log_domain: log domain, usually %G_LOG_DOMAIN
1567 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1568 * level
1569 * @...: key-value pairs of structured data to add to the log entry, followed
1570 * by the key "MESSAGE", followed by a printf()-style message format,
1571 * followed by parameters to insert in the format string
1573 * Log a message with structured data. The message will be passed through to
1574 * the log writer set by the application using g_log_set_writer_func(). If the
1575 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1576 * be aborted by calling G_BREAKPOINT() at the end of this function. If the log writer returns
1577 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1578 * See the documentation for #GLogWriterFunc for information on chaining
1579 * writers.
1581 * The structured data is provided as key–value pairs, where keys are UTF-8
1582 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1583 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1584 * structured data, use g_log_structured_array(). The keys for structured data
1585 * should follow the [systemd journal
1586 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1587 * specification. It is suggested that custom keys are namespaced according to
1588 * the code which sets them. For example, custom keys from GLib all have a
1589 * `GLIB_` prefix.
1591 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1592 * be converted into a
1593 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1594 * field. The format string will have its placeholders substituted for the provided
1595 * values and be converted into a
1596 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1597 * field.
1599 * Other fields you may commonly want to pass into this function:
1601 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1602 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1603 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1604 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1605 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1607 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1608 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1609 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1610 * glib.h.
1612 * For example:
1613 * |[<!-- language="C" -->
1614 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1615 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1616 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1617 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1618 * some_pointer, some_integer);
1619 * ]|
1621 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1622 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1623 * If adding a `MESSAGE_ID`, consider shipping a [message
1624 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1625 * your software.
1627 * To pass a user data pointer to the log writer function which is specific to
1628 * this logging call, you must use g_log_structured_array() and pass the pointer
1629 * as a field with #GLogField.length set to zero, otherwise it will be
1630 * interpreted as a string.
1632 * For example:
1633 * |[<!-- language="C" -->
1634 * const GLogField fields[] = {
1635 * { "MESSAGE", "This is a debug message.", -1 },
1636 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1637 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1638 * { "MY_APPLICATION_STATE", state_object, 0 },
1639 * };
1640 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1641 * ]|
1643 * Note also that, even if no other structured fields are specified, there
1644 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1645 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1646 * field for which printf()-style formatting is supported.
1648 * The default writer function for `stdout` and `stderr` will automatically
1649 * append a new-line character after the message, so you should not add one
1650 * manually to the format string.
1652 * Since: 2.50
1654 void
1655 g_log_structured (const gchar *log_domain,
1656 GLogLevelFlags log_level,
1657 ...)
1659 va_list args;
1660 gchar buffer[1025], *message_allocated = NULL;
1661 const char *format;
1662 const gchar *message;
1663 gpointer p;
1664 gsize n_fields, i;
1665 GLogField stack_fields[16];
1666 GLogField *fields = stack_fields;
1667 GLogField *fields_allocated = NULL;
1668 GArray *array = NULL;
1670 va_start (args, log_level);
1672 /* MESSAGE and PRIORITY are a given */
1673 n_fields = 2;
1675 if (log_domain)
1676 n_fields++;
1678 for (p = va_arg (args, gchar *), i = n_fields;
1679 strcmp (p, "MESSAGE") != 0;
1680 p = va_arg (args, gchar *), i++)
1682 GLogField field;
1683 const gchar *key = p;
1684 gconstpointer value = va_arg (args, gpointer);
1686 field.key = key;
1687 field.value = value;
1688 field.length = -1;
1690 if (i < 16)
1691 stack_fields[i] = field;
1692 else
1694 /* Don't allow dynamic allocation, since we're likely
1695 * in an out-of-memory situation. For lack of a better solution,
1696 * just ignore further key-value pairs.
1698 if (log_level & G_LOG_FLAG_RECURSION)
1699 continue;
1701 if (i == 16)
1703 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1704 g_array_append_vals (array, stack_fields, 16);
1707 g_array_append_val (array, field);
1711 n_fields = i;
1713 if (array)
1714 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1716 format = va_arg (args, gchar *);
1718 if (log_level & G_LOG_FLAG_RECURSION)
1720 /* we use a stack buffer of fixed size, since we're likely
1721 * in an out-of-memory situation
1723 gsize size G_GNUC_UNUSED;
1725 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1726 message = buffer;
1728 else
1730 message = message_allocated = g_strdup_vprintf (format, args);
1733 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1734 fields[0].key = "MESSAGE";
1735 fields[0].value = message;
1736 fields[0].length = -1;
1738 fields[1].key = "PRIORITY";
1739 fields[1].value = log_level_to_priority (log_level);
1740 fields[1].length = -1;
1742 if (log_domain)
1744 fields[2].key = "GLIB_DOMAIN";
1745 fields[2].value = log_domain;
1746 fields[2].length = -1;
1749 /* Log it. */
1750 g_log_structured_array (log_level, fields, n_fields);
1752 g_free (fields_allocated);
1753 g_free (message_allocated);
1755 va_end (args);
1759 * g_log_variant:
1760 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1761 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1762 * level
1763 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1764 * containing the key-value pairs of message data.
1766 * Log a message with structured data, accepting the data within a #GVariant. This
1767 * version is especially useful for use in other languages, via introspection.
1769 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1770 * contain the text shown to the user.
1772 * The values in the @fields dictionary are likely to be of type String
1773 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1774 * supported. In this case the message is handled as binary and will be forwarded
1775 * to the log writer as such. The size of the array should not be higher than
1776 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1777 * g_variant_print() will be used to convert the value into a string.
1779 * For more details on its usage and about the parameters, see g_log_structured().
1781 * Since: 2.50
1784 void
1785 g_log_variant (const gchar *log_domain,
1786 GLogLevelFlags log_level,
1787 GVariant *fields)
1789 GVariantIter iter;
1790 GVariant *value;
1791 gchar *key;
1792 GArray *fields_array;
1793 GLogField field;
1794 GSList *values_list, *print_list;
1796 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1798 values_list = print_list = NULL;
1799 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1801 field.key = "PRIORITY";
1802 field.value = log_level_to_priority (log_level);
1803 field.length = -1;
1804 g_array_append_val (fields_array, field);
1806 if (log_domain)
1808 field.key = "GLIB_DOMAIN";
1809 field.value = log_domain;
1810 field.length = -1;
1811 g_array_append_val (fields_array, field);
1814 g_variant_iter_init (&iter, fields);
1815 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1817 gboolean defer_unref = TRUE;
1819 field.key = key;
1820 field.length = -1;
1822 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1824 field.value = g_variant_get_string (value, NULL);
1826 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1828 gsize s;
1829 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1830 if (G_LIKELY (s <= G_MAXSSIZE))
1832 field.length = s;
1834 else
1836 _g_fprintf (stderr,
1837 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1838 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1839 " bytes.", s);
1840 field.length = G_MAXSSIZE;
1843 else
1845 char *s = g_variant_print (value, FALSE);
1846 field.value = s;
1847 print_list = g_slist_prepend (print_list, s);
1848 defer_unref = FALSE;
1851 g_array_append_val (fields_array, field);
1853 if (G_LIKELY (defer_unref))
1854 values_list = g_slist_prepend (values_list, value);
1855 else
1856 g_variant_unref (value);
1859 /* Log it. */
1860 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1862 g_array_free (fields_array, TRUE);
1863 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1864 g_slist_free_full (print_list, g_free);
1868 #pragma GCC diagnostic pop
1870 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1871 const GLogField *fields,
1872 gsize n_fields,
1873 gpointer user_data);
1876 * g_log_structured_array:
1877 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1878 * level
1879 * @fields: (array length=n_fields): key–value pairs of structured data to add
1880 * to the log message
1881 * @n_fields: number of elements in the @fields array
1883 * Log a message with structured data. The message will be passed through to the
1884 * log writer set by the application using g_log_set_writer_func(). If the
1885 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1886 * be aborted at the end of this function.
1888 * See g_log_structured() for more documentation.
1890 * This assumes that @log_level is already present in @fields (typically as the
1891 * `PRIORITY` field).
1893 * Since: 2.50
1895 void
1896 g_log_structured_array (GLogLevelFlags log_level,
1897 const GLogField *fields,
1898 gsize n_fields)
1900 GLogWriterFunc writer_func;
1901 gpointer writer_user_data;
1902 gboolean recursion;
1903 guint depth;
1905 if (n_fields == 0)
1906 return;
1908 /* Check for recursion and look up the writer function. */
1909 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1910 recursion = (depth > 0);
1912 g_mutex_lock (&g_messages_lock);
1914 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1915 writer_user_data = log_writer_user_data;
1917 g_mutex_unlock (&g_messages_lock);
1919 /* Write the log entry. */
1920 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1922 g_assert (writer_func != NULL);
1923 writer_func (log_level, fields, n_fields, writer_user_data);
1925 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1927 /* Abort if the message was fatal. */
1928 if (log_level & G_LOG_FATAL_MASK)
1929 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1932 /* Semi-private helper function to implement the g_message() (etc.) macros
1933 * with support for G_GNUC_PRINTF so that @message_format can be checked
1934 * with -Wformat. */
1935 void
1936 g_log_structured_standard (const gchar *log_domain,
1937 GLogLevelFlags log_level,
1938 const gchar *file,
1939 const gchar *line,
1940 const gchar *func,
1941 const gchar *message_format,
1942 ...)
1944 GLogField fields[] =
1946 { "PRIORITY", log_level_to_priority (log_level), -1 },
1947 { "CODE_FILE", file, -1 },
1948 { "CODE_LINE", line, -1 },
1949 { "CODE_FUNC", func, -1 },
1950 /* Filled in later: */
1951 { "MESSAGE", NULL, -1 },
1952 /* If @log_domain is %NULL, we will not pass this field: */
1953 { "GLIB_DOMAIN", log_domain, -1 },
1955 gsize n_fields;
1956 gchar *message_allocated = NULL;
1957 gchar buffer[1025];
1958 va_list args;
1960 va_start (args, message_format);
1962 if (log_level & G_LOG_FLAG_RECURSION)
1964 /* we use a stack buffer of fixed size, since we're likely
1965 * in an out-of-memory situation
1967 gsize size G_GNUC_UNUSED;
1969 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
1970 fields[4].value = buffer;
1972 else
1974 fields[4].value = message_allocated = g_strdup_vprintf (message_format, args);
1977 va_end (args);
1979 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
1980 g_log_structured_array (log_level, fields, n_fields);
1982 g_free (message_allocated);
1986 * g_log_set_writer_func:
1987 * @func: log writer function, which must not be %NULL
1988 * @user_data: (closure func): user data to pass to @func
1989 * @user_data_free: (destroy func): function to free @user_data once it’s
1990 * finished with, if non-%NULL
1992 * Set a writer function which will be called to format and write out each log
1993 * message. Each program should set a writer function, or the default writer
1994 * (g_log_writer_default()) will be used.
1996 * Libraries **must not** call this function — only programs are allowed to
1997 * install a writer function, as there must be a single, central point where
1998 * log messages are formatted and outputted.
2000 * There can only be one writer function. It is an error to set more than one.
2002 * Since: 2.50
2004 void
2005 g_log_set_writer_func (GLogWriterFunc func,
2006 gpointer user_data,
2007 GDestroyNotify user_data_free)
2009 g_return_if_fail (func != NULL);
2011 g_mutex_lock (&g_messages_lock);
2012 log_writer_func = func;
2013 log_writer_user_data = user_data;
2014 log_writer_user_data_free = user_data_free;
2015 g_mutex_unlock (&g_messages_lock);
2019 * g_log_writer_supports_color:
2020 * @output_fd: output file descriptor to check
2022 * Check whether the given @output_fd file descriptor supports ANSI color
2023 * escape sequences. If so, they can safely be used when formatting log
2024 * messages.
2026 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2027 * Since: 2.50
2029 gboolean
2030 g_log_writer_supports_color (gint output_fd)
2032 #ifdef G_OS_WIN32
2033 gboolean result = FALSE;
2035 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2036 _invalid_parameter_handler oldHandler, newHandler;
2037 int prev_report_mode = 0;
2038 #endif
2040 #endif
2042 g_return_val_if_fail (output_fd >= 0, FALSE);
2044 /* FIXME: This check could easily be expanded in future to be more robust
2045 * against different types of terminal, which still vary in their color
2046 * support. cmd.exe on Windows, for example, supports ANSI colors only
2047 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2048 * The Windows 10 color support is supported on:
2049 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2050 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2051 * but not:
2052 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2053 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2055 * On UNIX systems, we probably want to use the functions from terminfo to
2056 * work out whether colors are supported.
2058 * Some examples:
2059 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2060 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2061 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2062 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2064 #ifdef G_OS_WIN32
2066 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2067 /* Set up our empty invalid parameter handler, for isatty(),
2068 * in case of bad fd's passed in for isatty(), so that
2069 * msvcrt80.dll+ won't abort the program
2071 newHandler = myInvalidParameterHandler;
2072 oldHandler = _set_invalid_parameter_handler (newHandler);
2074 /* Disable the message box for assertions. */
2075 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2076 #endif
2078 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2080 HANDLE h_output;
2081 DWORD dw_mode;
2083 if (_isatty (output_fd))
2085 h_output = (HANDLE) _get_osfhandle (output_fd);
2087 if (!GetConsoleMode (h_output, &dw_mode))
2088 goto reset_invalid_param_handler;
2090 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2091 result = TRUE;
2093 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2094 goto reset_invalid_param_handler;
2096 result = TRUE;
2100 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2101 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2102 * (bug 775468), on standard Windows consoles, such as cmd.exe
2104 if (!result)
2105 result = win32_is_pipe_tty (output_fd);
2107 reset_invalid_param_handler:
2108 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2109 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2110 _set_invalid_parameter_handler (oldHandler);
2111 #endif
2113 return result;
2114 #else
2115 return isatty (output_fd);
2116 #endif
2119 #if defined(__linux__) && !defined(__BIONIC__)
2120 static int journal_fd = -1;
2122 #ifndef SOCK_CLOEXEC
2123 #define SOCK_CLOEXEC 0
2124 #else
2125 #define HAVE_SOCK_CLOEXEC 1
2126 #endif
2128 static void
2129 open_journal (void)
2131 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2132 return;
2134 #ifndef HAVE_SOCK_CLOEXEC
2135 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2137 close (journal_fd);
2138 journal_fd = -1;
2140 #endif
2142 #endif
2145 * g_log_writer_is_journald:
2146 * @output_fd: output file descriptor to check
2148 * Check whether the given @output_fd file descriptor is a connection to the
2149 * systemd journal, or something else (like a log file or `stdout` or
2150 * `stderr`).
2152 * Invalid file descriptors are accepted and return %FALSE, which allows for
2153 * the following construct without needing any additional error handling:
2154 * |[<!-- language="C" -->
2155 * is_journald = g_log_writer_is_journald (fileno (stderr));
2156 * ]|
2158 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2159 * Since: 2.50
2161 gboolean
2162 g_log_writer_is_journald (gint output_fd)
2164 #if defined(__linux__) && !defined(__BIONIC__)
2165 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2166 * journal. See: https://github.com/systemd/systemd/issues/2473
2168 static gsize initialized;
2169 static gboolean fd_is_journal = FALSE;
2171 if (output_fd < 0)
2172 return FALSE;
2174 if (g_once_init_enter (&initialized))
2176 union {
2177 struct sockaddr_storage storage;
2178 struct sockaddr sa;
2179 struct sockaddr_un un;
2180 } addr;
2181 socklen_t addr_len = sizeof(addr);
2182 int err = getpeername (output_fd, &addr.sa, &addr_len);
2183 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2184 fd_is_journal = g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2186 g_once_init_leave (&initialized, TRUE);
2189 return fd_is_journal;
2190 #else
2191 return FALSE;
2192 #endif
2195 static void escape_string (GString *string);
2198 * g_log_writer_format_fields:
2199 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2200 * level
2201 * @fields: (array length=n_fields): key–value pairs of structured data forming
2202 * the log message
2203 * @n_fields: number of elements in the @fields array
2204 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2205 * message, %FALSE to not
2207 * Format a structured log message as a string suitable for outputting to the
2208 * terminal (or elsewhere). This will include the values of all fields it knows
2209 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2210 * documentation for g_log_structured()). It does not include values from
2211 * unknown fields.
2213 * The returned string does **not** have a trailing new-line character. It is
2214 * encoded in the character set of the current locale, which is not necessarily
2215 * UTF-8.
2217 * Returns: (transfer full): string containing the formatted log message, in
2218 * the character set of the current locale
2219 * Since: 2.50
2221 gchar *
2222 g_log_writer_format_fields (GLogLevelFlags log_level,
2223 const GLogField *fields,
2224 gsize n_fields,
2225 gboolean use_color)
2227 gsize i;
2228 const gchar *message = NULL;
2229 const gchar *log_domain = NULL;
2230 gchar level_prefix[STRING_BUFFER_SIZE];
2231 GString *gstring;
2232 gint64 now;
2233 time_t now_secs;
2234 struct tm *now_tm;
2235 gchar time_buf[128];
2237 /* Extract some common fields. */
2238 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2240 const GLogField *field = &fields[i];
2242 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2243 message = field->value;
2244 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2245 log_domain = field->value;
2248 /* Format things. */
2249 mklevel_prefix (level_prefix, log_level, use_color);
2251 gstring = g_string_new (NULL);
2252 if (log_level & ALERT_LEVELS)
2253 g_string_append (gstring, "\n");
2254 if (!log_domain)
2255 g_string_append (gstring, "** ");
2257 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2258 (log_level & G_LOG_LEVEL_MASK))
2260 const gchar *prg_name = g_get_prgname ();
2261 gulong pid = getpid ();
2263 if (prg_name == NULL)
2264 g_string_append_printf (gstring, "(process:%lu): ", pid);
2265 else
2266 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2269 if (log_domain != NULL)
2271 g_string_append (gstring, log_domain);
2272 g_string_append_c (gstring, '-');
2274 g_string_append (gstring, level_prefix);
2276 g_string_append (gstring, ": ");
2278 /* Timestamp */
2279 now = g_get_real_time ();
2280 now_secs = (time_t) (now / 1000000);
2281 now_tm = localtime (&now_secs);
2282 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2284 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2285 use_color ? "\033[34m" : "",
2286 time_buf, (gint) ((now / 1000) % 1000),
2287 color_reset (use_color));
2289 if (message == NULL)
2291 g_string_append (gstring, "(NULL) message");
2293 else
2295 GString *msg;
2296 const gchar *charset;
2298 msg = g_string_new (message);
2299 escape_string (msg);
2301 if (g_get_charset (&charset))
2303 /* charset is UTF-8 already */
2304 g_string_append (gstring, msg->str);
2306 else
2308 gchar *lstring = strdup_convert (msg->str, charset);
2309 g_string_append (gstring, lstring);
2310 g_free (lstring);
2313 g_string_free (msg, TRUE);
2316 return g_string_free (gstring, FALSE);
2319 /* Enable support for the journal if we're on a recent enough Linux */
2320 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2321 #define ENABLE_JOURNAL_SENDV
2322 #endif
2324 #ifdef ENABLE_JOURNAL_SENDV
2325 static int
2326 journal_sendv (struct iovec *iov,
2327 gsize iovlen)
2329 int buf_fd = -1;
2330 struct msghdr mh;
2331 struct sockaddr_un sa;
2332 union {
2333 struct cmsghdr cmsghdr;
2334 guint8 buf[CMSG_SPACE(sizeof(int))];
2335 } control;
2336 struct cmsghdr *cmsg;
2337 char path[] = "/dev/shm/journal.XXXXXX";
2339 if (journal_fd < 0)
2340 open_journal ();
2342 if (journal_fd < 0)
2343 return -1;
2345 memset (&sa, 0, sizeof (sa));
2346 sa.sun_family = AF_UNIX;
2347 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2348 return -1;
2350 memset (&mh, 0, sizeof (mh));
2351 mh.msg_name = &sa;
2352 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2353 mh.msg_iov = iov;
2354 mh.msg_iovlen = iovlen;
2356 retry:
2357 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2358 return 0;
2360 if (errno == EINTR)
2361 goto retry;
2363 if (errno != EMSGSIZE && errno != ENOBUFS)
2364 return -1;
2366 /* Message was too large, so dump to temporary file
2367 * and pass an FD to the journal
2369 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2370 return -1;
2372 if (unlink (path) < 0)
2374 close (buf_fd);
2375 return -1;
2378 if (writev (buf_fd, iov, iovlen) < 0)
2380 close (buf_fd);
2381 return -1;
2384 mh.msg_iov = NULL;
2385 mh.msg_iovlen = 0;
2387 memset (&control, 0, sizeof (control));
2388 mh.msg_control = &control;
2389 mh.msg_controllen = sizeof (control);
2391 cmsg = CMSG_FIRSTHDR (&mh);
2392 cmsg->cmsg_level = SOL_SOCKET;
2393 cmsg->cmsg_type = SCM_RIGHTS;
2394 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2395 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2397 mh.msg_controllen = cmsg->cmsg_len;
2399 retry2:
2400 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2401 return 0;
2403 if (errno == EINTR)
2404 goto retry2;
2406 return -1;
2408 #endif /* ENABLE_JOURNAL_SENDV */
2411 * g_log_writer_journald:
2412 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2413 * level
2414 * @fields: (array length=n_fields): key–value pairs of structured data forming
2415 * the log message
2416 * @n_fields: number of elements in the @fields array
2417 * @user_data: user data passed to g_log_set_writer_func()
2419 * Format a structured log message and send it to the systemd journal as a set
2420 * of key–value pairs. All fields are sent to the journal, but if a field has
2421 * length zero (indicating program-specific data) then only its key will be
2422 * sent.
2424 * This is suitable for use as a #GLogWriterFunc.
2426 * If GLib has been compiled without systemd support, this function is still
2427 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2429 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2430 * Since: 2.50
2432 GLogWriterOutput
2433 g_log_writer_journald (GLogLevelFlags log_level,
2434 const GLogField *fields,
2435 gsize n_fields,
2436 gpointer user_data)
2438 #ifdef ENABLE_JOURNAL_SENDV
2439 const char equals = '=';
2440 const char newline = '\n';
2441 gsize i, k;
2442 struct iovec *iov, *v;
2443 char *buf;
2444 gint retval;
2446 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2447 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2449 /* According to systemd.journal-fields(7), the journal allows fields in any
2450 * format (including arbitrary binary), but expects text fields to be UTF-8.
2451 * This is great, because we require input strings to be in UTF-8, so no
2452 * conversion is necessary and we don’t need to care about the current
2453 * locale’s character set.
2456 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2457 buf = g_alloca (32 * n_fields);
2459 k = 0;
2460 v = iov;
2461 for (i = 0; i < n_fields; i++)
2463 guint64 length;
2464 gboolean binary;
2466 if (fields[i].length < 0)
2468 length = strlen (fields[i].value);
2469 binary = strchr (fields[i].value, '\n') != NULL;
2471 else
2473 length = fields[i].length;
2474 binary = TRUE;
2477 if (binary)
2479 guint64 nstr;
2481 v[0].iov_base = (gpointer)fields[i].key;
2482 v[0].iov_len = strlen (fields[i].key);
2484 v[1].iov_base = (gpointer)&newline;
2485 v[1].iov_len = 1;
2487 nstr = GUINT64_TO_LE(length);
2488 memcpy (&buf[k], &nstr, sizeof (nstr));
2490 v[2].iov_base = &buf[k];
2491 v[2].iov_len = sizeof (nstr);
2492 v += 3;
2493 k += sizeof (nstr);
2495 else
2497 v[0].iov_base = (gpointer)fields[i].key;
2498 v[0].iov_len = strlen (fields[i].key);
2500 v[1].iov_base = (gpointer)&equals;
2501 v[1].iov_len = 1;
2502 v += 2;
2505 v[0].iov_base = (gpointer)fields[i].value;
2506 v[0].iov_len = length;
2508 v[1].iov_base = (gpointer)&newline;
2509 v[1].iov_len = 1;
2510 v += 2;
2513 retval = journal_sendv (iov, v - iov);
2515 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2516 #else
2517 return G_LOG_WRITER_UNHANDLED;
2518 #endif /* ENABLE_JOURNAL_SENDV */
2522 * g_log_writer_standard_streams:
2523 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2524 * level
2525 * @fields: (array length=n_fields): key–value pairs of structured data forming
2526 * the log message
2527 * @n_fields: number of elements in the @fields array
2528 * @user_data: user data passed to g_log_set_writer_func()
2530 * Format a structured log message and print it to either `stdout` or `stderr`,
2531 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2532 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2533 * which are understood by this function are included in the formatted string
2534 * which is printed.
2536 * If the output stream supports ANSI color escape sequences, they will be used
2537 * in the output.
2539 * A trailing new-line character is added to the log message when it is printed.
2541 * This is suitable for use as a #GLogWriterFunc.
2543 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2544 * Since: 2.50
2546 GLogWriterOutput
2547 g_log_writer_standard_streams (GLogLevelFlags log_level,
2548 const GLogField *fields,
2549 gsize n_fields,
2550 gpointer user_data)
2552 FILE *stream;
2553 gchar *out = NULL; /* in the current locale’s character set */
2555 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2556 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2558 stream = log_level_to_file (log_level);
2559 if (!stream || fileno (stream) < 0)
2560 return G_LOG_WRITER_UNHANDLED;
2562 out = g_log_writer_format_fields (log_level, fields, n_fields,
2563 g_log_writer_supports_color (fileno (stream)));
2564 _g_fprintf (stream, "%s\n", out);
2565 fflush (stream);
2566 g_free (out);
2568 return G_LOG_WRITER_HANDLED;
2571 /* The old g_log() API is implemented in terms of the new structured log API.
2572 * However, some of the checks do not line up between the two APIs: the
2573 * structured API only handles fatalness of messages for log levels; the old API
2574 * handles it per-domain as well. Consequently, we need to disable fatalness
2575 * handling in the structured log API when called from the old g_log() API.
2577 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2578 * the first field to g_log_structured_array(), if that is the case.
2580 static gboolean
2581 log_is_old_api (const GLogField *fields,
2582 gsize n_fields)
2584 return (n_fields >= 1 &&
2585 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2586 g_strcmp0 (fields[0].value, "1") == 0);
2590 * g_log_writer_default:
2591 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2592 * level
2593 * @fields: (array length=n_fields): key–value pairs of structured data forming
2594 * the log message
2595 * @n_fields: number of elements in the @fields array
2596 * @user_data: user data passed to g_log_set_writer_func()
2598 * Format a structured log message and output it to the default log destination
2599 * for the platform. On Linux, this is typically the systemd journal, falling
2600 * back to `stdout` or `stderr` if running from the terminal or if output is
2601 * being redirected to a file.
2603 * Support for other platform-specific logging mechanisms may be added in
2604 * future. Distributors of GLib may modify this function to impose their own
2605 * (documented) platform-specific log writing policies.
2607 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2608 * if no other is set using g_log_set_writer_func().
2610 * As with g_log_default_handler(), this function drops debug and informational
2611 * messages unless their log domain (or `all`) is listed in the space-separated
2612 * `G_MESSAGES_DEBUG` environment variable.
2614 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2615 * Since: 2.50
2617 GLogWriterOutput
2618 g_log_writer_default (GLogLevelFlags log_level,
2619 const GLogField *fields,
2620 gsize n_fields,
2621 gpointer user_data)
2623 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2624 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2626 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2627 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2629 const gchar *domains, *log_domain = NULL;
2630 gsize i;
2632 domains = g_getenv ("G_MESSAGES_DEBUG");
2634 if ((log_level & INFO_LEVELS) == 0 ||
2635 domains == NULL)
2636 return G_LOG_WRITER_HANDLED;
2638 for (i = 0; i < n_fields; i++)
2640 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2642 log_domain = fields[i].value;
2643 break;
2647 if (strcmp (domains, "all") != 0 &&
2648 (log_domain == NULL || !strstr (domains, log_domain)))
2649 return G_LOG_WRITER_HANDLED;
2652 /* Mark messages as fatal if they have a level set in
2653 * g_log_set_always_fatal().
2655 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2656 log_level |= G_LOG_FLAG_FATAL;
2658 /* Try logging to the systemd journal as first choice. */
2659 if (g_log_writer_is_journald (fileno (stderr)) &&
2660 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2661 G_LOG_WRITER_HANDLED)
2662 goto handled;
2664 /* FIXME: Add support for the Windows log. */
2666 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2667 G_LOG_WRITER_HANDLED)
2668 goto handled;
2670 return G_LOG_WRITER_UNHANDLED;
2672 handled:
2673 /* Abort if the message was fatal. */
2674 if (log_level & G_LOG_FLAG_FATAL)
2676 #ifdef G_OS_WIN32
2677 if (!g_test_initialized ())
2679 gchar *locale_msg = NULL;
2681 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2682 MessageBox (NULL, locale_msg, NULL,
2683 MB_ICONERROR | MB_SETFOREGROUND);
2684 g_free (locale_msg);
2686 #endif /* !G_OS_WIN32 */
2688 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2691 return G_LOG_WRITER_HANDLED;
2694 static GLogWriterOutput
2695 _g_log_writer_fallback (GLogLevelFlags log_level,
2696 const GLogField *fields,
2697 gsize n_fields,
2698 gpointer user_data)
2700 FILE *stream;
2701 gsize i;
2703 /* we cannot call _any_ GLib functions in this fallback handler,
2704 * which is why we skip UTF-8 conversion, etc.
2705 * since we either recursed or ran out of memory, we're in a pretty
2706 * pathologic situation anyways, what we can do is giving the
2707 * the process ID unconditionally however.
2710 stream = log_level_to_file (log_level);
2712 for (i = 0; i < n_fields; i++)
2714 const GLogField *field = &fields[i];
2716 /* Only print fields we definitely recognise, otherwise we could end up
2717 * printing a random non-string pointer provided by the user to be
2718 * interpreted by their writer function.
2720 if (strcmp (field->key, "MESSAGE") != 0 &&
2721 strcmp (field->key, "MESSAGE_ID") != 0 &&
2722 strcmp (field->key, "PRIORITY") != 0 &&
2723 strcmp (field->key, "CODE_FILE") != 0 &&
2724 strcmp (field->key, "CODE_LINE") != 0 &&
2725 strcmp (field->key, "CODE_FUNC") != 0 &&
2726 strcmp (field->key, "ERRNO") != 0 &&
2727 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2728 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2729 strcmp (field->key, "SYSLOG_PID") != 0 &&
2730 strcmp (field->key, "GLIB_DOMAIN") != 0)
2731 continue;
2733 write_string (stream, field->key);
2734 write_string (stream, "=");
2735 write_string_sized (stream, field->value, field->length);
2738 #ifndef G_OS_WIN32
2740 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2742 format_unsigned (pid_string, getpid (), 10);
2743 write_string (stream, "_PID=");
2744 write_string (stream, pid_string);
2746 #endif
2748 return G_LOG_WRITER_HANDLED;
2752 * g_return_if_fail_warning: (skip)
2753 * @log_domain: (nullable):
2754 * @pretty_function:
2755 * @expression: (nullable):
2757 void
2758 g_return_if_fail_warning (const char *log_domain,
2759 const char *pretty_function,
2760 const char *expression)
2762 g_log (log_domain,
2763 G_LOG_LEVEL_CRITICAL,
2764 "%s: assertion '%s' failed",
2765 pretty_function,
2766 expression);
2770 * g_warn_message: (skip)
2771 * @domain: (nullable):
2772 * @file:
2773 * @line:
2774 * @func:
2775 * @warnexpr: (nullable):
2777 void
2778 g_warn_message (const char *domain,
2779 const char *file,
2780 int line,
2781 const char *func,
2782 const char *warnexpr)
2784 char *s, lstr[32];
2785 g_snprintf (lstr, 32, "%d", line);
2786 if (warnexpr)
2787 s = g_strconcat ("(", file, ":", lstr, "):",
2788 func, func[0] ? ":" : "",
2789 " runtime check failed: (", warnexpr, ")", NULL);
2790 else
2791 s = g_strconcat ("(", file, ":", lstr, "):",
2792 func, func[0] ? ":" : "",
2793 " ", "code should not be reached", NULL);
2794 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2795 g_free (s);
2798 void
2799 g_assert_warning (const char *log_domain,
2800 const char *file,
2801 const int line,
2802 const char *pretty_function,
2803 const char *expression)
2805 if (expression)
2806 g_log (log_domain,
2807 G_LOG_LEVEL_ERROR,
2808 "file %s: line %d (%s): assertion failed: (%s)",
2809 file,
2810 line,
2811 pretty_function,
2812 expression);
2813 else
2814 g_log (log_domain,
2815 G_LOG_LEVEL_ERROR,
2816 "file %s: line %d (%s): should not be reached",
2817 file,
2818 line,
2819 pretty_function);
2820 _g_log_abort (FALSE);
2821 g_abort ();
2825 * g_test_expect_message:
2826 * @log_domain: (nullable): the log domain of the message
2827 * @log_level: the log level of the message
2828 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2830 * Indicates that a message with the given @log_domain and @log_level,
2831 * with text matching @pattern, is expected to be logged. When this
2832 * message is logged, it will not be printed, and the test case will
2833 * not abort.
2835 * This API may only be used with the old logging API (g_log() without
2836 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2837 * API. See [Testing for Messages][testing-for-messages].
2839 * Use g_test_assert_expected_messages() to assert that all
2840 * previously-expected messages have been seen and suppressed.
2842 * You can call this multiple times in a row, if multiple messages are
2843 * expected as a result of a single call. (The messages must appear in
2844 * the same order as the calls to g_test_expect_message().)
2846 * For example:
2848 * |[<!-- language="C" -->
2849 * // g_main_context_push_thread_default() should fail if the
2850 * // context is already owned by another thread.
2851 * g_test_expect_message (G_LOG_DOMAIN,
2852 * G_LOG_LEVEL_CRITICAL,
2853 * "assertion*acquired_context*failed");
2854 * g_main_context_push_thread_default (bad_context);
2855 * g_test_assert_expected_messages ();
2856 * ]|
2858 * Note that you cannot use this to test g_error() messages, since
2859 * g_error() intentionally never returns even if the program doesn't
2860 * abort; use g_test_trap_subprocess() in this case.
2862 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2863 * expected via g_test_expect_message() then they will be ignored.
2865 * Since: 2.34
2867 void
2868 g_test_expect_message (const gchar *log_domain,
2869 GLogLevelFlags log_level,
2870 const gchar *pattern)
2872 GTestExpectedMessage *expected;
2874 g_return_if_fail (log_level != 0);
2875 g_return_if_fail (pattern != NULL);
2876 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2878 expected = g_new (GTestExpectedMessage, 1);
2879 expected->log_domain = g_strdup (log_domain);
2880 expected->log_level = log_level;
2881 expected->pattern = g_strdup (pattern);
2883 expected_messages = g_slist_append (expected_messages, expected);
2886 void
2887 g_test_assert_expected_messages_internal (const char *domain,
2888 const char *file,
2889 int line,
2890 const char *func)
2892 if (expected_messages)
2894 GTestExpectedMessage *expected;
2895 gchar level_prefix[STRING_BUFFER_SIZE];
2896 gchar *message;
2898 expected = expected_messages->data;
2900 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2901 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2902 expected->log_domain ? expected->log_domain : "**",
2903 level_prefix, expected->pattern);
2904 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2905 g_free (message);
2910 * g_test_assert_expected_messages:
2912 * Asserts that all messages previously indicated via
2913 * g_test_expect_message() have been seen and suppressed.
2915 * This API may only be used with the old logging API (g_log() without
2916 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2917 * API. See [Testing for Messages][testing-for-messages].
2919 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2920 * expected via g_test_expect_message() then they will be ignored.
2922 * Since: 2.34
2925 void
2926 _g_log_fallback_handler (const gchar *log_domain,
2927 GLogLevelFlags log_level,
2928 const gchar *message,
2929 gpointer unused_data)
2931 gchar level_prefix[STRING_BUFFER_SIZE];
2932 #ifndef G_OS_WIN32
2933 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2934 #endif
2935 FILE *stream;
2937 /* we cannot call _any_ GLib functions in this fallback handler,
2938 * which is why we skip UTF-8 conversion, etc.
2939 * since we either recursed or ran out of memory, we're in a pretty
2940 * pathologic situation anyways, what we can do is giving the
2941 * the process ID unconditionally however.
2944 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2945 if (!message)
2946 message = "(NULL) message";
2948 #ifndef G_OS_WIN32
2949 format_unsigned (pid_string, getpid (), 10);
2950 #endif
2952 if (log_domain)
2953 write_string (stream, "\n");
2954 else
2955 write_string (stream, "\n** ");
2957 #ifndef G_OS_WIN32
2958 write_string (stream, "(process:");
2959 write_string (stream, pid_string);
2960 write_string (stream, "): ");
2961 #endif
2963 if (log_domain)
2965 write_string (stream, log_domain);
2966 write_string (stream, "-");
2968 write_string (stream, level_prefix);
2969 write_string (stream, ": ");
2970 write_string (stream, message);
2973 static void
2974 escape_string (GString *string)
2976 const char *p = string->str;
2977 gunichar wc;
2979 while (p < string->str + string->len)
2981 gboolean safe;
2983 wc = g_utf8_get_char_validated (p, -1);
2984 if (wc == (gunichar)-1 || wc == (gunichar)-2)
2986 gchar *tmp;
2987 guint pos;
2989 pos = p - string->str;
2991 /* Emit invalid UTF-8 as hex escapes
2993 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
2994 g_string_erase (string, pos, 1);
2995 g_string_insert (string, pos, tmp);
2997 p = string->str + (pos + 4); /* Skip over escape sequence */
2999 g_free (tmp);
3000 continue;
3002 if (wc == '\r')
3004 safe = *(p + 1) == '\n';
3006 else
3008 safe = CHAR_IS_SAFE (wc);
3011 if (!safe)
3013 gchar *tmp;
3014 guint pos;
3016 pos = p - string->str;
3018 /* Largest char we escape is 0x0a, so we don't have to worry
3019 * about 8-digit \Uxxxxyyyy
3021 tmp = g_strdup_printf ("\\u%04x", wc);
3022 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3023 g_string_insert (string, pos, tmp);
3024 g_free (tmp);
3026 p = string->str + (pos + 6); /* Skip over escape sequence */
3028 else
3029 p = g_utf8_next_char (p);
3034 * g_log_default_handler:
3035 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3036 * default "" application domain
3037 * @log_level: the level of the message
3038 * @message: (nullable): the message
3039 * @unused_data: (nullable): data passed from g_log() which is unused
3041 * The default log handler set up by GLib; g_log_set_default_handler()
3042 * allows to install an alternate default log handler.
3043 * This is used if no log handler has been set for the particular log
3044 * domain and log level combination. It outputs the message to stderr
3045 * or stdout and if the log level is fatal it calls G_BREAKPOINT(). It automatically
3046 * prints a new-line character after the message, so one does not need to be
3047 * manually included in @message.
3049 * The behavior of this log handler can be influenced by a number of
3050 * environment variables:
3052 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3053 * messages should be prefixed by the program name and PID of the
3054 * aplication.
3056 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3057 * which debug and informational messages are printed. By default
3058 * these messages are not printed.
3060 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3061 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3062 * the rest.
3064 * This has no effect if structured logging is enabled; see
3065 * [Using Structured Logging][using-structured-logging].
3067 void
3068 g_log_default_handler (const gchar *log_domain,
3069 GLogLevelFlags log_level,
3070 const gchar *message,
3071 gpointer unused_data)
3073 GLogField fields[4];
3074 int n_fields = 0;
3076 /* we can be called externally with recursion for whatever reason */
3077 if (log_level & G_LOG_FLAG_RECURSION)
3079 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3080 return;
3083 fields[0].key = "GLIB_OLD_LOG_API";
3084 fields[0].value = "1";
3085 fields[0].length = -1;
3086 n_fields++;
3088 fields[1].key = "MESSAGE";
3089 fields[1].value = message;
3090 fields[1].length = -1;
3091 n_fields++;
3093 fields[2].key = "PRIORITY";
3094 fields[2].value = log_level_to_priority (log_level);
3095 fields[2].length = -1;
3096 n_fields++;
3098 if (log_domain)
3100 fields[3].key = "GLIB_DOMAIN";
3101 fields[3].value = log_domain;
3102 fields[3].length = -1;
3103 n_fields++;
3106 /* Print out via the structured log API, but drop any fatal flags since we
3107 * have already handled them. The fatal handling in the structured logging
3108 * API is more coarse-grained than in the old g_log() API, so we don't want
3109 * to use it here.
3111 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3115 * g_set_print_handler:
3116 * @func: the new print handler
3118 * Sets the print handler.
3120 * Any messages passed to g_print() will be output via
3121 * the new handler. The default handler simply outputs
3122 * the message to stdout. By providing your own handler
3123 * you can redirect the output, to a GTK+ widget or a
3124 * log file for example.
3126 * Returns: the old print handler
3128 GPrintFunc
3129 g_set_print_handler (GPrintFunc func)
3131 GPrintFunc old_print_func;
3133 g_mutex_lock (&g_messages_lock);
3134 old_print_func = glib_print_func;
3135 glib_print_func = func;
3136 g_mutex_unlock (&g_messages_lock);
3138 return old_print_func;
3142 * g_print:
3143 * @format: the message format. See the printf() documentation
3144 * @...: the parameters to insert into the format string
3146 * Outputs a formatted message via the print handler.
3147 * The default print handler simply outputs the message to stdout, without
3148 * appending a trailing new-line character. Typically, @format should end with
3149 * its own new-line character.
3151 * g_print() should not be used from within libraries for debugging
3152 * messages, since it may be redirected by applications to special
3153 * purpose message windows or even files. Instead, libraries should
3154 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3155 * g_warning() and g_error().
3157 void
3158 g_print (const gchar *format,
3159 ...)
3161 va_list args;
3162 gchar *string;
3163 GPrintFunc local_glib_print_func;
3165 g_return_if_fail (format != NULL);
3167 va_start (args, format);
3168 string = g_strdup_vprintf (format, args);
3169 va_end (args);
3171 g_mutex_lock (&g_messages_lock);
3172 local_glib_print_func = glib_print_func;
3173 g_mutex_unlock (&g_messages_lock);
3175 if (local_glib_print_func)
3176 local_glib_print_func (string);
3177 else
3179 const gchar *charset;
3181 if (g_get_charset (&charset))
3182 fputs (string, stdout); /* charset is UTF-8 already */
3183 else
3185 gchar *lstring = strdup_convert (string, charset);
3187 fputs (lstring, stdout);
3188 g_free (lstring);
3190 fflush (stdout);
3192 g_free (string);
3196 * g_set_printerr_handler:
3197 * @func: the new error message handler
3199 * Sets the handler for printing error messages.
3201 * Any messages passed to g_printerr() will be output via
3202 * the new handler. The default handler simply outputs the
3203 * message to stderr. By providing your own handler you can
3204 * redirect the output, to a GTK+ widget or a log file for
3205 * example.
3207 * Returns: the old error message handler
3209 GPrintFunc
3210 g_set_printerr_handler (GPrintFunc func)
3212 GPrintFunc old_printerr_func;
3214 g_mutex_lock (&g_messages_lock);
3215 old_printerr_func = glib_printerr_func;
3216 glib_printerr_func = func;
3217 g_mutex_unlock (&g_messages_lock);
3219 return old_printerr_func;
3223 * g_printerr:
3224 * @format: the message format. See the printf() documentation
3225 * @...: the parameters to insert into the format string
3227 * Outputs a formatted message via the error message handler.
3228 * The default handler simply outputs the message to stderr, without appending
3229 * a trailing new-line character. Typically, @format should end with its own
3230 * new-line character.
3232 * g_printerr() should not be used from within libraries.
3233 * Instead g_log() or g_log_structured() should be used, or the convenience
3234 * macros g_message(), g_warning() and g_error().
3236 void
3237 g_printerr (const gchar *format,
3238 ...)
3240 va_list args;
3241 gchar *string;
3242 GPrintFunc local_glib_printerr_func;
3244 g_return_if_fail (format != NULL);
3246 va_start (args, format);
3247 string = g_strdup_vprintf (format, args);
3248 va_end (args);
3250 g_mutex_lock (&g_messages_lock);
3251 local_glib_printerr_func = glib_printerr_func;
3252 g_mutex_unlock (&g_messages_lock);
3254 if (local_glib_printerr_func)
3255 local_glib_printerr_func (string);
3256 else
3258 const gchar *charset;
3260 if (g_get_charset (&charset))
3261 fputs (string, stderr); /* charset is UTF-8 already */
3262 else
3264 gchar *lstring = strdup_convert (string, charset);
3266 fputs (lstring, stderr);
3267 g_free (lstring);
3269 fflush (stderr);
3271 g_free (string);
3275 * g_printf_string_upper_bound:
3276 * @format: the format string. See the printf() documentation
3277 * @args: the parameters to be inserted into the format string
3279 * Calculates the maximum space needed to store the output
3280 * of the sprintf() function.
3282 * Returns: the maximum space needed to store the formatted string
3284 gsize
3285 g_printf_string_upper_bound (const gchar *format,
3286 va_list args)
3288 gchar c;
3289 return _g_vsnprintf (&c, 1, format, args) + 1;