Merge branch '976-disable-assert-checks' into 'master'
[glib.git] / glib / gmessages.c
blobb468ef3b759a2b4d038bbeaa105872c2db8363f7
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
432 * abort() 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, the abort()
1242 * function is called to terminate the program.
1244 * If g_log_default_handler() is used as the log handler function, a new-line
1245 * character will automatically be appended to @..., and need not be entered
1246 * manually.
1248 * If [structured logging is enabled][using-structured-logging] this will
1249 * output via the structured log writer function (see g_log_set_writer_func()).
1251 void
1252 g_logv (const gchar *log_domain,
1253 GLogLevelFlags log_level,
1254 const gchar *format,
1255 va_list args)
1257 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1258 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1259 gchar buffer[1025], *msg, *msg_alloc = NULL;
1260 gint i;
1262 log_level &= G_LOG_LEVEL_MASK;
1263 if (!log_level)
1264 return;
1266 if (log_level & G_LOG_FLAG_RECURSION)
1268 /* we use a stack buffer of fixed size, since we're likely
1269 * in an out-of-memory situation
1271 gsize size G_GNUC_UNUSED;
1273 size = _g_vsnprintf (buffer, 1024, format, args);
1274 msg = buffer;
1276 else
1277 msg = msg_alloc = g_strdup_vprintf (format, args);
1279 if (expected_messages)
1281 GTestExpectedMessage *expected = expected_messages->data;
1283 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1284 ((log_level & expected->log_level) == expected->log_level) &&
1285 g_pattern_match_simple (expected->pattern, msg))
1287 expected_messages = g_slist_delete_link (expected_messages,
1288 expected_messages);
1289 g_free (expected->log_domain);
1290 g_free (expected->pattern);
1291 g_free (expected);
1292 g_free (msg_alloc);
1293 return;
1295 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1297 gchar level_prefix[STRING_BUFFER_SIZE];
1298 gchar *expected_message;
1300 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1301 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1302 expected->log_domain ? expected->log_domain : "**",
1303 level_prefix, expected->pattern);
1304 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1305 g_free (expected_message);
1307 log_level |= G_LOG_FLAG_FATAL;
1311 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1313 GLogLevelFlags test_level;
1315 test_level = 1 << i;
1316 if (log_level & test_level)
1318 GLogDomain *domain;
1319 GLogFunc log_func;
1320 GLogLevelFlags domain_fatal_mask;
1321 gpointer data = NULL;
1322 gboolean masquerade_fatal = FALSE;
1323 guint depth;
1325 if (was_fatal)
1326 test_level |= G_LOG_FLAG_FATAL;
1327 if (was_recursion)
1328 test_level |= G_LOG_FLAG_RECURSION;
1330 /* check recursion and lookup handler */
1331 g_mutex_lock (&g_messages_lock);
1332 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1333 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1334 if (depth)
1335 test_level |= G_LOG_FLAG_RECURSION;
1336 depth++;
1337 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1338 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1339 test_level |= G_LOG_FLAG_FATAL;
1340 if (test_level & G_LOG_FLAG_RECURSION)
1341 log_func = _g_log_fallback_handler;
1342 else
1343 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1344 domain = NULL;
1345 g_mutex_unlock (&g_messages_lock);
1347 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1349 log_func (log_domain, test_level, msg, data);
1351 if ((test_level & G_LOG_FLAG_FATAL)
1352 && !(test_level & G_LOG_LEVEL_ERROR))
1354 masquerade_fatal = fatal_log_func
1355 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1358 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1360 #ifdef G_OS_WIN32
1361 if (win32_keep_fatal_message)
1363 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1365 MessageBox (NULL, locale_msg, NULL,
1366 MB_ICONERROR|MB_SETFOREGROUND);
1368 #endif /* !G_OS_WIN32 */
1370 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1373 depth--;
1374 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1378 g_free (msg_alloc);
1382 * g_log:
1383 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1384 * for the default
1385 * @log_level: the log level, either from #GLogLevelFlags
1386 * or a user-defined level
1387 * @format: the message format. See the printf() documentation
1388 * @...: the parameters to insert into the format string
1390 * Logs an error or debugging message.
1392 * If the log level has been set as fatal, the abort()
1393 * function is called to terminate the program.
1395 * If g_log_default_handler() is used as the log handler function, a new-line
1396 * character will automatically be appended to @..., and need not be entered
1397 * manually.
1399 * If [structured logging is enabled][using-structured-logging] this will
1400 * output via the structured log writer function (see g_log_set_writer_func()).
1402 void
1403 g_log (const gchar *log_domain,
1404 GLogLevelFlags log_level,
1405 const gchar *format,
1406 ...)
1408 va_list args;
1410 va_start (args, format);
1411 g_logv (log_domain, log_level, format, args);
1412 va_end (args);
1415 /* Return value must be 1 byte long (plus nul byte).
1416 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1418 static const gchar *
1419 log_level_to_priority (GLogLevelFlags log_level)
1421 if (log_level & G_LOG_LEVEL_ERROR)
1422 return "3";
1423 else if (log_level & G_LOG_LEVEL_CRITICAL)
1424 return "4";
1425 else if (log_level & G_LOG_LEVEL_WARNING)
1426 return "4";
1427 else if (log_level & G_LOG_LEVEL_MESSAGE)
1428 return "5";
1429 else if (log_level & G_LOG_LEVEL_INFO)
1430 return "6";
1431 else if (log_level & G_LOG_LEVEL_DEBUG)
1432 return "7";
1434 /* Default to LOG_NOTICE for custom log levels. */
1435 return "5";
1438 static FILE *
1439 log_level_to_file (GLogLevelFlags log_level)
1441 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1442 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1443 return stderr;
1444 else
1445 return stdout;
1448 static const gchar *
1449 log_level_to_color (GLogLevelFlags log_level,
1450 gboolean use_color)
1452 /* we may not call _any_ GLib functions here */
1454 if (!use_color)
1455 return "";
1457 if (log_level & G_LOG_LEVEL_ERROR)
1458 return "\033[1;31m"; /* red */
1459 else if (log_level & G_LOG_LEVEL_CRITICAL)
1460 return "\033[1;35m"; /* magenta */
1461 else if (log_level & G_LOG_LEVEL_WARNING)
1462 return "\033[1;33m"; /* yellow */
1463 else if (log_level & G_LOG_LEVEL_MESSAGE)
1464 return "\033[1;32m"; /* green */
1465 else if (log_level & G_LOG_LEVEL_INFO)
1466 return "\033[1;32m"; /* green */
1467 else if (log_level & G_LOG_LEVEL_DEBUG)
1468 return "\033[1;32m"; /* green */
1470 /* No color for custom log levels. */
1471 return "";
1474 static const gchar *
1475 color_reset (gboolean use_color)
1477 /* we may not call _any_ GLib functions here */
1479 if (!use_color)
1480 return "";
1482 return "\033[0m";
1485 #ifdef G_OS_WIN32
1487 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1488 * so we need to check the name of the pipe if _isatty (fd) == 0
1491 static gboolean
1492 win32_is_pipe_tty (int fd)
1494 gboolean result = FALSE;
1495 HANDLE h_fd;
1496 FILE_NAME_INFO *info = NULL;
1497 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1498 wchar_t *name = NULL;
1499 gint length;
1501 h_fd = (HANDLE) _get_osfhandle (fd);
1503 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1504 goto done_query;
1506 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1508 info = g_try_malloc (info_size);
1510 if (info == NULL ||
1511 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1512 goto done_query;
1514 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1515 name = info->FileName;
1517 length = wcslen (L"\\cygwin-");
1518 if (wcsncmp (name, L"\\cygwin-", length))
1520 length = wcslen (L"\\msys-");
1521 if (wcsncmp (name, L"\\msys-", length))
1522 goto done_query;
1525 name += length;
1526 length = wcsspn (name, L"0123456789abcdefABCDEF");
1527 if (length != 16)
1528 goto done_query;
1530 name += length;
1531 length = wcslen (L"-pty");
1532 if (wcsncmp (name, L"-pty", length))
1533 goto done_query;
1535 name += length;
1536 length = wcsspn (name, L"0123456789");
1537 if (length != 1)
1538 goto done_query;
1540 name += length;
1541 length = wcslen (L"-to-master");
1542 if (wcsncmp (name, L"-to-master", length))
1544 length = wcslen (L"-from-master");
1545 if (wcsncmp (name, L"-from-master", length))
1546 goto done_query;
1549 result = TRUE;
1551 done_query:
1552 if (info != NULL)
1553 g_free (info);
1555 return result;
1557 #endif
1559 #pragma GCC diagnostic push
1560 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1563 * g_log_structured:
1564 * @log_domain: log domain, usually %G_LOG_DOMAIN
1565 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1566 * level
1567 * @...: key-value pairs of structured data to add to the log entry, followed
1568 * by the key "MESSAGE", followed by a printf()-style message format,
1569 * followed by parameters to insert in the format string
1571 * Log a message with structured data. The message will be passed through to
1572 * the log writer set by the application using g_log_set_writer_func(). If the
1573 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1574 * be aborted at the end of this function. If the log writer returns
1575 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1576 * See the documentation for #GLogWriterFunc for information on chaining
1577 * writers.
1579 * The structured data is provided as key–value pairs, where keys are UTF-8
1580 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1581 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1582 * structured data, use g_log_structured_array(). The keys for structured data
1583 * should follow the [systemd journal
1584 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1585 * specification. It is suggested that custom keys are namespaced according to
1586 * the code which sets them. For example, custom keys from GLib all have a
1587 * `GLIB_` prefix.
1589 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1590 * be converted into a
1591 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1592 * field. The format string will have its placeholders substituted for the provided
1593 * values and be converted into a
1594 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1595 * field.
1597 * Other fields you may commonly want to pass into this function:
1599 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1600 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1601 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1602 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1603 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1605 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1606 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1607 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1608 * glib.h.
1610 * For example:
1611 * |[<!-- language="C" -->
1612 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1613 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1614 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1615 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1616 * some_pointer, some_integer);
1617 * ]|
1619 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1620 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1621 * If adding a `MESSAGE_ID`, consider shipping a [message
1622 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1623 * your software.
1625 * To pass a user data pointer to the log writer function which is specific to
1626 * this logging call, you must use g_log_structured_array() and pass the pointer
1627 * as a field with #GLogField.length set to zero, otherwise it will be
1628 * interpreted as a string.
1630 * For example:
1631 * |[<!-- language="C" -->
1632 * const GLogField fields[] = {
1633 * { "MESSAGE", "This is a debug message.", -1 },
1634 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1635 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1636 * { "MY_APPLICATION_STATE", state_object, 0 },
1637 * };
1638 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1639 * ]|
1641 * Note also that, even if no other structured fields are specified, there
1642 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1643 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1644 * field for which printf()-style formatting is supported.
1646 * The default writer function for `stdout` and `stderr` will automatically
1647 * append a new-line character after the message, so you should not add one
1648 * manually to the format string.
1650 * Since: 2.50
1652 void
1653 g_log_structured (const gchar *log_domain,
1654 GLogLevelFlags log_level,
1655 ...)
1657 va_list args;
1658 gchar buffer[1025], *message_allocated = NULL;
1659 const char *format;
1660 const gchar *message;
1661 gpointer p;
1662 gsize n_fields, i;
1663 GLogField stack_fields[16];
1664 GLogField *fields = stack_fields;
1665 GLogField *fields_allocated = NULL;
1666 GArray *array = NULL;
1668 va_start (args, log_level);
1670 /* MESSAGE and PRIORITY are a given */
1671 n_fields = 2;
1673 if (log_domain)
1674 n_fields++;
1676 for (p = va_arg (args, gchar *), i = n_fields;
1677 strcmp (p, "MESSAGE") != 0;
1678 p = va_arg (args, gchar *), i++)
1680 GLogField field;
1681 const gchar *key = p;
1682 gconstpointer value = va_arg (args, gpointer);
1684 field.key = key;
1685 field.value = value;
1686 field.length = -1;
1688 if (i < 16)
1689 stack_fields[i] = field;
1690 else
1692 /* Don't allow dynamic allocation, since we're likely
1693 * in an out-of-memory situation. For lack of a better solution,
1694 * just ignore further key-value pairs.
1696 if (log_level & G_LOG_FLAG_RECURSION)
1697 continue;
1699 if (i == 16)
1701 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1702 g_array_append_vals (array, stack_fields, 16);
1705 g_array_append_val (array, field);
1709 n_fields = i;
1711 if (array)
1712 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1714 format = va_arg (args, gchar *);
1716 if (log_level & G_LOG_FLAG_RECURSION)
1718 /* we use a stack buffer of fixed size, since we're likely
1719 * in an out-of-memory situation
1721 gsize size G_GNUC_UNUSED;
1723 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1724 message = buffer;
1726 else
1728 message = message_allocated = g_strdup_vprintf (format, args);
1731 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1732 fields[0].key = "MESSAGE";
1733 fields[0].value = message;
1734 fields[0].length = -1;
1736 fields[1].key = "PRIORITY";
1737 fields[1].value = log_level_to_priority (log_level);
1738 fields[1].length = -1;
1740 if (log_domain)
1742 fields[2].key = "GLIB_DOMAIN";
1743 fields[2].value = log_domain;
1744 fields[2].length = -1;
1747 /* Log it. */
1748 g_log_structured_array (log_level, fields, n_fields);
1750 g_free (fields_allocated);
1751 g_free (message_allocated);
1753 va_end (args);
1757 * g_log_variant:
1758 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1759 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1760 * level
1761 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1762 * containing the key-value pairs of message data.
1764 * Log a message with structured data, accepting the data within a #GVariant. This
1765 * version is especially useful for use in other languages, via introspection.
1767 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1768 * contain the text shown to the user.
1770 * The values in the @fields dictionary are likely to be of type String
1771 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1772 * supported. In this case the message is handled as binary and will be forwarded
1773 * to the log writer as such. The size of the array should not be higher than
1774 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1775 * g_variant_print() will be used to convert the value into a string.
1777 * For more details on its usage and about the parameters, see g_log_structured().
1779 * Since: 2.50
1782 void
1783 g_log_variant (const gchar *log_domain,
1784 GLogLevelFlags log_level,
1785 GVariant *fields)
1787 GVariantIter iter;
1788 GVariant *value;
1789 gchar *key;
1790 GArray *fields_array;
1791 GLogField field;
1792 GSList *values_list, *print_list;
1794 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1796 values_list = print_list = NULL;
1797 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1799 field.key = "PRIORITY";
1800 field.value = log_level_to_priority (log_level);
1801 field.length = -1;
1802 g_array_append_val (fields_array, field);
1804 if (log_domain)
1806 field.key = "GLIB_DOMAIN";
1807 field.value = log_domain;
1808 field.length = -1;
1809 g_array_append_val (fields_array, field);
1812 g_variant_iter_init (&iter, fields);
1813 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1815 gboolean defer_unref = TRUE;
1817 field.key = key;
1818 field.length = -1;
1820 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1822 field.value = g_variant_get_string (value, NULL);
1824 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1826 gsize s;
1827 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1828 if (G_LIKELY (s <= G_MAXSSIZE))
1830 field.length = s;
1832 else
1834 _g_fprintf (stderr,
1835 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1836 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1837 " bytes.", s);
1838 field.length = G_MAXSSIZE;
1841 else
1843 char *s = g_variant_print (value, FALSE);
1844 field.value = s;
1845 print_list = g_slist_prepend (print_list, s);
1846 defer_unref = FALSE;
1849 g_array_append_val (fields_array, field);
1851 if (G_LIKELY (defer_unref))
1852 values_list = g_slist_prepend (values_list, value);
1853 else
1854 g_variant_unref (value);
1857 /* Log it. */
1858 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1860 g_array_free (fields_array, TRUE);
1861 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1862 g_slist_free_full (print_list, g_free);
1866 #pragma GCC diagnostic pop
1868 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1869 const GLogField *fields,
1870 gsize n_fields,
1871 gpointer user_data);
1874 * g_log_structured_array:
1875 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1876 * level
1877 * @fields: (array length=n_fields): key–value pairs of structured data to add
1878 * to the log message
1879 * @n_fields: number of elements in the @fields array
1881 * Log a message with structured data. The message will be passed through to the
1882 * log writer set by the application using g_log_set_writer_func(). If the
1883 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1884 * be aborted at the end of this function.
1886 * See g_log_structured() for more documentation.
1888 * This assumes that @log_level is already present in @fields (typically as the
1889 * `PRIORITY` field).
1891 * Since: 2.50
1893 void
1894 g_log_structured_array (GLogLevelFlags log_level,
1895 const GLogField *fields,
1896 gsize n_fields)
1898 GLogWriterFunc writer_func;
1899 gpointer writer_user_data;
1900 gboolean recursion;
1901 guint depth;
1903 if (n_fields == 0)
1904 return;
1906 /* Check for recursion and look up the writer function. */
1907 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1908 recursion = (depth > 0);
1910 g_mutex_lock (&g_messages_lock);
1912 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1913 writer_user_data = log_writer_user_data;
1915 g_mutex_unlock (&g_messages_lock);
1917 /* Write the log entry. */
1918 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1920 g_assert (writer_func != NULL);
1921 writer_func (log_level, fields, n_fields, writer_user_data);
1923 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1925 /* Abort if the message was fatal. */
1926 if (log_level & G_LOG_FATAL_MASK)
1927 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1930 /* Semi-private helper function to implement the g_message() (etc.) macros
1931 * with support for G_GNUC_PRINTF so that @message_format can be checked
1932 * with -Wformat. */
1933 void
1934 g_log_structured_standard (const gchar *log_domain,
1935 GLogLevelFlags log_level,
1936 const gchar *file,
1937 const gchar *line,
1938 const gchar *func,
1939 const gchar *message_format,
1940 ...)
1942 GLogField fields[] =
1944 { "PRIORITY", log_level_to_priority (log_level), -1 },
1945 { "CODE_FILE", file, -1 },
1946 { "CODE_LINE", line, -1 },
1947 { "CODE_FUNC", func, -1 },
1948 /* Filled in later: */
1949 { "MESSAGE", NULL, -1 },
1950 /* If @log_domain is %NULL, we will not pass this field: */
1951 { "GLIB_DOMAIN", log_domain, -1 },
1953 gsize n_fields;
1954 gchar *message_allocated = NULL;
1955 gchar buffer[1025];
1956 va_list args;
1958 va_start (args, message_format);
1960 if (log_level & G_LOG_FLAG_RECURSION)
1962 /* we use a stack buffer of fixed size, since we're likely
1963 * in an out-of-memory situation
1965 gsize size G_GNUC_UNUSED;
1967 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
1968 fields[4].value = buffer;
1970 else
1972 fields[4].value = message_allocated = g_strdup_vprintf (message_format, args);
1975 va_end (args);
1977 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
1978 g_log_structured_array (log_level, fields, n_fields);
1980 g_free (message_allocated);
1984 * g_log_set_writer_func:
1985 * @func: log writer function, which must not be %NULL
1986 * @user_data: (closure func): user data to pass to @func
1987 * @user_data_free: (destroy func): function to free @user_data once it’s
1988 * finished with, if non-%NULL
1990 * Set a writer function which will be called to format and write out each log
1991 * message. Each program should set a writer function, or the default writer
1992 * (g_log_writer_default()) will be used.
1994 * Libraries **must not** call this function — only programs are allowed to
1995 * install a writer function, as there must be a single, central point where
1996 * log messages are formatted and outputted.
1998 * There can only be one writer function. It is an error to set more than one.
2000 * Since: 2.50
2002 void
2003 g_log_set_writer_func (GLogWriterFunc func,
2004 gpointer user_data,
2005 GDestroyNotify user_data_free)
2007 g_return_if_fail (func != NULL);
2009 g_mutex_lock (&g_messages_lock);
2010 log_writer_func = func;
2011 log_writer_user_data = user_data;
2012 log_writer_user_data_free = user_data_free;
2013 g_mutex_unlock (&g_messages_lock);
2017 * g_log_writer_supports_color:
2018 * @output_fd: output file descriptor to check
2020 * Check whether the given @output_fd file descriptor supports ANSI color
2021 * escape sequences. If so, they can safely be used when formatting log
2022 * messages.
2024 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2025 * Since: 2.50
2027 gboolean
2028 g_log_writer_supports_color (gint output_fd)
2030 #ifdef G_OS_WIN32
2031 gboolean result = FALSE;
2033 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2034 _invalid_parameter_handler oldHandler, newHandler;
2035 int prev_report_mode = 0;
2036 #endif
2038 #endif
2040 g_return_val_if_fail (output_fd >= 0, FALSE);
2042 /* FIXME: This check could easily be expanded in future to be more robust
2043 * against different types of terminal, which still vary in their color
2044 * support. cmd.exe on Windows, for example, supports ANSI colors only
2045 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2046 * The Windows 10 color support is supported on:
2047 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2048 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2049 * but not:
2050 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2051 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2053 * On UNIX systems, we probably want to use the functions from terminfo to
2054 * work out whether colors are supported.
2056 * Some examples:
2057 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2058 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2059 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2060 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2062 #ifdef G_OS_WIN32
2064 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2065 /* Set up our empty invalid parameter handler, for isatty(),
2066 * in case of bad fd's passed in for isatty(), so that
2067 * msvcrt80.dll+ won't abort the program
2069 newHandler = myInvalidParameterHandler;
2070 oldHandler = _set_invalid_parameter_handler (newHandler);
2072 /* Disable the message box for assertions. */
2073 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2074 #endif
2076 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2078 HANDLE h_output;
2079 DWORD dw_mode;
2081 if (_isatty (output_fd))
2083 h_output = (HANDLE) _get_osfhandle (output_fd);
2085 if (!GetConsoleMode (h_output, &dw_mode))
2086 goto reset_invalid_param_handler;
2088 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2089 result = TRUE;
2091 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2092 goto reset_invalid_param_handler;
2094 result = TRUE;
2098 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2099 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2100 * (bug 775468), on standard Windows consoles, such as cmd.exe
2102 if (!result)
2103 result = win32_is_pipe_tty (output_fd);
2105 reset_invalid_param_handler:
2106 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2107 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2108 _set_invalid_parameter_handler (oldHandler);
2109 #endif
2111 return result;
2112 #else
2113 return isatty (output_fd);
2114 #endif
2117 #if defined(__linux__) && !defined(__BIONIC__)
2118 static int journal_fd = -1;
2120 #ifndef SOCK_CLOEXEC
2121 #define SOCK_CLOEXEC 0
2122 #else
2123 #define HAVE_SOCK_CLOEXEC 1
2124 #endif
2126 static void
2127 open_journal (void)
2129 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2130 return;
2132 #ifndef HAVE_SOCK_CLOEXEC
2133 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2135 close (journal_fd);
2136 journal_fd = -1;
2138 #endif
2140 #endif
2143 * g_log_writer_is_journald:
2144 * @output_fd: output file descriptor to check
2146 * Check whether the given @output_fd file descriptor is a connection to the
2147 * systemd journal, or something else (like a log file or `stdout` or
2148 * `stderr`).
2150 * Invalid file descriptors are accepted and return %FALSE, which allows for
2151 * the following construct without needing any additional error handling:
2152 * |[<!-- language="C" -->
2153 * is_journald = g_log_writer_is_journald (fileno (stderr));
2154 * ]|
2156 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2157 * Since: 2.50
2159 gboolean
2160 g_log_writer_is_journald (gint output_fd)
2162 #if defined(__linux__) && !defined(__BIONIC__)
2163 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2164 * journal. See: https://github.com/systemd/systemd/issues/2473
2166 static gsize initialized;
2167 static gboolean fd_is_journal = FALSE;
2169 if (output_fd < 0)
2170 return FALSE;
2172 if (g_once_init_enter (&initialized))
2174 union {
2175 struct sockaddr_storage storage;
2176 struct sockaddr sa;
2177 struct sockaddr_un un;
2178 } addr;
2179 socklen_t addr_len = sizeof(addr);
2180 int err = getpeername (output_fd, &addr.sa, &addr_len);
2181 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2182 fd_is_journal = g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2184 g_once_init_leave (&initialized, TRUE);
2187 return fd_is_journal;
2188 #else
2189 return FALSE;
2190 #endif
2193 static void escape_string (GString *string);
2196 * g_log_writer_format_fields:
2197 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2198 * level
2199 * @fields: (array length=n_fields): key–value pairs of structured data forming
2200 * the log message
2201 * @n_fields: number of elements in the @fields array
2202 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2203 * message, %FALSE to not
2205 * Format a structured log message as a string suitable for outputting to the
2206 * terminal (or elsewhere). This will include the values of all fields it knows
2207 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2208 * documentation for g_log_structured()). It does not include values from
2209 * unknown fields.
2211 * The returned string does **not** have a trailing new-line character. It is
2212 * encoded in the character set of the current locale, which is not necessarily
2213 * UTF-8.
2215 * Returns: (transfer full): string containing the formatted log message, in
2216 * the character set of the current locale
2217 * Since: 2.50
2219 gchar *
2220 g_log_writer_format_fields (GLogLevelFlags log_level,
2221 const GLogField *fields,
2222 gsize n_fields,
2223 gboolean use_color)
2225 gsize i;
2226 const gchar *message = NULL;
2227 const gchar *log_domain = NULL;
2228 gchar level_prefix[STRING_BUFFER_SIZE];
2229 GString *gstring;
2230 gint64 now;
2231 time_t now_secs;
2232 struct tm *now_tm;
2233 gchar time_buf[128];
2235 /* Extract some common fields. */
2236 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2238 const GLogField *field = &fields[i];
2240 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2241 message = field->value;
2242 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2243 log_domain = field->value;
2246 /* Format things. */
2247 mklevel_prefix (level_prefix, log_level, use_color);
2249 gstring = g_string_new (NULL);
2250 if (log_level & ALERT_LEVELS)
2251 g_string_append (gstring, "\n");
2252 if (!log_domain)
2253 g_string_append (gstring, "** ");
2255 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2256 (log_level & G_LOG_LEVEL_MASK))
2258 const gchar *prg_name = g_get_prgname ();
2259 gulong pid = getpid ();
2261 if (prg_name == NULL)
2262 g_string_append_printf (gstring, "(process:%lu): ", pid);
2263 else
2264 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2267 if (log_domain != NULL)
2269 g_string_append (gstring, log_domain);
2270 g_string_append_c (gstring, '-');
2272 g_string_append (gstring, level_prefix);
2274 g_string_append (gstring, ": ");
2276 /* Timestamp */
2277 now = g_get_real_time ();
2278 now_secs = (time_t) (now / 1000000);
2279 now_tm = localtime (&now_secs);
2280 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2282 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2283 use_color ? "\033[34m" : "",
2284 time_buf, (gint) ((now / 1000) % 1000),
2285 color_reset (use_color));
2287 if (message == NULL)
2289 g_string_append (gstring, "(NULL) message");
2291 else
2293 GString *msg;
2294 const gchar *charset;
2296 msg = g_string_new (message);
2297 escape_string (msg);
2299 if (g_get_charset (&charset))
2301 /* charset is UTF-8 already */
2302 g_string_append (gstring, msg->str);
2304 else
2306 gchar *lstring = strdup_convert (msg->str, charset);
2307 g_string_append (gstring, lstring);
2308 g_free (lstring);
2311 g_string_free (msg, TRUE);
2314 return g_string_free (gstring, FALSE);
2317 /* Enable support for the journal if we're on a recent enough Linux */
2318 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2319 #define ENABLE_JOURNAL_SENDV
2320 #endif
2322 #ifdef ENABLE_JOURNAL_SENDV
2323 static int
2324 journal_sendv (struct iovec *iov,
2325 gsize iovlen)
2327 int buf_fd = -1;
2328 struct msghdr mh;
2329 struct sockaddr_un sa;
2330 union {
2331 struct cmsghdr cmsghdr;
2332 guint8 buf[CMSG_SPACE(sizeof(int))];
2333 } control;
2334 struct cmsghdr *cmsg;
2335 char path[] = "/dev/shm/journal.XXXXXX";
2337 if (journal_fd < 0)
2338 open_journal ();
2340 if (journal_fd < 0)
2341 return -1;
2343 memset (&sa, 0, sizeof (sa));
2344 sa.sun_family = AF_UNIX;
2345 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2346 return -1;
2348 memset (&mh, 0, sizeof (mh));
2349 mh.msg_name = &sa;
2350 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2351 mh.msg_iov = iov;
2352 mh.msg_iovlen = iovlen;
2354 retry:
2355 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2356 return 0;
2358 if (errno == EINTR)
2359 goto retry;
2361 if (errno != EMSGSIZE && errno != ENOBUFS)
2362 return -1;
2364 /* Message was too large, so dump to temporary file
2365 * and pass an FD to the journal
2367 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2368 return -1;
2370 if (unlink (path) < 0)
2372 close (buf_fd);
2373 return -1;
2376 if (writev (buf_fd, iov, iovlen) < 0)
2378 close (buf_fd);
2379 return -1;
2382 mh.msg_iov = NULL;
2383 mh.msg_iovlen = 0;
2385 memset (&control, 0, sizeof (control));
2386 mh.msg_control = &control;
2387 mh.msg_controllen = sizeof (control);
2389 cmsg = CMSG_FIRSTHDR (&mh);
2390 cmsg->cmsg_level = SOL_SOCKET;
2391 cmsg->cmsg_type = SCM_RIGHTS;
2392 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2393 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2395 mh.msg_controllen = cmsg->cmsg_len;
2397 retry2:
2398 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2399 return 0;
2401 if (errno == EINTR)
2402 goto retry2;
2404 return -1;
2406 #endif /* ENABLE_JOURNAL_SENDV */
2409 * g_log_writer_journald:
2410 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2411 * level
2412 * @fields: (array length=n_fields): key–value pairs of structured data forming
2413 * the log message
2414 * @n_fields: number of elements in the @fields array
2415 * @user_data: user data passed to g_log_set_writer_func()
2417 * Format a structured log message and send it to the systemd journal as a set
2418 * of key–value pairs. All fields are sent to the journal, but if a field has
2419 * length zero (indicating program-specific data) then only its key will be
2420 * sent.
2422 * This is suitable for use as a #GLogWriterFunc.
2424 * If GLib has been compiled without systemd support, this function is still
2425 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2427 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2428 * Since: 2.50
2430 GLogWriterOutput
2431 g_log_writer_journald (GLogLevelFlags log_level,
2432 const GLogField *fields,
2433 gsize n_fields,
2434 gpointer user_data)
2436 #ifdef ENABLE_JOURNAL_SENDV
2437 const char equals = '=';
2438 const char newline = '\n';
2439 gsize i, k;
2440 struct iovec *iov, *v;
2441 char *buf;
2442 gint retval;
2444 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2445 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2447 /* According to systemd.journal-fields(7), the journal allows fields in any
2448 * format (including arbitrary binary), but expects text fields to be UTF-8.
2449 * This is great, because we require input strings to be in UTF-8, so no
2450 * conversion is necessary and we don’t need to care about the current
2451 * locale’s character set.
2454 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2455 buf = g_alloca (32 * n_fields);
2457 k = 0;
2458 v = iov;
2459 for (i = 0; i < n_fields; i++)
2461 guint64 length;
2462 gboolean binary;
2464 if (fields[i].length < 0)
2466 length = strlen (fields[i].value);
2467 binary = strchr (fields[i].value, '\n') != NULL;
2469 else
2471 length = fields[i].length;
2472 binary = TRUE;
2475 if (binary)
2477 guint64 nstr;
2479 v[0].iov_base = (gpointer)fields[i].key;
2480 v[0].iov_len = strlen (fields[i].key);
2482 v[1].iov_base = (gpointer)&newline;
2483 v[1].iov_len = 1;
2485 nstr = GUINT64_TO_LE(length);
2486 memcpy (&buf[k], &nstr, sizeof (nstr));
2488 v[2].iov_base = &buf[k];
2489 v[2].iov_len = sizeof (nstr);
2490 v += 3;
2491 k += sizeof (nstr);
2493 else
2495 v[0].iov_base = (gpointer)fields[i].key;
2496 v[0].iov_len = strlen (fields[i].key);
2498 v[1].iov_base = (gpointer)&equals;
2499 v[1].iov_len = 1;
2500 v += 2;
2503 v[0].iov_base = (gpointer)fields[i].value;
2504 v[0].iov_len = length;
2506 v[1].iov_base = (gpointer)&newline;
2507 v[1].iov_len = 1;
2508 v += 2;
2511 retval = journal_sendv (iov, v - iov);
2513 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2514 #else
2515 return G_LOG_WRITER_UNHANDLED;
2516 #endif /* ENABLE_JOURNAL_SENDV */
2520 * g_log_writer_standard_streams:
2521 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2522 * level
2523 * @fields: (array length=n_fields): key–value pairs of structured data forming
2524 * the log message
2525 * @n_fields: number of elements in the @fields array
2526 * @user_data: user data passed to g_log_set_writer_func()
2528 * Format a structured log message and print it to either `stdout` or `stderr`,
2529 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2530 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2531 * which are understood by this function are included in the formatted string
2532 * which is printed.
2534 * If the output stream supports ANSI color escape sequences, they will be used
2535 * in the output.
2537 * A trailing new-line character is added to the log message when it is printed.
2539 * This is suitable for use as a #GLogWriterFunc.
2541 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2542 * Since: 2.50
2544 GLogWriterOutput
2545 g_log_writer_standard_streams (GLogLevelFlags log_level,
2546 const GLogField *fields,
2547 gsize n_fields,
2548 gpointer user_data)
2550 FILE *stream;
2551 gchar *out = NULL; /* in the current locale’s character set */
2553 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2554 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2556 stream = log_level_to_file (log_level);
2557 if (!stream || fileno (stream) < 0)
2558 return G_LOG_WRITER_UNHANDLED;
2560 out = g_log_writer_format_fields (log_level, fields, n_fields,
2561 g_log_writer_supports_color (fileno (stream)));
2562 _g_fprintf (stream, "%s\n", out);
2563 fflush (stream);
2564 g_free (out);
2566 return G_LOG_WRITER_HANDLED;
2569 /* The old g_log() API is implemented in terms of the new structured log API.
2570 * However, some of the checks do not line up between the two APIs: the
2571 * structured API only handles fatalness of messages for log levels; the old API
2572 * handles it per-domain as well. Consequently, we need to disable fatalness
2573 * handling in the structured log API when called from the old g_log() API.
2575 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2576 * the first field to g_log_structured_array(), if that is the case.
2578 static gboolean
2579 log_is_old_api (const GLogField *fields,
2580 gsize n_fields)
2582 return (n_fields >= 1 &&
2583 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2584 g_strcmp0 (fields[0].value, "1") == 0);
2588 * g_log_writer_default:
2589 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2590 * level
2591 * @fields: (array length=n_fields): key–value pairs of structured data forming
2592 * the log message
2593 * @n_fields: number of elements in the @fields array
2594 * @user_data: user data passed to g_log_set_writer_func()
2596 * Format a structured log message and output it to the default log destination
2597 * for the platform. On Linux, this is typically the systemd journal, falling
2598 * back to `stdout` or `stderr` if running from the terminal or if output is
2599 * being redirected to a file.
2601 * Support for other platform-specific logging mechanisms may be added in
2602 * future. Distributors of GLib may modify this function to impose their own
2603 * (documented) platform-specific log writing policies.
2605 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2606 * if no other is set using g_log_set_writer_func().
2608 * As with g_log_default_handler(), this function drops debug and informational
2609 * messages unless their log domain (or `all`) is listed in the space-separated
2610 * `G_MESSAGES_DEBUG` environment variable.
2612 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2613 * Since: 2.50
2615 GLogWriterOutput
2616 g_log_writer_default (GLogLevelFlags log_level,
2617 const GLogField *fields,
2618 gsize n_fields,
2619 gpointer user_data)
2621 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2622 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2624 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2625 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2627 const gchar *domains, *log_domain = NULL;
2628 gsize i;
2630 domains = g_getenv ("G_MESSAGES_DEBUG");
2632 if ((log_level & INFO_LEVELS) == 0 ||
2633 domains == NULL)
2634 return G_LOG_WRITER_HANDLED;
2636 for (i = 0; i < n_fields; i++)
2638 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2640 log_domain = fields[i].value;
2641 break;
2645 if (strcmp (domains, "all") != 0 &&
2646 (log_domain == NULL || !strstr (domains, log_domain)))
2647 return G_LOG_WRITER_HANDLED;
2650 /* Mark messages as fatal if they have a level set in
2651 * g_log_set_always_fatal().
2653 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2654 log_level |= G_LOG_FLAG_FATAL;
2656 /* Try logging to the systemd journal as first choice. */
2657 if (g_log_writer_is_journald (fileno (stderr)) &&
2658 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2659 G_LOG_WRITER_HANDLED)
2660 goto handled;
2662 /* FIXME: Add support for the Windows log. */
2664 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2665 G_LOG_WRITER_HANDLED)
2666 goto handled;
2668 return G_LOG_WRITER_UNHANDLED;
2670 handled:
2671 /* Abort if the message was fatal. */
2672 if (log_level & G_LOG_FLAG_FATAL)
2674 #ifdef G_OS_WIN32
2675 if (!g_test_initialized ())
2677 gchar *locale_msg = NULL;
2679 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2680 MessageBox (NULL, locale_msg, NULL,
2681 MB_ICONERROR | MB_SETFOREGROUND);
2682 g_free (locale_msg);
2684 #endif /* !G_OS_WIN32 */
2686 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2689 return G_LOG_WRITER_HANDLED;
2692 static GLogWriterOutput
2693 _g_log_writer_fallback (GLogLevelFlags log_level,
2694 const GLogField *fields,
2695 gsize n_fields,
2696 gpointer user_data)
2698 FILE *stream;
2699 gsize i;
2701 /* we cannot call _any_ GLib functions in this fallback handler,
2702 * which is why we skip UTF-8 conversion, etc.
2703 * since we either recursed or ran out of memory, we're in a pretty
2704 * pathologic situation anyways, what we can do is giving the
2705 * the process ID unconditionally however.
2708 stream = log_level_to_file (log_level);
2710 for (i = 0; i < n_fields; i++)
2712 const GLogField *field = &fields[i];
2714 /* Only print fields we definitely recognise, otherwise we could end up
2715 * printing a random non-string pointer provided by the user to be
2716 * interpreted by their writer function.
2718 if (strcmp (field->key, "MESSAGE") != 0 &&
2719 strcmp (field->key, "MESSAGE_ID") != 0 &&
2720 strcmp (field->key, "PRIORITY") != 0 &&
2721 strcmp (field->key, "CODE_FILE") != 0 &&
2722 strcmp (field->key, "CODE_LINE") != 0 &&
2723 strcmp (field->key, "CODE_FUNC") != 0 &&
2724 strcmp (field->key, "ERRNO") != 0 &&
2725 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2726 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2727 strcmp (field->key, "SYSLOG_PID") != 0 &&
2728 strcmp (field->key, "GLIB_DOMAIN") != 0)
2729 continue;
2731 write_string (stream, field->key);
2732 write_string (stream, "=");
2733 write_string_sized (stream, field->value, field->length);
2736 #ifndef G_OS_WIN32
2738 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2740 format_unsigned (pid_string, getpid (), 10);
2741 write_string (stream, "_PID=");
2742 write_string (stream, pid_string);
2744 #endif
2746 return G_LOG_WRITER_HANDLED;
2750 * g_return_if_fail_warning: (skip)
2751 * @log_domain: (nullable):
2752 * @pretty_function:
2753 * @expression: (nullable):
2755 void
2756 g_return_if_fail_warning (const char *log_domain,
2757 const char *pretty_function,
2758 const char *expression)
2760 g_log (log_domain,
2761 G_LOG_LEVEL_CRITICAL,
2762 "%s: assertion '%s' failed",
2763 pretty_function,
2764 expression);
2768 * g_warn_message: (skip)
2769 * @domain: (nullable):
2770 * @file:
2771 * @line:
2772 * @func:
2773 * @warnexpr: (nullable):
2775 void
2776 g_warn_message (const char *domain,
2777 const char *file,
2778 int line,
2779 const char *func,
2780 const char *warnexpr)
2782 char *s, lstr[32];
2783 g_snprintf (lstr, 32, "%d", line);
2784 if (warnexpr)
2785 s = g_strconcat ("(", file, ":", lstr, "):",
2786 func, func[0] ? ":" : "",
2787 " runtime check failed: (", warnexpr, ")", NULL);
2788 else
2789 s = g_strconcat ("(", file, ":", lstr, "):",
2790 func, func[0] ? ":" : "",
2791 " ", "code should not be reached", NULL);
2792 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2793 g_free (s);
2796 void
2797 g_assert_warning (const char *log_domain,
2798 const char *file,
2799 const int line,
2800 const char *pretty_function,
2801 const char *expression)
2803 if (expression)
2804 g_log (log_domain,
2805 G_LOG_LEVEL_ERROR,
2806 "file %s: line %d (%s): assertion failed: (%s)",
2807 file,
2808 line,
2809 pretty_function,
2810 expression);
2811 else
2812 g_log (log_domain,
2813 G_LOG_LEVEL_ERROR,
2814 "file %s: line %d (%s): should not be reached",
2815 file,
2816 line,
2817 pretty_function);
2818 _g_log_abort (FALSE);
2819 g_abort ();
2823 * g_test_expect_message:
2824 * @log_domain: (nullable): the log domain of the message
2825 * @log_level: the log level of the message
2826 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2828 * Indicates that a message with the given @log_domain and @log_level,
2829 * with text matching @pattern, is expected to be logged. When this
2830 * message is logged, it will not be printed, and the test case will
2831 * not abort.
2833 * This API may only be used with the old logging API (g_log() without
2834 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2835 * API. See [Testing for Messages][testing-for-messages].
2837 * Use g_test_assert_expected_messages() to assert that all
2838 * previously-expected messages have been seen and suppressed.
2840 * You can call this multiple times in a row, if multiple messages are
2841 * expected as a result of a single call. (The messages must appear in
2842 * the same order as the calls to g_test_expect_message().)
2844 * For example:
2846 * |[<!-- language="C" -->
2847 * // g_main_context_push_thread_default() should fail if the
2848 * // context is already owned by another thread.
2849 * g_test_expect_message (G_LOG_DOMAIN,
2850 * G_LOG_LEVEL_CRITICAL,
2851 * "assertion*acquired_context*failed");
2852 * g_main_context_push_thread_default (bad_context);
2853 * g_test_assert_expected_messages ();
2854 * ]|
2856 * Note that you cannot use this to test g_error() messages, since
2857 * g_error() intentionally never returns even if the program doesn't
2858 * abort; use g_test_trap_subprocess() in this case.
2860 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2861 * expected via g_test_expect_message() then they will be ignored.
2863 * Since: 2.34
2865 void
2866 g_test_expect_message (const gchar *log_domain,
2867 GLogLevelFlags log_level,
2868 const gchar *pattern)
2870 GTestExpectedMessage *expected;
2872 g_return_if_fail (log_level != 0);
2873 g_return_if_fail (pattern != NULL);
2874 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2876 expected = g_new (GTestExpectedMessage, 1);
2877 expected->log_domain = g_strdup (log_domain);
2878 expected->log_level = log_level;
2879 expected->pattern = g_strdup (pattern);
2881 expected_messages = g_slist_append (expected_messages, expected);
2884 void
2885 g_test_assert_expected_messages_internal (const char *domain,
2886 const char *file,
2887 int line,
2888 const char *func)
2890 if (expected_messages)
2892 GTestExpectedMessage *expected;
2893 gchar level_prefix[STRING_BUFFER_SIZE];
2894 gchar *message;
2896 expected = expected_messages->data;
2898 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2899 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2900 expected->log_domain ? expected->log_domain : "**",
2901 level_prefix, expected->pattern);
2902 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2903 g_free (message);
2908 * g_test_assert_expected_messages:
2910 * Asserts that all messages previously indicated via
2911 * g_test_expect_message() have been seen and suppressed.
2913 * This API may only be used with the old logging API (g_log() without
2914 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2915 * API. See [Testing for Messages][testing-for-messages].
2917 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2918 * expected via g_test_expect_message() then they will be ignored.
2920 * Since: 2.34
2923 void
2924 _g_log_fallback_handler (const gchar *log_domain,
2925 GLogLevelFlags log_level,
2926 const gchar *message,
2927 gpointer unused_data)
2929 gchar level_prefix[STRING_BUFFER_SIZE];
2930 #ifndef G_OS_WIN32
2931 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2932 #endif
2933 FILE *stream;
2935 /* we cannot call _any_ GLib functions in this fallback handler,
2936 * which is why we skip UTF-8 conversion, etc.
2937 * since we either recursed or ran out of memory, we're in a pretty
2938 * pathologic situation anyways, what we can do is giving the
2939 * the process ID unconditionally however.
2942 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2943 if (!message)
2944 message = "(NULL) message";
2946 #ifndef G_OS_WIN32
2947 format_unsigned (pid_string, getpid (), 10);
2948 #endif
2950 if (log_domain)
2951 write_string (stream, "\n");
2952 else
2953 write_string (stream, "\n** ");
2955 #ifndef G_OS_WIN32
2956 write_string (stream, "(process:");
2957 write_string (stream, pid_string);
2958 write_string (stream, "): ");
2959 #endif
2961 if (log_domain)
2963 write_string (stream, log_domain);
2964 write_string (stream, "-");
2966 write_string (stream, level_prefix);
2967 write_string (stream, ": ");
2968 write_string (stream, message);
2971 static void
2972 escape_string (GString *string)
2974 const char *p = string->str;
2975 gunichar wc;
2977 while (p < string->str + string->len)
2979 gboolean safe;
2981 wc = g_utf8_get_char_validated (p, -1);
2982 if (wc == (gunichar)-1 || wc == (gunichar)-2)
2984 gchar *tmp;
2985 guint pos;
2987 pos = p - string->str;
2989 /* Emit invalid UTF-8 as hex escapes
2991 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
2992 g_string_erase (string, pos, 1);
2993 g_string_insert (string, pos, tmp);
2995 p = string->str + (pos + 4); /* Skip over escape sequence */
2997 g_free (tmp);
2998 continue;
3000 if (wc == '\r')
3002 safe = *(p + 1) == '\n';
3004 else
3006 safe = CHAR_IS_SAFE (wc);
3009 if (!safe)
3011 gchar *tmp;
3012 guint pos;
3014 pos = p - string->str;
3016 /* Largest char we escape is 0x0a, so we don't have to worry
3017 * about 8-digit \Uxxxxyyyy
3019 tmp = g_strdup_printf ("\\u%04x", wc);
3020 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3021 g_string_insert (string, pos, tmp);
3022 g_free (tmp);
3024 p = string->str + (pos + 6); /* Skip over escape sequence */
3026 else
3027 p = g_utf8_next_char (p);
3032 * g_log_default_handler:
3033 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3034 * default "" application domain
3035 * @log_level: the level of the message
3036 * @message: (nullable): the message
3037 * @unused_data: (nullable): data passed from g_log() which is unused
3039 * The default log handler set up by GLib; g_log_set_default_handler()
3040 * allows to install an alternate default log handler.
3041 * This is used if no log handler has been set for the particular log
3042 * domain and log level combination. It outputs the message to stderr
3043 * or stdout and if the log level is fatal it calls abort(). It automatically
3044 * prints a new-line character after the message, so one does not need to be
3045 * manually included in @message.
3047 * The behavior of this log handler can be influenced by a number of
3048 * environment variables:
3050 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3051 * messages should be prefixed by the program name and PID of the
3052 * aplication.
3054 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3055 * which debug and informational messages are printed. By default
3056 * these messages are not printed.
3058 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3059 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3060 * the rest.
3062 * This has no effect if structured logging is enabled; see
3063 * [Using Structured Logging][using-structured-logging].
3065 void
3066 g_log_default_handler (const gchar *log_domain,
3067 GLogLevelFlags log_level,
3068 const gchar *message,
3069 gpointer unused_data)
3071 GLogField fields[4];
3072 int n_fields = 0;
3074 /* we can be called externally with recursion for whatever reason */
3075 if (log_level & G_LOG_FLAG_RECURSION)
3077 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3078 return;
3081 fields[0].key = "GLIB_OLD_LOG_API";
3082 fields[0].value = "1";
3083 fields[0].length = -1;
3084 n_fields++;
3086 fields[1].key = "MESSAGE";
3087 fields[1].value = message;
3088 fields[1].length = -1;
3089 n_fields++;
3091 fields[2].key = "PRIORITY";
3092 fields[2].value = log_level_to_priority (log_level);
3093 fields[2].length = -1;
3094 n_fields++;
3096 if (log_domain)
3098 fields[3].key = "GLIB_DOMAIN";
3099 fields[3].value = log_domain;
3100 fields[3].length = -1;
3101 n_fields++;
3104 /* Print out via the structured log API, but drop any fatal flags since we
3105 * have already handled them. The fatal handling in the structured logging
3106 * API is more coarse-grained than in the old g_log() API, so we don't want
3107 * to use it here.
3109 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3113 * g_set_print_handler:
3114 * @func: the new print handler
3116 * Sets the print handler.
3118 * Any messages passed to g_print() will be output via
3119 * the new handler. The default handler simply outputs
3120 * the message to stdout. By providing your own handler
3121 * you can redirect the output, to a GTK+ widget or a
3122 * log file for example.
3124 * Returns: the old print handler
3126 GPrintFunc
3127 g_set_print_handler (GPrintFunc func)
3129 GPrintFunc old_print_func;
3131 g_mutex_lock (&g_messages_lock);
3132 old_print_func = glib_print_func;
3133 glib_print_func = func;
3134 g_mutex_unlock (&g_messages_lock);
3136 return old_print_func;
3140 * g_print:
3141 * @format: the message format. See the printf() documentation
3142 * @...: the parameters to insert into the format string
3144 * Outputs a formatted message via the print handler.
3145 * The default print handler simply outputs the message to stdout, without
3146 * appending a trailing new-line character. Typically, @format should end with
3147 * its own new-line character.
3149 * g_print() should not be used from within libraries for debugging
3150 * messages, since it may be redirected by applications to special
3151 * purpose message windows or even files. Instead, libraries should
3152 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3153 * g_warning() and g_error().
3155 void
3156 g_print (const gchar *format,
3157 ...)
3159 va_list args;
3160 gchar *string;
3161 GPrintFunc local_glib_print_func;
3163 g_return_if_fail (format != NULL);
3165 va_start (args, format);
3166 string = g_strdup_vprintf (format, args);
3167 va_end (args);
3169 g_mutex_lock (&g_messages_lock);
3170 local_glib_print_func = glib_print_func;
3171 g_mutex_unlock (&g_messages_lock);
3173 if (local_glib_print_func)
3174 local_glib_print_func (string);
3175 else
3177 const gchar *charset;
3179 if (g_get_charset (&charset))
3180 fputs (string, stdout); /* charset is UTF-8 already */
3181 else
3183 gchar *lstring = strdup_convert (string, charset);
3185 fputs (lstring, stdout);
3186 g_free (lstring);
3188 fflush (stdout);
3190 g_free (string);
3194 * g_set_printerr_handler:
3195 * @func: the new error message handler
3197 * Sets the handler for printing error messages.
3199 * Any messages passed to g_printerr() will be output via
3200 * the new handler. The default handler simply outputs the
3201 * message to stderr. By providing your own handler you can
3202 * redirect the output, to a GTK+ widget or a log file for
3203 * example.
3205 * Returns: the old error message handler
3207 GPrintFunc
3208 g_set_printerr_handler (GPrintFunc func)
3210 GPrintFunc old_printerr_func;
3212 g_mutex_lock (&g_messages_lock);
3213 old_printerr_func = glib_printerr_func;
3214 glib_printerr_func = func;
3215 g_mutex_unlock (&g_messages_lock);
3217 return old_printerr_func;
3221 * g_printerr:
3222 * @format: the message format. See the printf() documentation
3223 * @...: the parameters to insert into the format string
3225 * Outputs a formatted message via the error message handler.
3226 * The default handler simply outputs the message to stderr, without appending
3227 * a trailing new-line character. Typically, @format should end with its own
3228 * new-line character.
3230 * g_printerr() should not be used from within libraries.
3231 * Instead g_log() or g_log_structured() should be used, or the convenience
3232 * macros g_message(), g_warning() and g_error().
3234 void
3235 g_printerr (const gchar *format,
3236 ...)
3238 va_list args;
3239 gchar *string;
3240 GPrintFunc local_glib_printerr_func;
3242 g_return_if_fail (format != NULL);
3244 va_start (args, format);
3245 string = g_strdup_vprintf (format, args);
3246 va_end (args);
3248 g_mutex_lock (&g_messages_lock);
3249 local_glib_printerr_func = glib_printerr_func;
3250 g_mutex_unlock (&g_messages_lock);
3252 if (local_glib_printerr_func)
3253 local_glib_printerr_func (string);
3254 else
3256 const gchar *charset;
3258 if (g_get_charset (&charset))
3259 fputs (string, stderr); /* charset is UTF-8 already */
3260 else
3262 gchar *lstring = strdup_convert (string, charset);
3264 fputs (lstring, stderr);
3265 g_free (lstring);
3267 fflush (stderr);
3269 g_free (string);
3273 * g_printf_string_upper_bound:
3274 * @format: the format string. See the printf() documentation
3275 * @args: the parameters to be inserted into the format string
3277 * Calculates the maximum space needed to store the output
3278 * of the sprintf() function.
3280 * Returns: the maximum space needed to store the formatted string
3282 gsize
3283 g_printf_string_upper_bound (const gchar *format,
3284 va_list args)
3286 gchar c;
3287 return _g_vsnprintf (&c, 1, format, args) + 1;