Add some more cases to the app-id unit tests
[glib.git] / glib / gmessages.c
blobdb40801a9bbd54fae0efd8b402d6c4d4186d5067
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
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
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
109 * Log domains may be used to broadly split up the origins of log messages.
110 * Typically, there are one or a few log domains per application or library.
111 * %G_LOG_DOMAIN should be used to define the default log domain for the current
112 * compilation unit — it is typically defined at the top of a source file, or in
113 * the preprocessor flags for a group of source files.
115 * Log domains must be unique, and it is recommended that they are the
116 * application or library name, optionally followed by a hyphen and a sub-domain
117 * name. For example, `bloatpad` or `bloatpad-io`.
119 * ## Debug Message Output
121 * The default log functions (g_log_default_handler() for the old-style API and
122 * g_log_writer_default() for the structured API) both drop debug and
123 * informational messages by default, unless the log domains of those messages
124 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
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
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 "gmem.h"
193 #include "gprintfint.h"
194 #include "gtestutils.h"
195 #include "gthread.h"
196 #include "gstrfuncs.h"
197 #include "gstring.h"
198 #include "gpattern.h"
200 #ifdef G_OS_UNIX
201 #include <unistd.h>
202 #endif
204 #ifdef G_OS_WIN32
205 #include <process.h> /* For getpid() */
206 #include <io.h>
207 # include <windows.h>
209 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
210 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
211 #endif
213 /* XXX: Remove once XP support really dropped */
214 #if _WIN32_WINNT < 0x0600
216 typedef enum _FILE_INFO_BY_HANDLE_CLASS
218 FileBasicInfo = 0,
219 FileStandardInfo = 1,
220 FileNameInfo = 2,
221 FileRenameInfo = 3,
222 FileDispositionInfo = 4,
223 FileAllocationInfo = 5,
224 FileEndOfFileInfo = 6,
225 FileStreamInfo = 7,
226 FileCompressionInfo = 8,
227 FileAttributeTagInfo = 9,
228 FileIdBothDirectoryInfo = 10,
229 FileIdBothDirectoryRestartInfo = 11,
230 FileIoPriorityHintInfo = 12,
231 FileRemoteProtocolInfo = 13,
232 FileFullDirectoryInfo = 14,
233 FileFullDirectoryRestartInfo = 15,
234 FileStorageInfo = 16,
235 FileAlignmentInfo = 17,
236 FileIdInfo = 18,
237 FileIdExtdDirectoryInfo = 19,
238 FileIdExtdDirectoryRestartInfo = 20,
239 MaximumFileInfoByHandlesClass
240 } FILE_INFO_BY_HANDLE_CLASS;
242 typedef struct _FILE_NAME_INFO
244 DWORD FileNameLength;
245 WCHAR FileName[1];
246 } FILE_NAME_INFO;
248 typedef BOOL (WINAPI fGetFileInformationByHandleEx) (HANDLE,
249 FILE_INFO_BY_HANDLE_CLASS,
250 LPVOID,
251 DWORD);
252 #endif
254 #if defined (_MSC_VER) && (_MSC_VER >=1400)
255 /* This is ugly, but we need it for isatty() in case we have bad fd's,
256 * otherwise Windows will abort() the program on msvcrt80.dll and later
258 #include <crtdbg.h>
260 _GLIB_EXTERN void
261 myInvalidParameterHandler(const wchar_t *expression,
262 const wchar_t *function,
263 const wchar_t *file,
264 unsigned int line,
265 uintptr_t pReserved)
268 #endif
270 #include "gwin32.h"
271 #endif
274 * G_LOG_DOMAIN:
276 * Defines the log domain.
278 * For applications, this is typically left as the default %NULL
279 * (or "") domain. Libraries should define this so that any messages
280 * which they log can be differentiated from messages from other
281 * libraries and application code. But be careful not to define
282 * it in any public header files.
284 * For example, GTK+ uses this in its Makefile.am:
285 * |[
286 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
287 * ]|
291 * G_LOG_FATAL_MASK:
293 * GLib log levels that are considered fatal by default.
295 * This is not used if structured logging is enabled; see
296 * [Using Structured Logging][using-structured-logging].
300 * GLogFunc:
301 * @log_domain: the log domain of the message
302 * @log_level: the log level of the message (including the
303 * fatal and recursion flags)
304 * @message: the message to process
305 * @user_data: user data, set in g_log_set_handler()
307 * Specifies the prototype of log handler functions.
309 * The default log handler, g_log_default_handler(), automatically appends a
310 * new-line character to @message when printing it. It is advised that any
311 * custom log handler functions behave similarly, so that logging calls in user
312 * code do not need modifying to add a new-line character to the message if the
313 * log handler is changed.
315 * This is not used if structured logging is enabled; see
316 * [Using Structured Logging][using-structured-logging].
320 * GLogLevelFlags:
321 * @G_LOG_FLAG_RECURSION: internal flag
322 * @G_LOG_FLAG_FATAL: internal flag
323 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
324 * This level is also used for messages produced by g_assert().
325 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
326 * g_critical().
327 * This level is also used for messages produced by g_return_if_fail()
328 * and g_return_val_if_fail().
329 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
330 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
331 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
332 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
333 * @G_LOG_LEVEL_MASK: a mask including all log levels
335 * Flags specifying the level of log messages.
337 * It is possible to change how GLib treats messages of the various
338 * levels using g_log_set_handler() and g_log_set_fatal_mask().
342 * G_LOG_LEVEL_USER_SHIFT:
344 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
345 * Higher bits can be used for user-defined log levels.
349 * g_message:
350 * @...: format string, followed by parameters to insert
351 * into the format string (as with printf())
353 * A convenience function/macro to log a normal message.
355 * If g_log_default_handler() is used as the log handler function, a new-line
356 * character will automatically be appended to @..., and need not be entered
357 * manually.
359 * If structured logging is enabled, this will use g_log_structured();
360 * otherwise it will use g_log(). See
361 * [Using Structured Logging][using-structured-logging].
365 * g_warning:
366 * @...: format string, followed by parameters to insert
367 * into the format string (as with printf())
369 * A convenience function/macro to log a warning message.
371 * This is not intended for end user error reporting. Use of #GError is
372 * preferred for that instead, as it allows calling functions to perform actions
373 * conditional on the type of error.
375 * You can make warnings fatal at runtime by setting the `G_DEBUG`
376 * environment variable (see
377 * [Running GLib Applications](glib-running.html)).
379 * If g_log_default_handler() is used as the log handler function,
380 * a newline character will automatically be appended to @..., and
381 * need not be entered manually.
383 * If structured logging is enabled, this will use g_log_structured();
384 * otherwise it will use g_log(). See
385 * [Using Structured Logging][using-structured-logging].
389 * g_critical:
390 * @...: format string, followed by parameters to insert
391 * into the format string (as with printf())
393 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
394 * It's more or less application-defined what constitutes
395 * a critical vs. a regular warning. You could call
396 * g_log_set_always_fatal() to make critical warnings exit
397 * the program, then use g_critical() for fatal errors, for
398 * example.
400 * You can also make critical warnings fatal at runtime by
401 * setting the `G_DEBUG` environment variable (see
402 * [Running GLib Applications](glib-running.html)).
404 * If g_log_default_handler() is used as the log handler function, a new-line
405 * character will automatically be appended to @..., and need not be entered
406 * manually.
408 * If structured logging is enabled, this will use g_log_structured();
409 * otherwise it will use g_log(). See
410 * [Using Structured Logging][using-structured-logging].
414 * g_error:
415 * @...: format string, followed by parameters to insert
416 * into the format string (as with printf())
418 * A convenience function/macro to log an error message.
420 * This is not intended for end user error reporting. Use of #GError is
421 * preferred for that instead, as it allows calling functions to perform actions
422 * conditional on the type of error.
424 * Error messages are always fatal, resulting in a call to
425 * abort() to terminate the application. This function will
426 * result in a core dump; don't use it for errors you expect.
427 * Using this function indicates a bug in your program, i.e.
428 * an assertion failure.
430 * If g_log_default_handler() is used as the log handler function, a new-line
431 * character will automatically be appended to @..., and need not be entered
432 * manually.
434 * If structured logging is enabled, this will use g_log_structured();
435 * otherwise it will use g_log(). See
436 * [Using Structured Logging][using-structured-logging].
440 * g_info:
441 * @...: format string, followed by parameters to insert
442 * into the format string (as with printf())
444 * A convenience function/macro to log an informational message. Seldom used.
446 * If g_log_default_handler() is used as the log handler function, a new-line
447 * character will automatically be appended to @..., and need not be entered
448 * manually.
450 * Such messages are suppressed by the g_log_default_handler() and
451 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
452 * set appropriately.
454 * If structured logging is enabled, this will use g_log_structured();
455 * otherwise it will use g_log(). See
456 * [Using Structured Logging][using-structured-logging].
458 * Since: 2.40
462 * g_debug:
463 * @...: format string, followed by parameters to insert
464 * into the format string (as with printf())
466 * A convenience function/macro to log a debug message.
468 * If g_log_default_handler() is used as the log handler function, a new-line
469 * character will automatically be appended to @..., and need not be entered
470 * manually.
472 * Such messages are suppressed by the g_log_default_handler() and
473 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
474 * set appropriately.
476 * If structured logging is enabled, this will use g_log_structured();
477 * otherwise it will use g_log(). See
478 * [Using Structured Logging][using-structured-logging].
480 * Since: 2.6
483 /* --- structures --- */
484 typedef struct _GLogDomain GLogDomain;
485 typedef struct _GLogHandler GLogHandler;
486 struct _GLogDomain
488 gchar *log_domain;
489 GLogLevelFlags fatal_mask;
490 GLogHandler *handlers;
491 GLogDomain *next;
493 struct _GLogHandler
495 guint id;
496 GLogLevelFlags log_level;
497 GLogFunc log_func;
498 gpointer data;
499 GDestroyNotify destroy;
500 GLogHandler *next;
504 /* --- variables --- */
505 static GMutex g_messages_lock;
506 static GLogDomain *g_log_domains = NULL;
507 static GPrintFunc glib_print_func = NULL;
508 static GPrintFunc glib_printerr_func = NULL;
509 static GPrivate g_log_depth;
510 static GPrivate g_log_structured_depth;
511 static GLogFunc default_log_func = g_log_default_handler;
512 static gpointer default_log_data = NULL;
513 static GTestLogFatalFunc fatal_log_func = NULL;
514 static gpointer fatal_log_data;
515 static GLogWriterFunc log_writer_func = g_log_writer_default;
516 static gpointer log_writer_user_data = NULL;
517 static GDestroyNotify log_writer_user_data_free = NULL;
519 /* --- functions --- */
521 static void _g_log_abort (gboolean breakpoint);
523 static void
524 _g_log_abort (gboolean breakpoint)
526 gboolean debugger_present;
528 if (g_test_subprocess ())
530 /* If this is a test case subprocess then it probably caused
531 * this error message on purpose, so just exit() rather than
532 * abort()ing, to avoid triggering any system crash-reporting
533 * daemon.
535 _exit (1);
538 #ifdef G_OS_WIN32
539 debugger_present = IsDebuggerPresent ();
540 #else
541 /* Assume GDB is attached. */
542 debugger_present = TRUE;
543 #endif /* !G_OS_WIN32 */
545 if (debugger_present && breakpoint)
546 G_BREAKPOINT ();
547 else
548 g_abort ();
551 #ifdef G_OS_WIN32
552 static gboolean win32_keep_fatal_message = FALSE;
554 /* This default message will usually be overwritten. */
555 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
556 * called with huge strings, is it?
558 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
559 static gchar *fatal_msg_ptr = fatal_msg_buf;
561 #undef write
562 static inline int
563 dowrite (int fd,
564 const void *buf,
565 unsigned int len)
567 if (win32_keep_fatal_message)
569 memcpy (fatal_msg_ptr, buf, len);
570 fatal_msg_ptr += len;
571 *fatal_msg_ptr = 0;
572 return len;
575 write (fd, buf, len);
577 return len;
579 #define write(fd, buf, len) dowrite(fd, buf, len)
581 #endif
583 static void
584 write_string (FILE *stream,
585 const gchar *string)
587 fputs (string, stream);
590 static void
591 write_string_sized (FILE *stream,
592 const gchar *string,
593 gssize length)
595 /* Is it nul-terminated? */
596 if (length < 0)
597 write_string (stream, string);
598 else
599 fwrite (string, 1, length, stream);
602 static GLogDomain*
603 g_log_find_domain_L (const gchar *log_domain)
605 GLogDomain *domain;
607 domain = g_log_domains;
608 while (domain)
610 if (strcmp (domain->log_domain, log_domain) == 0)
611 return domain;
612 domain = domain->next;
614 return NULL;
617 static GLogDomain*
618 g_log_domain_new_L (const gchar *log_domain)
620 GLogDomain *domain;
622 domain = g_new (GLogDomain, 1);
623 domain->log_domain = g_strdup (log_domain);
624 domain->fatal_mask = G_LOG_FATAL_MASK;
625 domain->handlers = NULL;
627 domain->next = g_log_domains;
628 g_log_domains = domain;
630 return domain;
633 static void
634 g_log_domain_check_free_L (GLogDomain *domain)
636 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
637 domain->handlers == NULL)
639 GLogDomain *last, *work;
641 last = NULL;
643 work = g_log_domains;
644 while (work)
646 if (work == domain)
648 if (last)
649 last->next = domain->next;
650 else
651 g_log_domains = domain->next;
652 g_free (domain->log_domain);
653 g_free (domain);
654 break;
656 last = work;
657 work = last->next;
662 static GLogFunc
663 g_log_domain_get_handler_L (GLogDomain *domain,
664 GLogLevelFlags log_level,
665 gpointer *data)
667 if (domain && log_level)
669 GLogHandler *handler;
671 handler = domain->handlers;
672 while (handler)
674 if ((handler->log_level & log_level) == log_level)
676 *data = handler->data;
677 return handler->log_func;
679 handler = handler->next;
683 *data = default_log_data;
684 return default_log_func;
688 * g_log_set_always_fatal:
689 * @fatal_mask: the mask containing bits set for each level
690 * of error which is to be fatal
692 * Sets the message levels which are always fatal, in any log domain.
693 * When a message with any of these levels is logged the program terminates.
694 * You can only set the levels defined by GLib to be fatal.
695 * %G_LOG_LEVEL_ERROR is always fatal.
697 * You can also make some message levels fatal at runtime by setting
698 * the `G_DEBUG` environment variable (see
699 * [Running GLib Applications](glib-running.html)).
701 * Libraries should not call this function, as it affects all messages logged
702 * by a process, including those from other libraries.
704 * Structured log messages (using g_log_structured() and
705 * g_log_structured_array()) are fatal only if the default log writer is used;
706 * otherwise it is up to the writer function to determine which log messages
707 * are fatal. See [Using Structured Logging][using-structured-logging].
709 * Returns: the old fatal mask
711 GLogLevelFlags
712 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
714 GLogLevelFlags old_mask;
716 /* restrict the global mask to levels that are known to glib
717 * since this setting applies to all domains
719 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
720 /* force errors to be fatal */
721 fatal_mask |= G_LOG_LEVEL_ERROR;
722 /* remove bogus flag */
723 fatal_mask &= ~G_LOG_FLAG_FATAL;
725 g_mutex_lock (&g_messages_lock);
726 old_mask = g_log_always_fatal;
727 g_log_always_fatal = fatal_mask;
728 g_mutex_unlock (&g_messages_lock);
730 return old_mask;
734 * g_log_set_fatal_mask:
735 * @log_domain: the log domain
736 * @fatal_mask: the new fatal mask
738 * Sets the log levels which are fatal in the given domain.
739 * %G_LOG_LEVEL_ERROR is always fatal.
741 * This has no effect on structured log messages (using g_log_structured() or
742 * g_log_structured_array()). To change the fatal behaviour for specific log
743 * messages, programs must install a custom log writer function using
744 * g_log_set_writer_func(). See
745 * [Using Structured Logging][using-structured-logging].
747 * Returns: the old fatal mask for the log domain
749 GLogLevelFlags
750 g_log_set_fatal_mask (const gchar *log_domain,
751 GLogLevelFlags fatal_mask)
753 GLogLevelFlags old_flags;
754 GLogDomain *domain;
756 if (!log_domain)
757 log_domain = "";
759 /* force errors to be fatal */
760 fatal_mask |= G_LOG_LEVEL_ERROR;
761 /* remove bogus flag */
762 fatal_mask &= ~G_LOG_FLAG_FATAL;
764 g_mutex_lock (&g_messages_lock);
766 domain = g_log_find_domain_L (log_domain);
767 if (!domain)
768 domain = g_log_domain_new_L (log_domain);
769 old_flags = domain->fatal_mask;
771 domain->fatal_mask = fatal_mask;
772 g_log_domain_check_free_L (domain);
774 g_mutex_unlock (&g_messages_lock);
776 return old_flags;
780 * g_log_set_handler:
781 * @log_domain: (nullable): the log domain, or %NULL for the default ""
782 * application domain
783 * @log_levels: the log levels to apply the log handler for.
784 * To handle fatal and recursive messages as well, combine
785 * the log levels with the #G_LOG_FLAG_FATAL and
786 * #G_LOG_FLAG_RECURSION bit flags.
787 * @log_func: the log handler function
788 * @user_data: data passed to the log handler
790 * Sets the log handler for a domain and a set of log levels.
791 * To handle fatal and recursive messages the @log_levels parameter
792 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
793 * bit flags.
795 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
796 * you want to set a handler for this log level you must combine it with
797 * #G_LOG_FLAG_FATAL.
799 * This has no effect if structured logging is enabled; see
800 * [Using Structured Logging][using-structured-logging].
802 * Here is an example for adding a log handler for all warning messages
803 * in the default domain:
804 * |[<!-- language="C" -->
805 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
806 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
807 * ]|
809 * This example adds a log handler for all critical messages from GTK+:
810 * |[<!-- language="C" -->
811 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
812 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
813 * ]|
815 * This example adds a log handler for all messages from GLib:
816 * |[<!-- language="C" -->
817 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
818 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
819 * ]|
821 * Returns: the id of the new handler
823 guint
824 g_log_set_handler (const gchar *log_domain,
825 GLogLevelFlags log_levels,
826 GLogFunc log_func,
827 gpointer user_data)
829 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
833 * g_log_set_handler_full: (rename-to g_log_set_handler)
834 * @log_domain: (nullable): the log domain, or %NULL for the default ""
835 * application domain
836 * @log_levels: the log levels to apply the log handler for.
837 * To handle fatal and recursive messages as well, combine
838 * the log levels with the #G_LOG_FLAG_FATAL and
839 * #G_LOG_FLAG_RECURSION bit flags.
840 * @log_func: the log handler function
841 * @user_data: data passed to the log handler
842 * @destroy: destroy notify for @user_data, or %NULL
844 * Like g_log_sets_handler(), but takes a destroy notify for the @user_data.
846 * This has no effect if structured logging is enabled; see
847 * [Using Structured Logging][using-structured-logging].
849 * Returns: the id of the new handler
851 * Since: 2.46
853 guint
854 g_log_set_handler_full (const gchar *log_domain,
855 GLogLevelFlags log_levels,
856 GLogFunc log_func,
857 gpointer user_data,
858 GDestroyNotify destroy)
860 static guint handler_id = 0;
861 GLogDomain *domain;
862 GLogHandler *handler;
864 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
865 g_return_val_if_fail (log_func != NULL, 0);
867 if (!log_domain)
868 log_domain = "";
870 handler = g_new (GLogHandler, 1);
872 g_mutex_lock (&g_messages_lock);
874 domain = g_log_find_domain_L (log_domain);
875 if (!domain)
876 domain = g_log_domain_new_L (log_domain);
878 handler->id = ++handler_id;
879 handler->log_level = log_levels;
880 handler->log_func = log_func;
881 handler->data = user_data;
882 handler->destroy = destroy;
883 handler->next = domain->handlers;
884 domain->handlers = handler;
886 g_mutex_unlock (&g_messages_lock);
888 return handler_id;
892 * g_log_set_default_handler:
893 * @log_func: the log handler function
894 * @user_data: data passed to the log handler
896 * Installs a default log handler which is used if no
897 * log handler has been set for the particular log domain
898 * and log level combination. By default, GLib uses
899 * g_log_default_handler() as default log handler.
901 * This has no effect if structured logging is enabled; see
902 * [Using Structured Logging][using-structured-logging].
904 * Returns: the previous default log handler
906 * Since: 2.6
908 GLogFunc
909 g_log_set_default_handler (GLogFunc log_func,
910 gpointer user_data)
912 GLogFunc old_log_func;
914 g_mutex_lock (&g_messages_lock);
915 old_log_func = default_log_func;
916 default_log_func = log_func;
917 default_log_data = user_data;
918 g_mutex_unlock (&g_messages_lock);
920 return old_log_func;
924 * g_test_log_set_fatal_handler:
925 * @log_func: the log handler function.
926 * @user_data: data passed to the log handler.
928 * Installs a non-error fatal log handler which can be
929 * used to decide whether log messages which are counted
930 * as fatal abort the program.
932 * The use case here is that you are running a test case
933 * that depends on particular libraries or circumstances
934 * and cannot prevent certain known critical or warning
935 * messages. So you install a handler that compares the
936 * domain and message to precisely not abort in such a case.
938 * Note that the handler is reset at the beginning of
939 * any test case, so you have to set it inside each test
940 * function which needs the special behavior.
942 * This handler has no effect on g_error messages.
944 * This handler also has no effect on structured log messages (using
945 * g_log_structured() or g_log_structured_array()). To change the fatal
946 * behaviour for specific log messages, programs must install a custom log
947 * writer function using g_log_set_writer_func().See
948 * [Using Structured Logging][using-structured-logging].
950 * Since: 2.22
952 void
953 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
954 gpointer user_data)
956 g_mutex_lock (&g_messages_lock);
957 fatal_log_func = log_func;
958 fatal_log_data = user_data;
959 g_mutex_unlock (&g_messages_lock);
963 * g_log_remove_handler:
964 * @log_domain: the log domain
965 * @handler_id: the id of the handler, which was returned
966 * in g_log_set_handler()
968 * Removes the log handler.
970 * This has no effect if structured logging is enabled; see
971 * [Using Structured Logging][using-structured-logging].
973 void
974 g_log_remove_handler (const gchar *log_domain,
975 guint handler_id)
977 GLogDomain *domain;
979 g_return_if_fail (handler_id > 0);
981 if (!log_domain)
982 log_domain = "";
984 g_mutex_lock (&g_messages_lock);
985 domain = g_log_find_domain_L (log_domain);
986 if (domain)
988 GLogHandler *work, *last;
990 last = NULL;
991 work = domain->handlers;
992 while (work)
994 if (work->id == handler_id)
996 if (last)
997 last->next = work->next;
998 else
999 domain->handlers = work->next;
1000 g_log_domain_check_free_L (domain);
1001 g_mutex_unlock (&g_messages_lock);
1002 if (work->destroy)
1003 work->destroy (work->data);
1004 g_free (work);
1005 return;
1007 last = work;
1008 work = last->next;
1011 g_mutex_unlock (&g_messages_lock);
1012 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1013 G_STRLOC, handler_id, log_domain);
1016 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1017 (wc == 0x7f) || \
1018 (wc >= 0x80 && wc < 0xa0)))
1020 static gchar*
1021 strdup_convert (const gchar *string,
1022 const gchar *charset)
1024 if (!g_utf8_validate (string, -1, NULL))
1026 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1027 guchar *p;
1029 for (p = (guchar *)string; *p; p++)
1031 if (CHAR_IS_SAFE(*p) &&
1032 !(*p == '\r' && *(p + 1) != '\n') &&
1033 *p < 0x80)
1034 g_string_append_c (gstring, *p);
1035 else
1036 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1039 return g_string_free (gstring, FALSE);
1041 else
1043 GError *err = NULL;
1045 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1046 if (result)
1047 return result;
1048 else
1050 /* Not thread-safe, but doesn't matter if we print the warning twice
1052 static gboolean warned = FALSE;
1053 if (!warned)
1055 warned = TRUE;
1056 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1058 g_error_free (err);
1060 return g_strdup (string);
1065 /* For a radix of 8 we need at most 3 output bytes for 1 input
1066 * byte. Additionally we might need up to 2 output bytes for the
1067 * readix prefix and 1 byte for the trailing NULL.
1069 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1071 static void
1072 format_unsigned (gchar *buf,
1073 gulong num,
1074 guint radix)
1076 gulong tmp;
1077 gchar c;
1078 gint i, n;
1080 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1082 if (radix != 8 && radix != 10 && radix != 16)
1084 *buf = '\000';
1085 return;
1088 if (!num)
1090 *buf++ = '0';
1091 *buf = '\000';
1092 return;
1095 if (radix == 16)
1097 *buf++ = '0';
1098 *buf++ = 'x';
1100 else if (radix == 8)
1102 *buf++ = '0';
1105 n = 0;
1106 tmp = num;
1107 while (tmp)
1109 tmp /= radix;
1110 n++;
1113 i = n;
1115 /* Again we can't use g_assert; actually this check should _never_ fail. */
1116 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1118 *buf = '\000';
1119 return;
1122 while (num)
1124 i--;
1125 c = (num % radix);
1126 if (c < 10)
1127 buf[i] = c + '0';
1128 else
1129 buf[i] = c + 'a' - 10;
1130 num /= radix;
1133 buf[n] = '\000';
1136 /* string size big enough to hold level prefix */
1137 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1139 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1141 /* these are emitted by the default log handler */
1142 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1143 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1144 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1146 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1147 gboolean use_color);
1148 static const gchar *color_reset (gboolean use_color);
1150 static FILE *
1151 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1152 GLogLevelFlags log_level,
1153 gboolean use_color)
1155 gboolean to_stdout = TRUE;
1157 /* we may not call _any_ GLib functions here */
1159 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1161 switch (log_level & G_LOG_LEVEL_MASK)
1163 case G_LOG_LEVEL_ERROR:
1164 strcat (level_prefix, "ERROR");
1165 to_stdout = FALSE;
1166 break;
1167 case G_LOG_LEVEL_CRITICAL:
1168 strcat (level_prefix, "CRITICAL");
1169 to_stdout = FALSE;
1170 break;
1171 case G_LOG_LEVEL_WARNING:
1172 strcat (level_prefix, "WARNING");
1173 to_stdout = FALSE;
1174 break;
1175 case G_LOG_LEVEL_MESSAGE:
1176 strcat (level_prefix, "Message");
1177 to_stdout = FALSE;
1178 break;
1179 case G_LOG_LEVEL_INFO:
1180 strcat (level_prefix, "INFO");
1181 break;
1182 case G_LOG_LEVEL_DEBUG:
1183 strcat (level_prefix, "DEBUG");
1184 break;
1185 default:
1186 if (log_level)
1188 strcat (level_prefix, "LOG-");
1189 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1191 else
1192 strcat (level_prefix, "LOG");
1193 break;
1196 strcat (level_prefix, color_reset (use_color));
1198 if (log_level & G_LOG_FLAG_RECURSION)
1199 strcat (level_prefix, " (recursed)");
1200 if (log_level & ALERT_LEVELS)
1201 strcat (level_prefix, " **");
1203 #ifdef G_OS_WIN32
1204 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1205 win32_keep_fatal_message = TRUE;
1206 #endif
1207 return to_stdout ? stdout : stderr;
1210 typedef struct {
1211 gchar *log_domain;
1212 GLogLevelFlags log_level;
1213 gchar *pattern;
1214 } GTestExpectedMessage;
1216 static GSList *expected_messages = NULL;
1219 * g_logv:
1220 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1221 * application domain
1222 * @log_level: the log level
1223 * @format: the message format. See the printf() documentation
1224 * @args: the parameters to insert into the format string
1226 * Logs an error or debugging message.
1228 * If the log level has been set as fatal, the abort()
1229 * function is called to terminate the program.
1231 * If g_log_default_handler() is used as the log handler function, a new-line
1232 * character will automatically be appended to @..., and need not be entered
1233 * manually.
1235 * If [structured logging is enabled][using-structured-logging] this will
1236 * output via the structured log writer function (see g_log_set_writer_func()).
1238 void
1239 g_logv (const gchar *log_domain,
1240 GLogLevelFlags log_level,
1241 const gchar *format,
1242 va_list args)
1244 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1245 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1246 gchar buffer[1025], *msg, *msg_alloc = NULL;
1247 gint i;
1249 log_level &= G_LOG_LEVEL_MASK;
1250 if (!log_level)
1251 return;
1253 if (log_level & G_LOG_FLAG_RECURSION)
1255 /* we use a stack buffer of fixed size, since we're likely
1256 * in an out-of-memory situation
1258 gsize size G_GNUC_UNUSED;
1260 size = _g_vsnprintf (buffer, 1024, format, args);
1261 msg = buffer;
1263 else
1264 msg = msg_alloc = g_strdup_vprintf (format, args);
1266 if (expected_messages)
1268 GTestExpectedMessage *expected = expected_messages->data;
1270 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1271 ((log_level & expected->log_level) == expected->log_level) &&
1272 g_pattern_match_simple (expected->pattern, msg))
1274 expected_messages = g_slist_delete_link (expected_messages,
1275 expected_messages);
1276 g_free (expected->log_domain);
1277 g_free (expected->pattern);
1278 g_free (expected);
1279 g_free (msg_alloc);
1280 return;
1282 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1284 gchar level_prefix[STRING_BUFFER_SIZE];
1285 gchar *expected_message;
1287 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1288 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1289 expected->log_domain ? expected->log_domain : "**",
1290 level_prefix, expected->pattern);
1291 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1292 g_free (expected_message);
1294 log_level |= G_LOG_FLAG_FATAL;
1298 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1300 GLogLevelFlags test_level;
1302 test_level = 1 << i;
1303 if (log_level & test_level)
1305 GLogDomain *domain;
1306 GLogFunc log_func;
1307 GLogLevelFlags domain_fatal_mask;
1308 gpointer data = NULL;
1309 gboolean masquerade_fatal = FALSE;
1310 guint depth;
1312 if (was_fatal)
1313 test_level |= G_LOG_FLAG_FATAL;
1314 if (was_recursion)
1315 test_level |= G_LOG_FLAG_RECURSION;
1317 /* check recursion and lookup handler */
1318 g_mutex_lock (&g_messages_lock);
1319 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1320 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1321 if (depth)
1322 test_level |= G_LOG_FLAG_RECURSION;
1323 depth++;
1324 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1325 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1326 test_level |= G_LOG_FLAG_FATAL;
1327 if (test_level & G_LOG_FLAG_RECURSION)
1328 log_func = _g_log_fallback_handler;
1329 else
1330 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1331 domain = NULL;
1332 g_mutex_unlock (&g_messages_lock);
1334 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1336 log_func (log_domain, test_level, msg, data);
1338 if ((test_level & G_LOG_FLAG_FATAL)
1339 && !(test_level & G_LOG_LEVEL_ERROR))
1341 masquerade_fatal = fatal_log_func
1342 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1345 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1347 #ifdef G_OS_WIN32
1348 if (win32_keep_fatal_message)
1350 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1352 MessageBox (NULL, locale_msg, NULL,
1353 MB_ICONERROR|MB_SETFOREGROUND);
1355 #endif /* !G_OS_WIN32 */
1357 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1360 depth--;
1361 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1365 g_free (msg_alloc);
1369 * g_log:
1370 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1371 * for the default
1372 * @log_level: the log level, either from #GLogLevelFlags
1373 * or a user-defined level
1374 * @format: the message format. See the printf() documentation
1375 * @...: the parameters to insert into the format string
1377 * Logs an error or debugging message.
1379 * If the log level has been set as fatal, the abort()
1380 * function is called to terminate the program.
1382 * If g_log_default_handler() is used as the log handler function, a new-line
1383 * character will automatically be appended to @..., and need not be entered
1384 * manually.
1386 * If [structured logging is enabled][using-structured-logging] this will
1387 * output via the structured log writer function (see g_log_set_writer_func()).
1389 void
1390 g_log (const gchar *log_domain,
1391 GLogLevelFlags log_level,
1392 const gchar *format,
1393 ...)
1395 va_list args;
1397 va_start (args, format);
1398 g_logv (log_domain, log_level, format, args);
1399 va_end (args);
1402 /* Return value must be 1 byte long (plus nul byte).
1403 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1405 static const gchar *
1406 log_level_to_priority (GLogLevelFlags log_level)
1408 if (log_level & G_LOG_LEVEL_ERROR)
1409 return "3";
1410 else if (log_level & G_LOG_LEVEL_CRITICAL)
1411 return "4";
1412 else if (log_level & G_LOG_LEVEL_WARNING)
1413 return "4";
1414 else if (log_level & G_LOG_LEVEL_MESSAGE)
1415 return "5";
1416 else if (log_level & G_LOG_LEVEL_INFO)
1417 return "6";
1418 else if (log_level & G_LOG_LEVEL_DEBUG)
1419 return "7";
1421 /* Default to LOG_NOTICE for custom log levels. */
1422 return "5";
1425 static FILE *
1426 log_level_to_file (GLogLevelFlags log_level)
1428 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1429 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1430 return stderr;
1431 else
1432 return stdout;
1435 static const gchar *
1436 log_level_to_color (GLogLevelFlags log_level,
1437 gboolean use_color)
1439 /* we may not call _any_ GLib functions here */
1441 if (!use_color)
1442 return "";
1444 if (log_level & G_LOG_LEVEL_ERROR)
1445 return "\033[1;31m";
1446 else if (log_level & G_LOG_LEVEL_CRITICAL)
1447 return "\033[1;35m";
1448 else if (log_level & G_LOG_LEVEL_WARNING)
1449 return "\033[1;33m";
1450 else if (log_level & G_LOG_LEVEL_MESSAGE)
1451 return "\033[1;32m";
1452 else if (log_level & G_LOG_LEVEL_INFO)
1453 return "\033[1;32m";
1454 else if (log_level & G_LOG_LEVEL_DEBUG)
1455 return "\033[1;32m";
1457 /* No color for custom log levels. */
1458 return "";
1461 static const gchar *
1462 color_reset (gboolean use_color)
1464 /* we may not call _any_ GLib functions here */
1466 if (!use_color)
1467 return "";
1469 return "\033[0m";
1472 #ifdef G_OS_WIN32
1474 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1475 * so we need to check the name of the pipe if _isatty (fd) == 0
1478 static gboolean
1479 win32_is_pipe_tty (int fd)
1481 gboolean result = FALSE;
1482 int error;
1483 HANDLE h_fd;
1484 FILE_NAME_INFO *info = NULL;
1485 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1486 wchar_t *name = NULL;
1487 gint length;
1489 /* XXX: Remove once XP support really dropped */
1490 #if _WIN32_WINNT < 0x0600
1491 HANDLE h_kerneldll = NULL;
1492 fGetFileInformationByHandleEx *GetFileInformationByHandleEx;
1493 #endif
1495 h_fd = (HANDLE) _get_osfhandle (fd);
1497 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1498 goto done_query;
1500 /* The following check is available on Vista or later, so on XP, no color support */
1501 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1503 /* XXX: Remove once XP support really dropped */
1504 #if _WIN32_WINNT < 0x0600
1505 h_kerneldll = LoadLibraryW (L"kernel32.dll");
1507 if (h_kerneldll == NULL)
1508 goto done_query;
1510 GetFileInformationByHandleEx =
1511 (fGetFileInformationByHandleEx *) GetProcAddress (h_kerneldll, "GetFileInformationByHandleEx");
1513 if (GetFileInformationByHandleEx == NULL)
1514 goto done_query;
1515 #endif
1517 info = g_try_malloc (info_size);
1519 if (info == NULL ||
1520 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1521 goto done_query;
1523 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1524 name = info->FileName;
1526 length = wcslen (L"\\cygwin-");
1527 if (wcsncmp (name, L"\\cygwin-", length))
1529 length = wcslen (L"\\msys-");
1530 if (wcsncmp (name, L"\\msys-", length))
1531 goto done_query;
1534 name += length;
1535 length = wcsspn (name, L"0123456789abcdefABCDEF");
1536 if (length != 16)
1537 goto done_query;
1539 name += length;
1540 length = wcslen (L"-pty");
1541 if (wcsncmp (name, L"-pty", length))
1542 goto done_query;
1544 name += length;
1545 length = wcsspn (name, L"0123456789");
1546 if (length != 1)
1547 goto done_query;
1549 name += length;
1550 length = wcslen (L"-to-master");
1551 if (wcsncmp (name, L"-to-master", length))
1553 length = wcslen (L"-from-master");
1554 if (wcsncmp (name, L"-from-master", length))
1555 goto done_query;
1558 result = TRUE;
1560 done_query:
1561 if (info != NULL)
1562 g_free (info);
1564 /* XXX: Remove once XP support really dropped */
1565 #if _WIN32_WINNT < 0x0600
1566 if (h_kerneldll != NULL)
1567 FreeLibrary (h_kerneldll);
1568 #endif
1570 return result;
1572 #endif
1574 #pragma GCC diagnostic push
1575 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1578 * g_log_structured:
1579 * @log_domain: log domain, usually %G_LOG_DOMAIN
1580 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1581 * level
1582 * @...: key-value pairs of structured data to add to the log entry, followed
1583 * by the key "MESSAGE", followed by a printf()-style message format,
1584 * followed by parameters to insert in the format string
1586 * Log a message with structured data. The message will be passed through to
1587 * the log writer set by the application using g_log_set_writer_func(). If the
1588 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1589 * be aborted at the end of this function.
1591 * The structured data is provided as key–value pairs, where keys are UTF-8
1592 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1593 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1594 * structured data, use g_log_structured_array(). The keys for structured data
1595 * should follow the [systemd journal
1596 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1597 * specification. It is suggested that custom keys are namespaced according to
1598 * the code which sets them. For example, custom keys from GLib all have a
1599 * `GLIB_` prefix.
1601 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1602 * be converted into a
1603 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1604 * field. The format string will have its placeholders substituted for the provided
1605 * values and be converted into a
1606 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1607 * field.
1609 * Other fields you may commonly want to pass into this function:
1611 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1612 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1613 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1614 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1615 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1617 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1618 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1619 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1620 * glib.h.
1622 * For example:
1623 * |[<!-- language="C" -->
1624 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1625 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1626 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1627 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1628 * some_pointer, some_integer);
1629 * ]|
1631 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1632 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1633 * If adding a `MESSAGE_ID`, consider shipping a [message
1634 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1635 * your software.
1637 * To pass a user data pointer to the log writer function which is specific to
1638 * this logging call, you must use g_log_structured_array() and pass the pointer
1639 * as a field with #GLogField.length set to zero, otherwise it will be
1640 * interpreted as a string.
1642 * For example:
1643 * |[<!-- language="C" -->
1644 * const GLogField fields[] = {
1645 * { "MESSAGE", "This is a debug message.", -1 },
1646 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1647 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1648 * { "MY_APPLICATION_STATE", state_object, 0 },
1649 * };
1650 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1651 * ]|
1653 * Note also that, even if no other structured fields are specified, there
1654 * must always be a "MESSAGE" key before the format string. The "MESSAGE"-format
1655 * pair has to be the last of the key-value pairs, and "MESSAGE" is the only
1656 * field for which printf()-style formatting is supported.
1658 * The default writer function for `stdout` and `stderr` will automatically
1659 * append a new-line character after the message, so you should not add one
1660 * manually to the format string.
1662 * Since: 2.50
1664 void
1665 g_log_structured (const gchar *log_domain,
1666 GLogLevelFlags log_level,
1667 ...)
1669 va_list args;
1670 gchar buffer[1025], *message_allocated = NULL;
1671 const char *format;
1672 const gchar *message;
1673 gpointer p;
1674 gsize n_fields, i;
1675 GLogField stack_fields[16];
1676 GLogField *fields = stack_fields;
1677 GLogField *fields_allocated = NULL;
1678 GArray *array = NULL;
1680 va_start (args, log_level);
1682 /* MESSAGE and PRIORITY are a given */
1683 n_fields = 2;
1685 if (log_domain)
1686 n_fields++;
1688 for (p = va_arg (args, gchar *), i = n_fields;
1689 strcmp (p, "MESSAGE") != 0;
1690 p = va_arg (args, gchar *), i++)
1692 GLogField field;
1693 const gchar *key = p;
1694 gconstpointer value = va_arg (args, gpointer);
1696 field.key = key;
1697 field.value = value;
1698 field.length = -1;
1700 if (i < 16)
1701 stack_fields[i] = field;
1702 else
1704 /* Don't allow dynamic allocation, since we're likely
1705 * in an out-of-memory situation. For lack of a better solution,
1706 * just ignore further key-value pairs.
1708 if (log_level & G_LOG_FLAG_RECURSION)
1709 continue;
1711 if (i == 16)
1713 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1714 g_array_append_vals (array, stack_fields, 16);
1717 g_array_append_val (array, field);
1721 n_fields = i;
1723 if (array)
1724 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1726 format = va_arg (args, gchar *);
1728 if (log_level & G_LOG_FLAG_RECURSION)
1730 /* we use a stack buffer of fixed size, since we're likely
1731 * in an out-of-memory situation
1733 gsize size G_GNUC_UNUSED;
1735 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1736 message = buffer;
1738 else
1740 message = message_allocated = g_strdup_vprintf (format, args);
1743 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1744 fields[0].key = "MESSAGE";
1745 fields[0].value = message;
1746 fields[0].length = -1;
1748 fields[1].key = "PRIORITY";
1749 fields[1].value = log_level_to_priority (log_level);
1750 fields[1].length = -1;
1752 if (log_domain)
1754 fields[2].key = "GLIB_DOMAIN";
1755 fields[2].value = log_domain;
1756 fields[2].length = -1;
1759 /* Log it. */
1760 g_log_structured_array (log_level, fields, n_fields);
1762 g_free (fields_allocated);
1763 g_free (message_allocated);
1765 va_end (args);
1769 * g_log_variant:
1770 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1771 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1772 * level
1773 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1774 * containing the key-value pairs of message data.
1776 * Log a message with structured data, accepting the data within a #GVariant. This
1777 * version is especially useful for use in other languages, via introspection.
1779 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1780 * contain the text shown to the user.
1782 * The values in the @fields dictionary are likely to be of type String
1783 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1784 * supported. In this case the message is handled as binary and will be forwarded
1785 * to the log writer as such. The size of the array should not be higher than
1786 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1787 * g_variant_print() will be used to convert the value into a string.
1789 * For more details on its usage and about the parameters, see g_log_structured().
1791 * Since: 2.50
1794 void
1795 g_log_variant (const gchar *log_domain,
1796 GLogLevelFlags log_level,
1797 GVariant *fields)
1799 GVariantIter iter;
1800 GVariant *value;
1801 gchar *key;
1802 GArray *fields_array;
1803 GLogField field;
1804 GSList *values_list, *print_list;
1806 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1808 values_list = print_list = NULL;
1809 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1811 field.key = "PRIORITY";
1812 field.value = log_level_to_priority (log_level);
1813 field.length = -1;
1814 g_array_append_val (fields_array, field);
1816 if (log_domain)
1818 field.key = "GLIB_DOMAIN";
1819 field.value = log_domain;
1820 field.length = -1;
1821 g_array_append_val (fields_array, field);
1824 g_variant_iter_init (&iter, fields);
1825 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1827 gboolean defer_unref = TRUE;
1829 field.key = key;
1830 field.length = -1;
1832 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1834 field.value = g_variant_get_string (value, NULL);
1836 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1838 gsize s;
1839 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1840 if (G_LIKELY (s <= G_MAXSSIZE))
1842 field.length = s;
1844 else
1846 _g_fprintf (stderr,
1847 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1848 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1849 " bytes.", s);
1850 field.length = G_MAXSSIZE;
1853 else
1855 char *s = g_variant_print (value, FALSE);
1856 field.value = s;
1857 print_list = g_slist_prepend (print_list, s);
1858 defer_unref = FALSE;
1861 g_array_append_val (fields_array, field);
1863 if (G_LIKELY (defer_unref))
1864 values_list = g_slist_prepend (values_list, value);
1865 else
1866 g_variant_unref (value);
1869 /* Log it. */
1870 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1872 g_array_free (fields_array, TRUE);
1873 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1874 g_slist_free_full (print_list, g_free);
1878 #pragma GCC diagnostic pop
1880 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1881 const GLogField *fields,
1882 gsize n_fields,
1883 gpointer user_data);
1886 * g_log_structured_array:
1887 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1888 * level
1889 * @fields: (array length=n_fields): key–value pairs of structured data to add
1890 * to the log message
1891 * @n_fields: number of elements in the @fields array
1893 * Log a message with structured data. The message will be passed through to the
1894 * log writer set by the application using g_log_set_writer_func(). If the
1895 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1896 * be aborted at the end of this function.
1898 * See g_log_structured() for more documentation.
1900 * This assumes that @log_level is already present in @fields (typically as the
1901 * `PRIORITY` field).
1903 * Since: 2.50
1905 void
1906 g_log_structured_array (GLogLevelFlags log_level,
1907 const GLogField *fields,
1908 gsize n_fields)
1910 GLogWriterFunc writer_func;
1911 gpointer writer_user_data;
1912 gboolean recursion;
1913 guint depth;
1915 if (n_fields == 0)
1916 return;
1918 /* Check for recursion and look up the writer function. */
1919 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1920 recursion = (depth > 0);
1922 g_mutex_lock (&g_messages_lock);
1924 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1925 writer_user_data = log_writer_user_data;
1927 g_mutex_unlock (&g_messages_lock);
1929 /* Write the log entry. */
1930 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1932 g_assert (writer_func != NULL);
1933 writer_func (log_level, fields, n_fields, writer_user_data);
1935 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1937 /* Abort if the message was fatal. */
1938 if (log_level & G_LOG_FATAL_MASK)
1939 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1943 * g_log_set_writer_func:
1944 * @func: log writer function, which must not be %NULL
1945 * @user_data: (closure func): user data to pass to @func
1946 * @user_data_free: (destroy func): function to free @user_data once it’s
1947 * finished with, if non-%NULL
1949 * Set a writer function which will be called to format and write out each log
1950 * message. Each program should set a writer function, or the default writer
1951 * (g_log_writer_default()) will be used.
1953 * Libraries **must not** call this function — only programs are allowed to
1954 * install a writer function, as there must be a single, central point where
1955 * log messages are formatted and outputted.
1957 * There can only be one writer function. It is an error to set more than one.
1959 * Since: 2.50
1961 void
1962 g_log_set_writer_func (GLogWriterFunc func,
1963 gpointer user_data,
1964 GDestroyNotify user_data_free)
1966 g_return_if_fail (func != NULL);
1968 g_mutex_lock (&g_messages_lock);
1969 log_writer_func = func;
1970 log_writer_user_data = user_data;
1971 log_writer_user_data_free = user_data_free;
1972 g_mutex_unlock (&g_messages_lock);
1976 * g_log_writer_supports_color:
1977 * @output_fd: output file descriptor to check
1979 * Check whether the given @output_fd file descriptor supports ANSI color
1980 * escape sequences. If so, they can safely be used when formatting log
1981 * messages.
1983 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
1984 * Since: 2.50
1986 gboolean
1987 g_log_writer_supports_color (gint output_fd)
1989 #ifdef G_OS_WIN32
1990 gboolean result = FALSE;
1992 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
1993 _invalid_parameter_handler oldHandler, newHandler;
1994 int prev_report_mode = 0;
1995 #endif
1997 #endif
1999 g_return_val_if_fail (output_fd >= 0, FALSE);
2001 /* FIXME: This check could easily be expanded in future to be more robust
2002 * against different types of terminal, which still vary in their color
2003 * support. cmd.exe on Windows, for example, supports ANSI colors only
2004 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2005 * The Windows 10 color support is supported on:
2006 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2007 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2008 * but not:
2009 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2010 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2012 * On UNIX systems, we probably want to use the functions from terminfo to
2013 * work out whether colors are supported.
2015 * Some examples:
2016 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2017 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2018 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2019 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2021 #ifdef G_OS_WIN32
2023 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2024 /* Set up our empty invalid parameter handler, for isatty(),
2025 * in case of bad fd's passed in for isatty(), so that
2026 * msvcrt80.dll+ won't abort the program
2028 newHandler = myInvalidParameterHandler;
2029 oldHandler = _set_invalid_parameter_handler (newHandler);
2031 /* Disable the message box for assertions. */
2032 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2033 #endif
2035 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2037 HANDLE h_output;
2038 DWORD dw_mode;
2040 if (_isatty (output_fd))
2042 h_output = (HANDLE) _get_osfhandle (output_fd);
2044 if (!GetConsoleMode (h_output, &dw_mode))
2045 goto reset_invalid_param_handler;
2047 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2048 result = TRUE;
2050 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2051 goto reset_invalid_param_handler;
2053 result = TRUE;
2057 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2058 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2059 * (bug 775468), on standard Windows consoles, such as cmd.exe
2061 if (!result)
2062 result = win32_is_pipe_tty (output_fd);
2064 reset_invalid_param_handler:
2065 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2066 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2067 _set_invalid_parameter_handler (oldHandler);
2068 #endif
2070 return result;
2071 #else
2072 return isatty (output_fd);
2073 #endif
2076 #if defined(__linux__) && !defined(__BIONIC__)
2077 static int journal_fd = -1;
2079 #ifndef SOCK_CLOEXEC
2080 #define SOCK_CLOEXEC 0
2081 #else
2082 #define HAVE_SOCK_CLOEXEC 1
2083 #endif
2085 static void
2086 open_journal (void)
2088 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2089 return;
2091 #ifndef HAVE_SOCK_CLOEXEC
2092 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2094 close (journal_fd);
2095 journal_fd = -1;
2097 #endif
2099 #endif
2102 * g_log_writer_is_journald:
2103 * @output_fd: output file descriptor to check
2105 * Check whether the given @output_fd file descriptor is a connection to the
2106 * systemd journal, or something else (like a log file or `stdout` or
2107 * `stderr`).
2109 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2110 * Since: 2.50
2112 gboolean
2113 g_log_writer_is_journald (gint output_fd)
2115 #if defined(__linux__) && !defined(__BIONIC__)
2116 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2117 * journal. See: https://github.com/systemd/systemd/issues/2473
2119 static gsize initialized;
2120 static gboolean fd_is_journal = FALSE;
2122 g_return_val_if_fail (output_fd >= 0, FALSE);
2124 if (g_once_init_enter (&initialized))
2126 struct sockaddr_storage addr;
2127 socklen_t addr_len = sizeof(addr);
2128 int err = getpeername (output_fd, (struct sockaddr *) &addr, &addr_len);
2129 if (err == 0 && addr.ss_family == AF_UNIX)
2130 fd_is_journal = g_str_has_prefix (((struct sockaddr_un *)&addr)->sun_path,
2131 "/run/systemd/journal/");
2133 g_once_init_leave (&initialized, TRUE);
2136 return fd_is_journal;
2137 #else
2138 return FALSE;
2139 #endif
2142 static void escape_string (GString *string);
2145 * g_log_writer_format_fields:
2146 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2147 * level
2148 * @fields: (array length=n_fields): key–value pairs of structured data forming
2149 * the log message
2150 * @n_fields: number of elements in the @fields array
2151 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2152 * message, %FALSE to not
2154 * Format a structured log message as a string suitable for outputting to the
2155 * terminal (or elsewhere). This will include the values of all fields it knows
2156 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2157 * documentation for g_log_structured()). It does not include values from
2158 * unknown fields.
2160 * The returned string does **not** have a trailing new-line character. It is
2161 * encoded in the character set of the current locale, which is not necessarily
2162 * UTF-8.
2164 * Returns: (transfer full): string containing the formatted log message, in
2165 * the character set of the current locale
2166 * Since: 2.50
2168 gchar *
2169 g_log_writer_format_fields (GLogLevelFlags log_level,
2170 const GLogField *fields,
2171 gsize n_fields,
2172 gboolean use_color)
2174 gsize i;
2175 const gchar *message = NULL;
2176 const gchar *log_domain = NULL;
2177 gchar level_prefix[STRING_BUFFER_SIZE];
2178 GString *gstring;
2180 /* Extract some common fields. */
2181 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2183 const GLogField *field = &fields[i];
2185 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2186 message = field->value;
2187 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2188 log_domain = field->value;
2191 /* Format things. */
2192 mklevel_prefix (level_prefix, log_level, use_color);
2194 gstring = g_string_new (NULL);
2195 if (log_level & ALERT_LEVELS)
2196 g_string_append (gstring, "\n");
2197 if (!log_domain)
2198 g_string_append (gstring, "** ");
2200 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2201 (log_level & G_LOG_LEVEL_MASK))
2203 const gchar *prg_name = g_get_prgname ();
2204 gulong pid = getpid ();
2206 if (prg_name == NULL)
2207 g_string_append_printf (gstring, "(process:%lu): ", pid);
2208 else
2209 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2212 if (log_domain != NULL)
2214 g_string_append (gstring, log_domain);
2215 g_string_append_c (gstring, '-');
2217 g_string_append (gstring, level_prefix);
2219 g_string_append (gstring, ": ");
2220 if (message == NULL)
2222 g_string_append (gstring, "(NULL) message");
2224 else
2226 GString *msg;
2227 const gchar *charset;
2229 msg = g_string_new (message);
2230 escape_string (msg);
2232 if (g_get_charset (&charset))
2234 /* charset is UTF-8 already */
2235 g_string_append (gstring, msg->str);
2237 else
2239 gchar *lstring = strdup_convert (msg->str, charset);
2240 g_string_append (gstring, lstring);
2241 g_free (lstring);
2244 g_string_free (msg, TRUE);
2247 return g_string_free (gstring, FALSE);
2250 #if defined(__linux__) && !defined(__BIONIC__)
2251 static int
2252 journal_sendv (struct iovec *iov,
2253 gsize iovlen)
2255 int buf_fd = -1;
2256 struct msghdr mh;
2257 struct sockaddr_un sa;
2258 union {
2259 struct cmsghdr cmsghdr;
2260 guint8 buf[CMSG_SPACE(sizeof(int))];
2261 } control;
2262 struct cmsghdr *cmsg;
2263 char path[] = "/dev/shm/journal.XXXXXX";
2265 if (journal_fd < 0)
2266 open_journal ();
2268 if (journal_fd < 0)
2269 return -1;
2271 memset (&sa, 0, sizeof (sa));
2272 sa.sun_family = AF_UNIX;
2273 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2274 return -1;
2276 memset (&mh, 0, sizeof (mh));
2277 mh.msg_name = &sa;
2278 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2279 mh.msg_iov = iov;
2280 mh.msg_iovlen = iovlen;
2282 retry:
2283 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2284 return 0;
2286 if (errno == EINTR)
2287 goto retry;
2289 if (errno != EMSGSIZE && errno != ENOBUFS)
2290 return -1;
2292 /* Message was too large, so dump to temporary file
2293 * and pass an FD to the journal
2295 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2296 return -1;
2298 if (unlink (path) < 0)
2300 close (buf_fd);
2301 return -1;
2304 if (writev (buf_fd, iov, iovlen) < 0)
2306 close (buf_fd);
2307 return -1;
2310 mh.msg_iov = NULL;
2311 mh.msg_iovlen = 0;
2313 memset (&control, 0, sizeof (control));
2314 mh.msg_control = &control;
2315 mh.msg_controllen = sizeof (control);
2317 cmsg = CMSG_FIRSTHDR (&mh);
2318 cmsg->cmsg_level = SOL_SOCKET;
2319 cmsg->cmsg_type = SCM_RIGHTS;
2320 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2321 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2323 mh.msg_controllen = cmsg->cmsg_len;
2325 retry2:
2326 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2327 return 0;
2329 if (errno == EINTR)
2330 goto retry2;
2332 return -1;
2334 #endif
2337 * g_log_writer_journald:
2338 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2339 * level
2340 * @fields: (array length=n_fields): key–value pairs of structured data forming
2341 * the log message
2342 * @n_fields: number of elements in the @fields array
2343 * @user_data: user data passed to g_log_set_writer_func()
2345 * Format a structured log message and send it to the systemd journal as a set
2346 * of key–value pairs. All fields are sent to the journal, but if a field has
2347 * length zero (indicating program-specific data) then only its key will be
2348 * sent.
2350 * This is suitable for use as a #GLogWriterFunc.
2352 * If GLib has been compiled without systemd support, this function is still
2353 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2355 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2356 * Since: 2.50
2358 GLogWriterOutput
2359 g_log_writer_journald (GLogLevelFlags log_level,
2360 const GLogField *fields,
2361 gsize n_fields,
2362 gpointer user_data)
2364 #if defined(__linux__) && !defined(__BIONIC__)
2365 const char equals = '=';
2366 const char newline = '\n';
2367 gsize i, k;
2368 struct iovec *iov, *v;
2369 char *buf;
2370 gint retval;
2372 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2373 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2375 /* According to systemd.journal-fields(7), the journal allows fields in any
2376 * format (including arbitrary binary), but expects text fields to be UTF-8.
2377 * This is great, because we require input strings to be in UTF-8, so no
2378 * conversion is necessary and we don’t need to care about the current
2379 * locale’s character set.
2382 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2383 buf = g_alloca (32 * n_fields);
2385 k = 0;
2386 v = iov;
2387 for (i = 0; i < n_fields; i++)
2389 guint64 length;
2390 gboolean binary;
2392 if (fields[i].length < 0)
2394 length = strlen (fields[i].value);
2395 binary = strchr (fields[i].value, '\n') != NULL;
2397 else
2399 length = fields[i].length;
2400 binary = TRUE;
2403 if (binary)
2405 guint64 nstr;
2407 v[0].iov_base = (gpointer)fields[i].key;
2408 v[0].iov_len = strlen (fields[i].key);
2410 v[1].iov_base = (gpointer)&newline;
2411 v[1].iov_len = 1;
2413 nstr = GUINT64_TO_LE(length);
2414 memcpy (&buf[k], &nstr, sizeof (nstr));
2416 v[2].iov_base = &buf[k];
2417 v[2].iov_len = sizeof (nstr);
2418 v += 3;
2419 k += sizeof (nstr);
2421 else
2423 v[0].iov_base = (gpointer)fields[i].key;
2424 v[0].iov_len = strlen (fields[i].key);
2426 v[1].iov_base = (gpointer)&equals;
2427 v[1].iov_len = 1;
2428 v += 2;
2431 v[0].iov_base = (gpointer)fields[i].value;
2432 v[0].iov_len = length;
2434 v[1].iov_base = (gpointer)&newline;
2435 v[1].iov_len = 1;
2436 v += 2;
2439 retval = journal_sendv (iov, v - iov);
2441 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2442 #else
2443 return G_LOG_WRITER_UNHANDLED;
2444 #endif
2448 * g_log_writer_standard_streams:
2449 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2450 * level
2451 * @fields: (array length=n_fields): key–value pairs of structured data forming
2452 * the log message
2453 * @n_fields: number of elements in the @fields array
2454 * @user_data: user data passed to g_log_set_writer_func()
2456 * Format a structured log message and print it to either `stdout` or `stderr`,
2457 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2458 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2459 * which are understood by this function are included in the formatted string
2460 * which is printed.
2462 * If the output stream supports ANSI color escape sequences, they will be used
2463 * in the output.
2465 * A trailing new-line character is added to the log message when it is printed.
2467 * This is suitable for use as a #GLogWriterFunc.
2469 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2470 * Since: 2.50
2472 GLogWriterOutput
2473 g_log_writer_standard_streams (GLogLevelFlags log_level,
2474 const GLogField *fields,
2475 gsize n_fields,
2476 gpointer user_data)
2478 FILE *stream;
2479 gchar *out = NULL; /* in the current locale’s character set */
2481 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2482 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2484 stream = log_level_to_file (log_level);
2485 if (!stream || fileno (stream) < 0)
2486 return G_LOG_WRITER_UNHANDLED;
2488 out = g_log_writer_format_fields (log_level, fields, n_fields,
2489 g_log_writer_supports_color (fileno (stream)));
2490 _g_fprintf (stream, "%s\n", out);
2491 g_free (out);
2493 return G_LOG_WRITER_HANDLED;
2496 /* The old g_log() API is implemented in terms of the new structured log API.
2497 * However, some of the checks do not line up between the two APIs: the
2498 * structured API only handles fatalness of messages for log levels; the old API
2499 * handles it per-domain as well. Consequently, we need to disable fatalness
2500 * handling in the structured log API when called from the old g_log() API.
2502 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2503 * the first field to g_log_structured_array(), if that is the case.
2505 static gboolean
2506 log_is_old_api (const GLogField *fields,
2507 gsize n_fields)
2509 return (n_fields >= 1 &&
2510 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2511 g_strcmp0 (fields[0].value, "1") == 0);
2515 * g_log_writer_default:
2516 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2517 * level
2518 * @fields: (array length=n_fields): key–value pairs of structured data forming
2519 * the log message
2520 * @n_fields: number of elements in the @fields array
2521 * @user_data: user data passed to g_log_set_writer_func()
2523 * Format a structured log message and output it to the default log destination
2524 * for the platform. On Linux, this is typically the systemd journal, falling
2525 * back to `stdout` or `stderr` if running from the terminal or if output is
2526 * being redirected to a file.
2528 * Support for other platform-specific logging mechanisms may be added in
2529 * future. Distributors of GLib may modify this function to impose their own
2530 * (documented) platform-specific log writing policies.
2532 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2533 * if no other is set using g_log_set_writer_func().
2535 * As with g_log_default_handler(), this function drops debug and informational
2536 * messages unless their log domain (or `all`) is listed in the space-separated
2537 * `G_MESSAGES_DEBUG` environment variable.
2539 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2540 * Since: 2.50
2542 GLogWriterOutput
2543 g_log_writer_default (GLogLevelFlags log_level,
2544 const GLogField *fields,
2545 gsize n_fields,
2546 gpointer user_data)
2548 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2549 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2551 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2552 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2554 const gchar *domains, *log_domain = NULL;
2555 gsize i;
2557 domains = g_getenv ("G_MESSAGES_DEBUG");
2559 if ((log_level & INFO_LEVELS) == 0 ||
2560 domains == NULL)
2561 return G_LOG_WRITER_HANDLED;
2563 for (i = 0; i < n_fields; i++)
2565 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2567 log_domain = fields[i].value;
2568 break;
2572 if (strcmp (domains, "all") != 0 &&
2573 (log_domain == NULL || !strstr (domains, log_domain)))
2574 return G_LOG_WRITER_HANDLED;
2577 /* Mark messages as fatal if they have a level set in
2578 * g_log_set_always_fatal().
2580 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2581 log_level |= G_LOG_FLAG_FATAL;
2583 /* Try logging to the systemd journal as first choice. */
2584 if (g_log_writer_is_journald (fileno (stderr)) &&
2585 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2586 G_LOG_WRITER_HANDLED)
2587 goto handled;
2589 /* FIXME: Add support for the Windows log. */
2591 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2592 G_LOG_WRITER_HANDLED)
2593 goto handled;
2595 return G_LOG_WRITER_UNHANDLED;
2597 handled:
2598 /* Abort if the message was fatal. */
2599 if (log_level & G_LOG_FLAG_FATAL)
2601 #ifdef G_OS_WIN32
2602 if (!g_test_initialized ())
2604 gchar *locale_msg = NULL;
2606 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2607 MessageBox (NULL, locale_msg, NULL,
2608 MB_ICONERROR | MB_SETFOREGROUND);
2609 g_free (locale_msg);
2611 #endif /* !G_OS_WIN32 */
2613 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2616 return G_LOG_WRITER_HANDLED;
2619 static GLogWriterOutput
2620 _g_log_writer_fallback (GLogLevelFlags log_level,
2621 const GLogField *fields,
2622 gsize n_fields,
2623 gpointer user_data)
2625 FILE *stream;
2626 gsize i;
2628 /* we cannot call _any_ GLib functions in this fallback handler,
2629 * which is why we skip UTF-8 conversion, etc.
2630 * since we either recursed or ran out of memory, we're in a pretty
2631 * pathologic situation anyways, what we can do is giving the
2632 * the process ID unconditionally however.
2635 stream = log_level_to_file (log_level);
2637 for (i = 0; i < n_fields; i++)
2639 const GLogField *field = &fields[i];
2641 /* Only print fields we definitely recognise, otherwise we could end up
2642 * printing a random non-string pointer provided by the user to be
2643 * interpreted by their writer function.
2645 if (strcmp (field->key, "MESSAGE") != 0 &&
2646 strcmp (field->key, "MESSAGE_ID") != 0 &&
2647 strcmp (field->key, "PRIORITY") != 0 &&
2648 strcmp (field->key, "CODE_FILE") != 0 &&
2649 strcmp (field->key, "CODE_LINE") != 0 &&
2650 strcmp (field->key, "CODE_FUNC") != 0 &&
2651 strcmp (field->key, "ERRNO") != 0 &&
2652 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2653 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2654 strcmp (field->key, "SYSLOG_PID") != 0 &&
2655 strcmp (field->key, "GLIB_DOMAIN") != 0)
2656 continue;
2658 write_string (stream, field->key);
2659 write_string (stream, "=");
2660 write_string_sized (stream, field->value, field->length);
2663 #ifndef G_OS_WIN32
2665 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2667 format_unsigned (pid_string, getpid (), 10);
2668 write_string (stream, "_PID=");
2669 write_string (stream, pid_string);
2671 #endif
2673 return G_LOG_WRITER_HANDLED;
2677 * g_return_if_fail_warning: (skip)
2678 * @log_domain: (nullable):
2679 * @pretty_function:
2680 * @expression: (nullable):
2682 void
2683 g_return_if_fail_warning (const char *log_domain,
2684 const char *pretty_function,
2685 const char *expression)
2687 g_log (log_domain,
2688 G_LOG_LEVEL_CRITICAL,
2689 "%s: assertion '%s' failed",
2690 pretty_function,
2691 expression);
2695 * g_warn_message: (skip)
2696 * @domain: (nullable):
2697 * @file:
2698 * @line:
2699 * @func:
2700 * @warnexpr: (nullable):
2702 void
2703 g_warn_message (const char *domain,
2704 const char *file,
2705 int line,
2706 const char *func,
2707 const char *warnexpr)
2709 char *s, lstr[32];
2710 g_snprintf (lstr, 32, "%d", line);
2711 if (warnexpr)
2712 s = g_strconcat ("(", file, ":", lstr, "):",
2713 func, func[0] ? ":" : "",
2714 " runtime check failed: (", warnexpr, ")", NULL);
2715 else
2716 s = g_strconcat ("(", file, ":", lstr, "):",
2717 func, func[0] ? ":" : "",
2718 " ", "code should not be reached", NULL);
2719 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2720 g_free (s);
2723 void
2724 g_assert_warning (const char *log_domain,
2725 const char *file,
2726 const int line,
2727 const char *pretty_function,
2728 const char *expression)
2730 if (expression)
2731 g_log (log_domain,
2732 G_LOG_LEVEL_ERROR,
2733 "file %s: line %d (%s): assertion failed: (%s)",
2734 file,
2735 line,
2736 pretty_function,
2737 expression);
2738 else
2739 g_log (log_domain,
2740 G_LOG_LEVEL_ERROR,
2741 "file %s: line %d (%s): should not be reached",
2742 file,
2743 line,
2744 pretty_function);
2745 _g_log_abort (FALSE);
2746 g_abort ();
2750 * g_test_expect_message:
2751 * @log_domain: (nullable): the log domain of the message
2752 * @log_level: the log level of the message
2753 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2755 * Indicates that a message with the given @log_domain and @log_level,
2756 * with text matching @pattern, is expected to be logged. When this
2757 * message is logged, it will not be printed, and the test case will
2758 * not abort.
2760 * This API may only be used with the old logging API (g_log() without
2761 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2762 * API. See [Testing for Messages][testing-for-messages].
2764 * Use g_test_assert_expected_messages() to assert that all
2765 * previously-expected messages have been seen and suppressed.
2767 * You can call this multiple times in a row, if multiple messages are
2768 * expected as a result of a single call. (The messages must appear in
2769 * the same order as the calls to g_test_expect_message().)
2771 * For example:
2773 * |[<!-- language="C" -->
2774 * // g_main_context_push_thread_default() should fail if the
2775 * // context is already owned by another thread.
2776 * g_test_expect_message (G_LOG_DOMAIN,
2777 * G_LOG_LEVEL_CRITICAL,
2778 * "assertion*acquired_context*failed");
2779 * g_main_context_push_thread_default (bad_context);
2780 * g_test_assert_expected_messages ();
2781 * ]|
2783 * Note that you cannot use this to test g_error() messages, since
2784 * g_error() intentionally never returns even if the program doesn't
2785 * abort; use g_test_trap_subprocess() in this case.
2787 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2788 * expected via g_test_expect_message() then they will be ignored.
2790 * Since: 2.34
2792 void
2793 g_test_expect_message (const gchar *log_domain,
2794 GLogLevelFlags log_level,
2795 const gchar *pattern)
2797 GTestExpectedMessage *expected;
2799 g_return_if_fail (log_level != 0);
2800 g_return_if_fail (pattern != NULL);
2801 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2803 expected = g_new (GTestExpectedMessage, 1);
2804 expected->log_domain = g_strdup (log_domain);
2805 expected->log_level = log_level;
2806 expected->pattern = g_strdup (pattern);
2808 expected_messages = g_slist_append (expected_messages, expected);
2811 void
2812 g_test_assert_expected_messages_internal (const char *domain,
2813 const char *file,
2814 int line,
2815 const char *func)
2817 if (expected_messages)
2819 GTestExpectedMessage *expected;
2820 gchar level_prefix[STRING_BUFFER_SIZE];
2821 gchar *message;
2823 expected = expected_messages->data;
2825 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2826 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2827 expected->log_domain ? expected->log_domain : "**",
2828 level_prefix, expected->pattern);
2829 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2830 g_free (message);
2835 * g_test_assert_expected_messages:
2837 * Asserts that all messages previously indicated via
2838 * g_test_expect_message() have been seen and suppressed.
2840 * This API may only be used with the old logging API (g_log() without
2841 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2842 * API. See [Testing for Messages][testing-for-messages].
2844 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2845 * expected via g_test_expect_message() then they will be ignored.
2847 * Since: 2.34
2850 void
2851 _g_log_fallback_handler (const gchar *log_domain,
2852 GLogLevelFlags log_level,
2853 const gchar *message,
2854 gpointer unused_data)
2856 gchar level_prefix[STRING_BUFFER_SIZE];
2857 #ifndef G_OS_WIN32
2858 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2859 #endif
2860 FILE *stream;
2862 /* we cannot call _any_ GLib functions in this fallback handler,
2863 * which is why we skip UTF-8 conversion, etc.
2864 * since we either recursed or ran out of memory, we're in a pretty
2865 * pathologic situation anyways, what we can do is giving the
2866 * the process ID unconditionally however.
2869 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2870 if (!message)
2871 message = "(NULL) message";
2873 #ifndef G_OS_WIN32
2874 format_unsigned (pid_string, getpid (), 10);
2875 #endif
2877 if (log_domain)
2878 write_string (stream, "\n");
2879 else
2880 write_string (stream, "\n** ");
2882 #ifndef G_OS_WIN32
2883 write_string (stream, "(process:");
2884 write_string (stream, pid_string);
2885 write_string (stream, "): ");
2886 #endif
2888 if (log_domain)
2890 write_string (stream, log_domain);
2891 write_string (stream, "-");
2893 write_string (stream, level_prefix);
2894 write_string (stream, ": ");
2895 write_string (stream, message);
2898 static void
2899 escape_string (GString *string)
2901 const char *p = string->str;
2902 gunichar wc;
2904 while (p < string->str + string->len)
2906 gboolean safe;
2908 wc = g_utf8_get_char_validated (p, -1);
2909 if (wc == (gunichar)-1 || wc == (gunichar)-2)
2911 gchar *tmp;
2912 guint pos;
2914 pos = p - string->str;
2916 /* Emit invalid UTF-8 as hex escapes
2918 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
2919 g_string_erase (string, pos, 1);
2920 g_string_insert (string, pos, tmp);
2922 p = string->str + (pos + 4); /* Skip over escape sequence */
2924 g_free (tmp);
2925 continue;
2927 if (wc == '\r')
2929 safe = *(p + 1) == '\n';
2931 else
2933 safe = CHAR_IS_SAFE (wc);
2936 if (!safe)
2938 gchar *tmp;
2939 guint pos;
2941 pos = p - string->str;
2943 /* Largest char we escape is 0x0a, so we don't have to worry
2944 * about 8-digit \Uxxxxyyyy
2946 tmp = g_strdup_printf ("\\u%04x", wc);
2947 g_string_erase (string, pos, g_utf8_next_char (p) - p);
2948 g_string_insert (string, pos, tmp);
2949 g_free (tmp);
2951 p = string->str + (pos + 6); /* Skip over escape sequence */
2953 else
2954 p = g_utf8_next_char (p);
2959 * g_log_default_handler:
2960 * @log_domain: (nullable): the log domain of the message, or %NULL for the
2961 * default "" application domain
2962 * @log_level: the level of the message
2963 * @message: (nullable): the message
2964 * @unused_data: (nullable): data passed from g_log() which is unused
2966 * The default log handler set up by GLib; g_log_set_default_handler()
2967 * allows to install an alternate default log handler.
2968 * This is used if no log handler has been set for the particular log
2969 * domain and log level combination. It outputs the message to stderr
2970 * or stdout and if the log level is fatal it calls abort(). It automatically
2971 * prints a new-line character after the message, so one does not need to be
2972 * manually included in @message.
2974 * The behavior of this log handler can be influenced by a number of
2975 * environment variables:
2977 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
2978 * messages should be prefixed by the program name and PID of the
2979 * aplication.
2981 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
2982 * which debug and informational messages are printed. By default
2983 * these messages are not printed.
2985 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
2986 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
2987 * the rest.
2989 * This has no effect if structured logging is enabled; see
2990 * [Using Structured Logging][using-structured-logging].
2992 void
2993 g_log_default_handler (const gchar *log_domain,
2994 GLogLevelFlags log_level,
2995 const gchar *message,
2996 gpointer unused_data)
2998 const gchar *domains;
2999 GLogField fields[4];
3000 int n_fields = 0;
3002 if ((log_level & DEFAULT_LEVELS) || (log_level >> G_LOG_LEVEL_USER_SHIFT))
3003 goto emit;
3005 domains = g_getenv ("G_MESSAGES_DEBUG");
3006 if (((log_level & INFO_LEVELS) == 0) ||
3007 domains == NULL ||
3008 (strcmp (domains, "all") != 0 && (!log_domain || !strstr (domains, log_domain))))
3009 return;
3011 emit:
3012 /* we can be called externally with recursion for whatever reason */
3013 if (log_level & G_LOG_FLAG_RECURSION)
3015 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3016 return;
3019 fields[0].key = "GLIB_OLD_LOG_API";
3020 fields[0].value = "1";
3021 fields[0].length = -1;
3022 n_fields++;
3024 fields[1].key = "MESSAGE";
3025 fields[1].value = message;
3026 fields[1].length = -1;
3027 n_fields++;
3029 fields[2].key = "PRIORITY";
3030 fields[2].value = log_level_to_priority (log_level);
3031 fields[2].length = -1;
3032 n_fields++;
3034 if (log_domain)
3036 fields[3].key = "GLIB_DOMAIN";
3037 fields[3].value = log_domain;
3038 fields[3].length = -1;
3039 n_fields++;
3042 /* Print out via the structured log API, but drop any fatal flags since we
3043 * have already handled them. The fatal handling in the structured logging
3044 * API is more coarse-grained than in the old g_log() API, so we don't want
3045 * to use it here.
3047 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3051 * g_set_print_handler:
3052 * @func: the new print handler
3054 * Sets the print handler.
3056 * Any messages passed to g_print() will be output via
3057 * the new handler. The default handler simply outputs
3058 * the message to stdout. By providing your own handler
3059 * you can redirect the output, to a GTK+ widget or a
3060 * log file for example.
3062 * Returns: the old print handler
3064 GPrintFunc
3065 g_set_print_handler (GPrintFunc func)
3067 GPrintFunc old_print_func;
3069 g_mutex_lock (&g_messages_lock);
3070 old_print_func = glib_print_func;
3071 glib_print_func = func;
3072 g_mutex_unlock (&g_messages_lock);
3074 return old_print_func;
3078 * g_print:
3079 * @format: the message format. See the printf() documentation
3080 * @...: the parameters to insert into the format string
3082 * Outputs a formatted message via the print handler.
3083 * The default print handler simply outputs the message to stdout, without
3084 * appending a trailing new-line character. Typically, @format should end with
3085 * its own new-line character.
3087 * g_print() should not be used from within libraries for debugging
3088 * messages, since it may be redirected by applications to special
3089 * purpose message windows or even files. Instead, libraries should
3090 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3091 * g_warning() and g_error().
3093 void
3094 g_print (const gchar *format,
3095 ...)
3097 va_list args;
3098 gchar *string;
3099 GPrintFunc local_glib_print_func;
3101 g_return_if_fail (format != NULL);
3103 va_start (args, format);
3104 string = g_strdup_vprintf (format, args);
3105 va_end (args);
3107 g_mutex_lock (&g_messages_lock);
3108 local_glib_print_func = glib_print_func;
3109 g_mutex_unlock (&g_messages_lock);
3111 if (local_glib_print_func)
3112 local_glib_print_func (string);
3113 else
3115 const gchar *charset;
3117 if (g_get_charset (&charset))
3118 fputs (string, stdout); /* charset is UTF-8 already */
3119 else
3121 gchar *lstring = strdup_convert (string, charset);
3123 fputs (lstring, stdout);
3124 g_free (lstring);
3126 fflush (stdout);
3128 g_free (string);
3132 * g_set_printerr_handler:
3133 * @func: the new error message handler
3135 * Sets the handler for printing error messages.
3137 * Any messages passed to g_printerr() will be output via
3138 * the new handler. The default handler simply outputs the
3139 * message to stderr. By providing your own handler you can
3140 * redirect the output, to a GTK+ widget or a log file for
3141 * example.
3143 * Returns: the old error message handler
3145 GPrintFunc
3146 g_set_printerr_handler (GPrintFunc func)
3148 GPrintFunc old_printerr_func;
3150 g_mutex_lock (&g_messages_lock);
3151 old_printerr_func = glib_printerr_func;
3152 glib_printerr_func = func;
3153 g_mutex_unlock (&g_messages_lock);
3155 return old_printerr_func;
3159 * g_printerr:
3160 * @format: the message format. See the printf() documentation
3161 * @...: the parameters to insert into the format string
3163 * Outputs a formatted message via the error message handler.
3164 * The default handler simply outputs the message to stderr, without appending
3165 * a trailing new-line character. Typically, @format should end with its own
3166 * new-line character.
3168 * g_printerr() should not be used from within libraries.
3169 * Instead g_log() or g_log_structured() should be used, or the convenience
3170 * macros g_message(), g_warning() and g_error().
3172 void
3173 g_printerr (const gchar *format,
3174 ...)
3176 va_list args;
3177 gchar *string;
3178 GPrintFunc local_glib_printerr_func;
3180 g_return_if_fail (format != NULL);
3182 va_start (args, format);
3183 string = g_strdup_vprintf (format, args);
3184 va_end (args);
3186 g_mutex_lock (&g_messages_lock);
3187 local_glib_printerr_func = glib_printerr_func;
3188 g_mutex_unlock (&g_messages_lock);
3190 if (local_glib_printerr_func)
3191 local_glib_printerr_func (string);
3192 else
3194 const gchar *charset;
3196 if (g_get_charset (&charset))
3197 fputs (string, stderr); /* charset is UTF-8 already */
3198 else
3200 gchar *lstring = strdup_convert (string, charset);
3202 fputs (lstring, stderr);
3203 g_free (lstring);
3205 fflush (stderr);
3207 g_free (string);
3211 * g_printf_string_upper_bound:
3212 * @format: the format string. See the printf() documentation
3213 * @args: the parameters to be inserted into the format string
3215 * Calculates the maximum space needed to store the output
3216 * of the sprintf() function.
3218 * Returns: the maximum space needed to store the formatted string
3220 gsize
3221 g_printf_string_upper_bound (const gchar *format,
3222 va_list args)
3224 gchar c;
3225 return _g_vsnprintf (&c, 1, format, args) + 1;