docs: Small improvements to glib-mkenums man page
[glib.git] / glib / gmessages.c
blobdfae4df2ba92fc393f9f8564b711da15dc928749
1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
26 * MT safe
29 /**
30 * SECTION:messages
31 * @Title: Message Output and Debugging Functions
32 * @Short_description: functions to output messages and help debug applications
34 * These functions provide support for outputting messages.
36 * The g_return family of macros (g_return_if_fail(),
37 * g_return_val_if_fail(), g_return_if_reached(),
38 * g_return_val_if_reached()) should only be used for programming
39 * errors, a typical use case is checking for invalid parameters at
40 * the beginning of a public function. They should not be used if
41 * you just mean "if (error) return", they should only be used if
42 * you mean "if (bug in program) return". The program behavior is
43 * generally considered undefined after one of these checks fails.
44 * They are not intended for normal control flow, only to give a
45 * perhaps-helpful warning before giving up.
47 * Structured logging output is supported using g_log_structured(). This differs
48 * from the traditional g_log() API in that log messages are handled as a
49 * collection of key–value pairs representing individual pieces of information,
50 * rather than as a single string containing all the information in an arbitrary
51 * format.
53 * The convenience macros g_info(), g_message(), g_debug(), g_warning() and g_error()
54 * will use the traditional g_log() API unless you define the symbol
55 * %G_LOG_USE_STRUCTURED before including `glib.h`. But note that even messages
56 * logged through the traditional g_log() API are ultimatively passed to
57 * g_log_structured(), so that all log messages end up in same destination.
58 * If %G_LOG_USE_STRUCTURED is defined, g_test_expect_message() will become
59 * ineffective for the wrapper macros g_warning() and friends (see
60 * [Testing for Messages][testing-for-messages]).
62 * The support for structured logging was motivated by the following needs (some
63 * of which were supported previously; others weren’t):
64 * * Support for multiple logging levels.
65 * * Structured log support with the ability to add `MESSAGE_ID`s (see
66 * g_log_structured()).
67 * * Moving the responsibility for filtering log messages from the program to
68 * the log viewer — instead of libraries and programs installing log handlers
69 * (with g_log_set_handler()) which filter messages before output, all log
70 * messages are outputted, and the log viewer program (such as `journalctl`)
71 * must filter them. This is based on the idea that bugs are sometimes hard
72 * to reproduce, so it is better to log everything possible and then use
73 * tools to analyse the logs than it is to not be able to reproduce a bug to
74 * get additional log data. Code which uses logging in performance-critical
75 * sections should compile out the g_log_structured() calls in
76 * release builds, and compile them in in debugging builds.
77 * * A single writer function which handles all log messages in a process, from
78 * all libraries and program code; rather than multiple log handlers with
79 * poorly defined interactions between them. This allows a program to easily
80 * change its logging policy by changing the writer function, for example to
81 * log to an additional location or to change what logging output fallbacks
82 * are used. The log writer functions provided by GLib are exposed publicly
83 * so they can be used from programs’ log writers. This allows log writer
84 * policy and implementation to be kept separate.
85 * * If a library wants to add standard information to all of its log messages
86 * (such as library state) or to redact private data (such as passwords or
87 * network credentials), it should use a wrapper function around its
88 * g_log_structured() calls or implement that in the single log writer
89 * function.
90 * * If a program wants to pass context data from a g_log_structured() call to
91 * its log writer function so that, for example, it can use the correct
92 * server connection to submit logs to, that user data can be passed as a
93 * zero-length #GLogField to g_log_structured_array().
94 * * Color output needed to be supported on the terminal, to make reading
95 * through logs easier.
97 * ## Using Structured Logging ## {#using-structured-logging}
99 * To use structured logging (rather than the old-style logging), either use
100 * the g_log_structured() and g_log_structured_array() functions; or define
101 * `G_LOG_USE_STRUCTURED` before including any GLib header, and use the
102 * g_message(), g_debug(), g_error() (etc.) macros.
104 * You do not need to define `G_LOG_USE_STRUCTURED` to use g_log_structured(),
105 * but it is a good idea to avoid confusion.
107 * ## Log Domains ## {#log-domains}
109 * Log domains may be used to broadly split up the origins of log messages.
110 * Typically, there are one or a few log domains per application or library.
111 * %G_LOG_DOMAIN should be used to define the default log domain for the current
112 * compilation unit — it is typically defined at the top of a source file, or in
113 * the preprocessor flags for a group of source files.
115 * Log domains must be unique, and it is recommended that they are the
116 * application or library name, optionally followed by a hyphen and a sub-domain
117 * name. For example, `bloatpad` or `bloatpad-io`.
119 * ## Debug Message Output ## {#debug-message-output}
121 * The default log functions (g_log_default_handler() for the old-style API and
122 * g_log_writer_default() for the structured API) both drop debug and
123 * informational messages by default, unless the log domains of those messages
124 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
125 * `all`).
127 * It is recommended that custom log writer functions re-use the
128 * `G_MESSAGES_DEBUG` environment variable, rather than inventing a custom one,
129 * so that developers can re-use the same debugging techniques and tools across
130 * projects.
132 * ## Testing for Messages ## {#testing-for-messages}
134 * With the old g_log() API, g_test_expect_message() and
135 * g_test_assert_expected_messages() could be used in simple cases to check
136 * whether some code under test had emitted a given log message. These
137 * functions have been deprecated with the structured logging API, for several
138 * reasons:
139 * * They relied on an internal queue which was too inflexible for many use
140 * cases, where messages might be emitted in several orders, some
141 * messages might not be emitted deterministically, or messages might be
142 * emitted by unrelated log domains.
143 * * They do not support structured log fields.
144 * * Examining the log output of code is a bad approach to testing it, and
145 * while it might be necessary for legacy code which uses g_log(), it should
146 * be avoided for new code using g_log_structured().
148 * They will continue to work as before if g_log() is in use (and
149 * %G_LOG_USE_STRUCTURED is not defined). They will do nothing if used with the
150 * structured logging API.
152 * Examining the log output of code is discouraged: libraries should not emit to
153 * `stderr` during defined behaviour, and hence this should not be tested. If
154 * the log emissions of a library during undefined behaviour need to be tested,
155 * they should be limited to asserting that the library aborts and prints a
156 * suitable error message before aborting. This should be done with
157 * g_test_trap_assert_stderr().
159 * If it is really necessary to test the structured log messages emitted by a
160 * particular piece of code – and the code cannot be restructured to be more
161 * suitable to more conventional unit testing – you should write a custom log
162 * writer function (see g_log_set_writer_func()) which appends all log messages
163 * to a queue. When you want to check the log messages, examine and clear the
164 * queue, ignoring irrelevant log messages (for example, from log domains other
165 * than the one under test).
168 #include "config.h"
170 #include <stdlib.h>
171 #include <stdarg.h>
172 #include <stdio.h>
173 #include <string.h>
174 #include <signal.h>
175 #include <locale.h>
176 #include <errno.h>
178 #if defined(__linux__) && !defined(__BIONIC__)
179 #include <sys/types.h>
180 #include <sys/socket.h>
181 #include <sys/un.h>
182 #include <fcntl.h>
183 #include <sys/uio.h>
184 #endif
186 #include "glib-init.h"
187 #include "galloca.h"
188 #include "gbacktrace.h"
189 #include "gcharset.h"
190 #include "gconvert.h"
191 #include "genviron.h"
192 #include "gmain.h"
193 #include "gmem.h"
194 #include "gprintfint.h"
195 #include "gtestutils.h"
196 #include "gthread.h"
197 #include "gstrfuncs.h"
198 #include "gstring.h"
199 #include "gpattern.h"
201 #ifdef G_OS_UNIX
202 #include <unistd.h>
203 #endif
205 #ifdef G_OS_WIN32
206 #include <process.h> /* For getpid() */
207 #include <io.h>
208 # include <windows.h>
210 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
211 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
212 #endif
214 /* XXX: Remove once XP support really dropped */
215 #if _WIN32_WINNT < 0x0600
217 typedef enum _FILE_INFO_BY_HANDLE_CLASS
219 FileBasicInfo = 0,
220 FileStandardInfo = 1,
221 FileNameInfo = 2,
222 FileRenameInfo = 3,
223 FileDispositionInfo = 4,
224 FileAllocationInfo = 5,
225 FileEndOfFileInfo = 6,
226 FileStreamInfo = 7,
227 FileCompressionInfo = 8,
228 FileAttributeTagInfo = 9,
229 FileIdBothDirectoryInfo = 10,
230 FileIdBothDirectoryRestartInfo = 11,
231 FileIoPriorityHintInfo = 12,
232 FileRemoteProtocolInfo = 13,
233 FileFullDirectoryInfo = 14,
234 FileFullDirectoryRestartInfo = 15,
235 FileStorageInfo = 16,
236 FileAlignmentInfo = 17,
237 FileIdInfo = 18,
238 FileIdExtdDirectoryInfo = 19,
239 FileIdExtdDirectoryRestartInfo = 20,
240 MaximumFileInfoByHandlesClass
241 } FILE_INFO_BY_HANDLE_CLASS;
243 typedef struct _FILE_NAME_INFO
245 DWORD FileNameLength;
246 WCHAR FileName[1];
247 } FILE_NAME_INFO;
249 typedef BOOL (WINAPI fGetFileInformationByHandleEx) (HANDLE,
250 FILE_INFO_BY_HANDLE_CLASS,
251 LPVOID,
252 DWORD);
253 #endif
255 #if defined (_MSC_VER) && (_MSC_VER >=1400)
256 /* This is ugly, but we need it for isatty() in case we have bad fd's,
257 * otherwise Windows will abort() the program on msvcrt80.dll and later
259 #include <crtdbg.h>
261 _GLIB_EXTERN void
262 myInvalidParameterHandler(const wchar_t *expression,
263 const wchar_t *function,
264 const wchar_t *file,
265 unsigned int line,
266 uintptr_t pReserved)
269 #endif
271 #include "gwin32.h"
272 #endif
275 * G_LOG_DOMAIN:
277 * Defines the log domain. See [Log Domains](#log-domains).
279 * Libraries should define this so that any messages
280 * which they log can be differentiated from messages from other
281 * libraries and application code. But be careful not to define
282 * it in any public header files.
284 * Log domains must be unique, and it is recommended that they are the
285 * application or library name, optionally followed by a hyphen and a sub-domain
286 * name. For example, `bloatpad` or `bloatpad-io`.
288 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
289 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
290 * environment variable.
292 * For example, GTK+ uses this in its `Makefile.am`:
293 * |[
294 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
295 * ]|
297 * Applications can choose to leave it as the default %NULL (or `""`)
298 * domain. However, defining the domain offers the same advantages as
299 * above.
305 * G_LOG_FATAL_MASK:
307 * GLib log levels that are considered fatal by default.
309 * This is not used if structured logging is enabled; see
310 * [Using Structured Logging][using-structured-logging].
314 * GLogFunc:
315 * @log_domain: the log domain of the message
316 * @log_level: the log level of the message (including the
317 * fatal and recursion flags)
318 * @message: the message to process
319 * @user_data: user data, set in g_log_set_handler()
321 * Specifies the prototype of log handler functions.
323 * The default log handler, g_log_default_handler(), automatically appends a
324 * new-line character to @message when printing it. It is advised that any
325 * custom log handler functions behave similarly, so that logging calls in user
326 * code do not need modifying to add a new-line character to the message if the
327 * log handler is changed.
329 * This is not used if structured logging is enabled; see
330 * [Using Structured Logging][using-structured-logging].
334 * GLogLevelFlags:
335 * @G_LOG_FLAG_RECURSION: internal flag
336 * @G_LOG_FLAG_FATAL: internal flag
337 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
338 * This level is also used for messages produced by g_assert().
339 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
340 * g_critical().
341 * This level is also used for messages produced by g_return_if_fail()
342 * and g_return_val_if_fail().
343 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
344 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
345 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
346 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
347 * @G_LOG_LEVEL_MASK: a mask including all log levels
349 * Flags specifying the level of log messages.
351 * It is possible to change how GLib treats messages of the various
352 * levels using g_log_set_handler() and g_log_set_fatal_mask().
356 * G_LOG_LEVEL_USER_SHIFT:
358 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
359 * Higher bits can be used for user-defined log levels.
363 * g_message:
364 * @...: format string, followed by parameters to insert
365 * into the format string (as with printf())
367 * A convenience function/macro to log a normal message.
369 * If g_log_default_handler() is used as the log handler function, a new-line
370 * character will automatically be appended to @..., and need not be entered
371 * manually.
373 * If structured logging is enabled, this will use g_log_structured();
374 * otherwise it will use g_log(). See
375 * [Using Structured Logging][using-structured-logging].
379 * g_warning:
380 * @...: format string, followed by parameters to insert
381 * into the format string (as with printf())
383 * A convenience function/macro to log a warning message. The message should
384 * typically *not* be translated to the user's language.
386 * This is not intended for end user error reporting. Use of #GError is
387 * preferred for that instead, as it allows calling functions to perform actions
388 * conditional on the type of error.
390 * You can make warnings fatal at runtime by setting the `G_DEBUG`
391 * environment variable (see
392 * [Running GLib Applications](glib-running.html)):
394 * |[
395 * G_DEBUG=fatal-warnings gdb ./my-program
396 * ]|
398 * Any unrelated failures can be skipped over in
399 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
401 * If g_log_default_handler() is used as the log handler function,
402 * a newline character will automatically be appended to @..., and
403 * need not be entered manually.
405 * If structured logging is enabled, this will use g_log_structured();
406 * otherwise it will use g_log(). See
407 * [Using Structured Logging][using-structured-logging].
411 * g_critical:
412 * @...: format string, followed by parameters to insert
413 * into the format string (as with printf())
415 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
416 * It's more or less application-defined what constitutes
417 * a critical vs. a regular warning. You could call
418 * g_log_set_always_fatal() to make critical warnings exit
419 * the program, then use g_critical() for fatal errors, for
420 * example.
422 * You can also make critical warnings fatal at runtime by
423 * setting the `G_DEBUG` environment variable (see
424 * [Running GLib Applications](glib-running.html)):
426 * |[
427 * G_DEBUG=fatal-warnings gdb ./my-program
428 * ]|
430 * Any unrelated failures can be skipped over in
431 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
433 * The message should typically *not* be translated to the
434 * user's language.
436 * If g_log_default_handler() is used as the log handler function, a new-line
437 * character will automatically be appended to @..., and need not be entered
438 * manually.
440 * If structured logging is enabled, this will use g_log_structured();
441 * otherwise it will use g_log(). See
442 * [Using Structured Logging][using-structured-logging].
446 * g_error:
447 * @...: format string, followed by parameters to insert
448 * into the format string (as with printf())
450 * A convenience function/macro to log an error message. The message should
451 * typically *not* be translated to the user's language.
453 * This is not intended for end user error reporting. Use of #GError is
454 * preferred for that instead, as it allows calling functions to perform actions
455 * conditional on the type of error.
457 * Error messages are always fatal, resulting in a call to
458 * abort() to terminate the application. This function will
459 * result in a core dump; don't use it for errors you expect.
460 * Using this function indicates a bug in your program, i.e.
461 * an assertion failure.
463 * If g_log_default_handler() is used as the log handler function, a new-line
464 * character will automatically be appended to @..., and need not be entered
465 * manually.
467 * If structured logging is enabled, this will use g_log_structured();
468 * otherwise it will use g_log(). See
469 * [Using Structured Logging][using-structured-logging].
473 * g_info:
474 * @...: format string, followed by parameters to insert
475 * into the format string (as with printf())
477 * A convenience function/macro to log an informational message. Seldom used.
479 * If g_log_default_handler() is used as the log handler function, a new-line
480 * character will automatically be appended to @..., and need not be entered
481 * manually.
483 * Such messages are suppressed by the g_log_default_handler() and
484 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
485 * set appropriately.
487 * If structured logging is enabled, this will use g_log_structured();
488 * otherwise it will use g_log(). See
489 * [Using Structured Logging][using-structured-logging].
491 * Since: 2.40
495 * g_debug:
496 * @...: format string, followed by parameters to insert
497 * into the format string (as with printf())
499 * A convenience function/macro to log a debug message. The message should
500 * typically *not* be translated to the user's language.
502 * If g_log_default_handler() is used as the log handler function, a new-line
503 * character will automatically be appended to @..., and need not be entered
504 * manually.
506 * Such messages are suppressed by the g_log_default_handler() and
507 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
508 * set appropriately.
510 * If structured logging is enabled, this will use g_log_structured();
511 * otherwise it will use g_log(). See
512 * [Using Structured Logging][using-structured-logging].
514 * Since: 2.6
517 /* --- structures --- */
518 typedef struct _GLogDomain GLogDomain;
519 typedef struct _GLogHandler GLogHandler;
520 struct _GLogDomain
522 gchar *log_domain;
523 GLogLevelFlags fatal_mask;
524 GLogHandler *handlers;
525 GLogDomain *next;
527 struct _GLogHandler
529 guint id;
530 GLogLevelFlags log_level;
531 GLogFunc log_func;
532 gpointer data;
533 GDestroyNotify destroy;
534 GLogHandler *next;
538 /* --- variables --- */
539 static GMutex g_messages_lock;
540 static GLogDomain *g_log_domains = NULL;
541 static GPrintFunc glib_print_func = NULL;
542 static GPrintFunc glib_printerr_func = NULL;
543 static GPrivate g_log_depth;
544 static GPrivate g_log_structured_depth;
545 static GLogFunc default_log_func = g_log_default_handler;
546 static gpointer default_log_data = NULL;
547 static GTestLogFatalFunc fatal_log_func = NULL;
548 static gpointer fatal_log_data;
549 static GLogWriterFunc log_writer_func = g_log_writer_default;
550 static gpointer log_writer_user_data = NULL;
551 static GDestroyNotify log_writer_user_data_free = NULL;
553 /* --- functions --- */
555 static void _g_log_abort (gboolean breakpoint);
557 static void
558 _g_log_abort (gboolean breakpoint)
560 gboolean debugger_present;
562 if (g_test_subprocess ())
564 /* If this is a test case subprocess then it probably caused
565 * this error message on purpose, so just exit() rather than
566 * abort()ing, to avoid triggering any system crash-reporting
567 * daemon.
569 _exit (1);
572 #ifdef G_OS_WIN32
573 debugger_present = IsDebuggerPresent ();
574 #else
575 /* Assume GDB is attached. */
576 debugger_present = TRUE;
577 #endif /* !G_OS_WIN32 */
579 if (debugger_present && breakpoint)
580 G_BREAKPOINT ();
581 else
582 g_abort ();
585 #ifdef G_OS_WIN32
586 static gboolean win32_keep_fatal_message = FALSE;
588 /* This default message will usually be overwritten. */
589 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
590 * called with huge strings, is it?
592 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
593 static gchar *fatal_msg_ptr = fatal_msg_buf;
595 #undef write
596 static inline int
597 dowrite (int fd,
598 const void *buf,
599 unsigned int len)
601 if (win32_keep_fatal_message)
603 memcpy (fatal_msg_ptr, buf, len);
604 fatal_msg_ptr += len;
605 *fatal_msg_ptr = 0;
606 return len;
609 write (fd, buf, len);
611 return len;
613 #define write(fd, buf, len) dowrite(fd, buf, len)
615 #endif
617 static void
618 write_string (FILE *stream,
619 const gchar *string)
621 fputs (string, stream);
624 static void
625 write_string_sized (FILE *stream,
626 const gchar *string,
627 gssize length)
629 /* Is it nul-terminated? */
630 if (length < 0)
631 write_string (stream, string);
632 else
633 fwrite (string, 1, length, stream);
636 static GLogDomain*
637 g_log_find_domain_L (const gchar *log_domain)
639 GLogDomain *domain;
641 domain = g_log_domains;
642 while (domain)
644 if (strcmp (domain->log_domain, log_domain) == 0)
645 return domain;
646 domain = domain->next;
648 return NULL;
651 static GLogDomain*
652 g_log_domain_new_L (const gchar *log_domain)
654 GLogDomain *domain;
656 domain = g_new (GLogDomain, 1);
657 domain->log_domain = g_strdup (log_domain);
658 domain->fatal_mask = G_LOG_FATAL_MASK;
659 domain->handlers = NULL;
661 domain->next = g_log_domains;
662 g_log_domains = domain;
664 return domain;
667 static void
668 g_log_domain_check_free_L (GLogDomain *domain)
670 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
671 domain->handlers == NULL)
673 GLogDomain *last, *work;
675 last = NULL;
677 work = g_log_domains;
678 while (work)
680 if (work == domain)
682 if (last)
683 last->next = domain->next;
684 else
685 g_log_domains = domain->next;
686 g_free (domain->log_domain);
687 g_free (domain);
688 break;
690 last = work;
691 work = last->next;
696 static GLogFunc
697 g_log_domain_get_handler_L (GLogDomain *domain,
698 GLogLevelFlags log_level,
699 gpointer *data)
701 if (domain && log_level)
703 GLogHandler *handler;
705 handler = domain->handlers;
706 while (handler)
708 if ((handler->log_level & log_level) == log_level)
710 *data = handler->data;
711 return handler->log_func;
713 handler = handler->next;
717 *data = default_log_data;
718 return default_log_func;
722 * g_log_set_always_fatal:
723 * @fatal_mask: the mask containing bits set for each level
724 * of error which is to be fatal
726 * Sets the message levels which are always fatal, in any log domain.
727 * When a message with any of these levels is logged the program terminates.
728 * You can only set the levels defined by GLib to be fatal.
729 * %G_LOG_LEVEL_ERROR is always fatal.
731 * You can also make some message levels fatal at runtime by setting
732 * the `G_DEBUG` environment variable (see
733 * [Running GLib Applications](glib-running.html)).
735 * Libraries should not call this function, as it affects all messages logged
736 * by a process, including those from other libraries.
738 * Structured log messages (using g_log_structured() and
739 * g_log_structured_array()) are fatal only if the default log writer is used;
740 * otherwise it is up to the writer function to determine which log messages
741 * are fatal. See [Using Structured Logging][using-structured-logging].
743 * Returns: the old fatal mask
745 GLogLevelFlags
746 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
748 GLogLevelFlags old_mask;
750 /* restrict the global mask to levels that are known to glib
751 * since this setting applies to all domains
753 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
754 /* force errors to be fatal */
755 fatal_mask |= G_LOG_LEVEL_ERROR;
756 /* remove bogus flag */
757 fatal_mask &= ~G_LOG_FLAG_FATAL;
759 g_mutex_lock (&g_messages_lock);
760 old_mask = g_log_always_fatal;
761 g_log_always_fatal = fatal_mask;
762 g_mutex_unlock (&g_messages_lock);
764 return old_mask;
768 * g_log_set_fatal_mask:
769 * @log_domain: the log domain
770 * @fatal_mask: the new fatal mask
772 * Sets the log levels which are fatal in the given domain.
773 * %G_LOG_LEVEL_ERROR is always fatal.
775 * This has no effect on structured log messages (using g_log_structured() or
776 * g_log_structured_array()). To change the fatal behaviour for specific log
777 * messages, programs must install a custom log writer function using
778 * g_log_set_writer_func(). See
779 * [Using Structured Logging][using-structured-logging].
781 * Returns: the old fatal mask for the log domain
783 GLogLevelFlags
784 g_log_set_fatal_mask (const gchar *log_domain,
785 GLogLevelFlags fatal_mask)
787 GLogLevelFlags old_flags;
788 GLogDomain *domain;
790 if (!log_domain)
791 log_domain = "";
793 /* force errors to be fatal */
794 fatal_mask |= G_LOG_LEVEL_ERROR;
795 /* remove bogus flag */
796 fatal_mask &= ~G_LOG_FLAG_FATAL;
798 g_mutex_lock (&g_messages_lock);
800 domain = g_log_find_domain_L (log_domain);
801 if (!domain)
802 domain = g_log_domain_new_L (log_domain);
803 old_flags = domain->fatal_mask;
805 domain->fatal_mask = fatal_mask;
806 g_log_domain_check_free_L (domain);
808 g_mutex_unlock (&g_messages_lock);
810 return old_flags;
814 * g_log_set_handler:
815 * @log_domain: (nullable): the log domain, or %NULL for the default ""
816 * application domain
817 * @log_levels: the log levels to apply the log handler for.
818 * To handle fatal and recursive messages as well, combine
819 * the log levels with the #G_LOG_FLAG_FATAL and
820 * #G_LOG_FLAG_RECURSION bit flags.
821 * @log_func: the log handler function
822 * @user_data: data passed to the log handler
824 * Sets the log handler for a domain and a set of log levels.
825 * To handle fatal and recursive messages the @log_levels parameter
826 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
827 * bit flags.
829 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
830 * you want to set a handler for this log level you must combine it with
831 * #G_LOG_FLAG_FATAL.
833 * This has no effect if structured logging is enabled; see
834 * [Using Structured Logging][using-structured-logging].
836 * Here is an example for adding a log handler for all warning messages
837 * in the default domain:
838 * |[<!-- language="C" -->
839 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
840 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
841 * ]|
843 * This example adds a log handler for all critical messages from GTK+:
844 * |[<!-- language="C" -->
845 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
846 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
847 * ]|
849 * This example adds a log handler for all messages from GLib:
850 * |[<!-- language="C" -->
851 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
852 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
853 * ]|
855 * Returns: the id of the new handler
857 guint
858 g_log_set_handler (const gchar *log_domain,
859 GLogLevelFlags log_levels,
860 GLogFunc log_func,
861 gpointer user_data)
863 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
867 * g_log_set_handler_full: (rename-to g_log_set_handler)
868 * @log_domain: (nullable): the log domain, or %NULL for the default ""
869 * application domain
870 * @log_levels: the log levels to apply the log handler for.
871 * To handle fatal and recursive messages as well, combine
872 * the log levels with the #G_LOG_FLAG_FATAL and
873 * #G_LOG_FLAG_RECURSION bit flags.
874 * @log_func: the log handler function
875 * @user_data: data passed to the log handler
876 * @destroy: destroy notify for @user_data, or %NULL
878 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
880 * This has no effect if structured logging is enabled; see
881 * [Using Structured Logging][using-structured-logging].
883 * Returns: the id of the new handler
885 * Since: 2.46
887 guint
888 g_log_set_handler_full (const gchar *log_domain,
889 GLogLevelFlags log_levels,
890 GLogFunc log_func,
891 gpointer user_data,
892 GDestroyNotify destroy)
894 static guint handler_id = 0;
895 GLogDomain *domain;
896 GLogHandler *handler;
898 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
899 g_return_val_if_fail (log_func != NULL, 0);
901 if (!log_domain)
902 log_domain = "";
904 handler = g_new (GLogHandler, 1);
906 g_mutex_lock (&g_messages_lock);
908 domain = g_log_find_domain_L (log_domain);
909 if (!domain)
910 domain = g_log_domain_new_L (log_domain);
912 handler->id = ++handler_id;
913 handler->log_level = log_levels;
914 handler->log_func = log_func;
915 handler->data = user_data;
916 handler->destroy = destroy;
917 handler->next = domain->handlers;
918 domain->handlers = handler;
920 g_mutex_unlock (&g_messages_lock);
922 return handler_id;
926 * g_log_set_default_handler:
927 * @log_func: the log handler function
928 * @user_data: data passed to the log handler
930 * Installs a default log handler which is used if no
931 * log handler has been set for the particular log domain
932 * and log level combination. By default, GLib uses
933 * g_log_default_handler() as default log handler.
935 * This has no effect if structured logging is enabled; see
936 * [Using Structured Logging][using-structured-logging].
938 * Returns: the previous default log handler
940 * Since: 2.6
942 GLogFunc
943 g_log_set_default_handler (GLogFunc log_func,
944 gpointer user_data)
946 GLogFunc old_log_func;
948 g_mutex_lock (&g_messages_lock);
949 old_log_func = default_log_func;
950 default_log_func = log_func;
951 default_log_data = user_data;
952 g_mutex_unlock (&g_messages_lock);
954 return old_log_func;
958 * g_test_log_set_fatal_handler:
959 * @log_func: the log handler function.
960 * @user_data: data passed to the log handler.
962 * Installs a non-error fatal log handler which can be
963 * used to decide whether log messages which are counted
964 * as fatal abort the program.
966 * The use case here is that you are running a test case
967 * that depends on particular libraries or circumstances
968 * and cannot prevent certain known critical or warning
969 * messages. So you install a handler that compares the
970 * domain and message to precisely not abort in such a case.
972 * Note that the handler is reset at the beginning of
973 * any test case, so you have to set it inside each test
974 * function which needs the special behavior.
976 * This handler has no effect on g_error messages.
978 * This handler also has no effect on structured log messages (using
979 * g_log_structured() or g_log_structured_array()). To change the fatal
980 * behaviour for specific log messages, programs must install a custom log
981 * writer function using g_log_set_writer_func().See
982 * [Using Structured Logging][using-structured-logging].
984 * Since: 2.22
986 void
987 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
988 gpointer user_data)
990 g_mutex_lock (&g_messages_lock);
991 fatal_log_func = log_func;
992 fatal_log_data = user_data;
993 g_mutex_unlock (&g_messages_lock);
997 * g_log_remove_handler:
998 * @log_domain: the log domain
999 * @handler_id: the id of the handler, which was returned
1000 * in g_log_set_handler()
1002 * Removes the log handler.
1004 * This has no effect if structured logging is enabled; see
1005 * [Using Structured Logging][using-structured-logging].
1007 void
1008 g_log_remove_handler (const gchar *log_domain,
1009 guint handler_id)
1011 GLogDomain *domain;
1013 g_return_if_fail (handler_id > 0);
1015 if (!log_domain)
1016 log_domain = "";
1018 g_mutex_lock (&g_messages_lock);
1019 domain = g_log_find_domain_L (log_domain);
1020 if (domain)
1022 GLogHandler *work, *last;
1024 last = NULL;
1025 work = domain->handlers;
1026 while (work)
1028 if (work->id == handler_id)
1030 if (last)
1031 last->next = work->next;
1032 else
1033 domain->handlers = work->next;
1034 g_log_domain_check_free_L (domain);
1035 g_mutex_unlock (&g_messages_lock);
1036 if (work->destroy)
1037 work->destroy (work->data);
1038 g_free (work);
1039 return;
1041 last = work;
1042 work = last->next;
1045 g_mutex_unlock (&g_messages_lock);
1046 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1047 G_STRLOC, handler_id, log_domain);
1050 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1051 (wc == 0x7f) || \
1052 (wc >= 0x80 && wc < 0xa0)))
1054 static gchar*
1055 strdup_convert (const gchar *string,
1056 const gchar *charset)
1058 if (!g_utf8_validate (string, -1, NULL))
1060 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1061 guchar *p;
1063 for (p = (guchar *)string; *p; p++)
1065 if (CHAR_IS_SAFE(*p) &&
1066 !(*p == '\r' && *(p + 1) != '\n') &&
1067 *p < 0x80)
1068 g_string_append_c (gstring, *p);
1069 else
1070 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1073 return g_string_free (gstring, FALSE);
1075 else
1077 GError *err = NULL;
1079 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1080 if (result)
1081 return result;
1082 else
1084 /* Not thread-safe, but doesn't matter if we print the warning twice
1086 static gboolean warned = FALSE;
1087 if (!warned)
1089 warned = TRUE;
1090 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1092 g_error_free (err);
1094 return g_strdup (string);
1099 /* For a radix of 8 we need at most 3 output bytes for 1 input
1100 * byte. Additionally we might need up to 2 output bytes for the
1101 * readix prefix and 1 byte for the trailing NULL.
1103 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1105 static void
1106 format_unsigned (gchar *buf,
1107 gulong num,
1108 guint radix)
1110 gulong tmp;
1111 gchar c;
1112 gint i, n;
1114 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1116 if (radix != 8 && radix != 10 && radix != 16)
1118 *buf = '\000';
1119 return;
1122 if (!num)
1124 *buf++ = '0';
1125 *buf = '\000';
1126 return;
1129 if (radix == 16)
1131 *buf++ = '0';
1132 *buf++ = 'x';
1134 else if (radix == 8)
1136 *buf++ = '0';
1139 n = 0;
1140 tmp = num;
1141 while (tmp)
1143 tmp /= radix;
1144 n++;
1147 i = n;
1149 /* Again we can't use g_assert; actually this check should _never_ fail. */
1150 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1152 *buf = '\000';
1153 return;
1156 while (num)
1158 i--;
1159 c = (num % radix);
1160 if (c < 10)
1161 buf[i] = c + '0';
1162 else
1163 buf[i] = c + 'a' - 10;
1164 num /= radix;
1167 buf[n] = '\000';
1170 /* string size big enough to hold level prefix */
1171 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1173 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1175 /* these are emitted by the default log handler */
1176 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1177 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1178 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1180 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1181 gboolean use_color);
1182 static const gchar *color_reset (gboolean use_color);
1184 static FILE *
1185 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1186 GLogLevelFlags log_level,
1187 gboolean use_color)
1189 gboolean to_stdout = TRUE;
1191 /* we may not call _any_ GLib functions here */
1193 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1195 switch (log_level & G_LOG_LEVEL_MASK)
1197 case G_LOG_LEVEL_ERROR:
1198 strcat (level_prefix, "ERROR");
1199 to_stdout = FALSE;
1200 break;
1201 case G_LOG_LEVEL_CRITICAL:
1202 strcat (level_prefix, "CRITICAL");
1203 to_stdout = FALSE;
1204 break;
1205 case G_LOG_LEVEL_WARNING:
1206 strcat (level_prefix, "WARNING");
1207 to_stdout = FALSE;
1208 break;
1209 case G_LOG_LEVEL_MESSAGE:
1210 strcat (level_prefix, "Message");
1211 to_stdout = FALSE;
1212 break;
1213 case G_LOG_LEVEL_INFO:
1214 strcat (level_prefix, "INFO");
1215 break;
1216 case G_LOG_LEVEL_DEBUG:
1217 strcat (level_prefix, "DEBUG");
1218 break;
1219 default:
1220 if (log_level)
1222 strcat (level_prefix, "LOG-");
1223 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1225 else
1226 strcat (level_prefix, "LOG");
1227 break;
1230 strcat (level_prefix, color_reset (use_color));
1232 if (log_level & G_LOG_FLAG_RECURSION)
1233 strcat (level_prefix, " (recursed)");
1234 if (log_level & ALERT_LEVELS)
1235 strcat (level_prefix, " **");
1237 #ifdef G_OS_WIN32
1238 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1239 win32_keep_fatal_message = TRUE;
1240 #endif
1241 return to_stdout ? stdout : stderr;
1244 typedef struct {
1245 gchar *log_domain;
1246 GLogLevelFlags log_level;
1247 gchar *pattern;
1248 } GTestExpectedMessage;
1250 static GSList *expected_messages = NULL;
1253 * g_logv:
1254 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1255 * application domain
1256 * @log_level: the log level
1257 * @format: the message format. See the printf() documentation
1258 * @args: the parameters to insert into the format string
1260 * Logs an error or debugging message.
1262 * If the log level has been set as fatal, the abort()
1263 * function is called to terminate the program.
1265 * If g_log_default_handler() is used as the log handler function, a new-line
1266 * character will automatically be appended to @..., and need not be entered
1267 * manually.
1269 * If [structured logging is enabled][using-structured-logging] this will
1270 * output via the structured log writer function (see g_log_set_writer_func()).
1272 void
1273 g_logv (const gchar *log_domain,
1274 GLogLevelFlags log_level,
1275 const gchar *format,
1276 va_list args)
1278 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1279 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1280 gchar buffer[1025], *msg, *msg_alloc = NULL;
1281 gint i;
1283 log_level &= G_LOG_LEVEL_MASK;
1284 if (!log_level)
1285 return;
1287 if (log_level & G_LOG_FLAG_RECURSION)
1289 /* we use a stack buffer of fixed size, since we're likely
1290 * in an out-of-memory situation
1292 gsize size G_GNUC_UNUSED;
1294 size = _g_vsnprintf (buffer, 1024, format, args);
1295 msg = buffer;
1297 else
1298 msg = msg_alloc = g_strdup_vprintf (format, args);
1300 if (expected_messages)
1302 GTestExpectedMessage *expected = expected_messages->data;
1304 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1305 ((log_level & expected->log_level) == expected->log_level) &&
1306 g_pattern_match_simple (expected->pattern, msg))
1308 expected_messages = g_slist_delete_link (expected_messages,
1309 expected_messages);
1310 g_free (expected->log_domain);
1311 g_free (expected->pattern);
1312 g_free (expected);
1313 g_free (msg_alloc);
1314 return;
1316 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1318 gchar level_prefix[STRING_BUFFER_SIZE];
1319 gchar *expected_message;
1321 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1322 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1323 expected->log_domain ? expected->log_domain : "**",
1324 level_prefix, expected->pattern);
1325 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1326 g_free (expected_message);
1328 log_level |= G_LOG_FLAG_FATAL;
1332 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1334 GLogLevelFlags test_level;
1336 test_level = 1 << i;
1337 if (log_level & test_level)
1339 GLogDomain *domain;
1340 GLogFunc log_func;
1341 GLogLevelFlags domain_fatal_mask;
1342 gpointer data = NULL;
1343 gboolean masquerade_fatal = FALSE;
1344 guint depth;
1346 if (was_fatal)
1347 test_level |= G_LOG_FLAG_FATAL;
1348 if (was_recursion)
1349 test_level |= G_LOG_FLAG_RECURSION;
1351 /* check recursion and lookup handler */
1352 g_mutex_lock (&g_messages_lock);
1353 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1354 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1355 if (depth)
1356 test_level |= G_LOG_FLAG_RECURSION;
1357 depth++;
1358 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1359 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1360 test_level |= G_LOG_FLAG_FATAL;
1361 if (test_level & G_LOG_FLAG_RECURSION)
1362 log_func = _g_log_fallback_handler;
1363 else
1364 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1365 domain = NULL;
1366 g_mutex_unlock (&g_messages_lock);
1368 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1370 log_func (log_domain, test_level, msg, data);
1372 if ((test_level & G_LOG_FLAG_FATAL)
1373 && !(test_level & G_LOG_LEVEL_ERROR))
1375 masquerade_fatal = fatal_log_func
1376 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1379 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1381 #ifdef G_OS_WIN32
1382 if (win32_keep_fatal_message)
1384 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1386 MessageBox (NULL, locale_msg, NULL,
1387 MB_ICONERROR|MB_SETFOREGROUND);
1389 #endif /* !G_OS_WIN32 */
1391 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1394 depth--;
1395 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1399 g_free (msg_alloc);
1403 * g_log:
1404 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1405 * for the default
1406 * @log_level: the log level, either from #GLogLevelFlags
1407 * or a user-defined level
1408 * @format: the message format. See the printf() documentation
1409 * @...: the parameters to insert into the format string
1411 * Logs an error or debugging message.
1413 * If the log level has been set as fatal, the abort()
1414 * function is called to terminate the program.
1416 * If g_log_default_handler() is used as the log handler function, a new-line
1417 * character will automatically be appended to @..., and need not be entered
1418 * manually.
1420 * If [structured logging is enabled][using-structured-logging] this will
1421 * output via the structured log writer function (see g_log_set_writer_func()).
1423 void
1424 g_log (const gchar *log_domain,
1425 GLogLevelFlags log_level,
1426 const gchar *format,
1427 ...)
1429 va_list args;
1431 va_start (args, format);
1432 g_logv (log_domain, log_level, format, args);
1433 va_end (args);
1436 /* Return value must be 1 byte long (plus nul byte).
1437 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1439 static const gchar *
1440 log_level_to_priority (GLogLevelFlags log_level)
1442 if (log_level & G_LOG_LEVEL_ERROR)
1443 return "3";
1444 else if (log_level & G_LOG_LEVEL_CRITICAL)
1445 return "4";
1446 else if (log_level & G_LOG_LEVEL_WARNING)
1447 return "4";
1448 else if (log_level & G_LOG_LEVEL_MESSAGE)
1449 return "5";
1450 else if (log_level & G_LOG_LEVEL_INFO)
1451 return "6";
1452 else if (log_level & G_LOG_LEVEL_DEBUG)
1453 return "7";
1455 /* Default to LOG_NOTICE for custom log levels. */
1456 return "5";
1459 static FILE *
1460 log_level_to_file (GLogLevelFlags log_level)
1462 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1463 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1464 return stderr;
1465 else
1466 return stdout;
1469 static const gchar *
1470 log_level_to_color (GLogLevelFlags log_level,
1471 gboolean use_color)
1473 /* we may not call _any_ GLib functions here */
1475 if (!use_color)
1476 return "";
1478 if (log_level & G_LOG_LEVEL_ERROR)
1479 return "\033[1;31m";
1480 else if (log_level & G_LOG_LEVEL_CRITICAL)
1481 return "\033[1;35m";
1482 else if (log_level & G_LOG_LEVEL_WARNING)
1483 return "\033[1;33m";
1484 else if (log_level & G_LOG_LEVEL_MESSAGE)
1485 return "\033[1;32m";
1486 else if (log_level & G_LOG_LEVEL_INFO)
1487 return "\033[1;32m";
1488 else if (log_level & G_LOG_LEVEL_DEBUG)
1489 return "\033[1;32m";
1491 /* No color for custom log levels. */
1492 return "";
1495 static const gchar *
1496 color_reset (gboolean use_color)
1498 /* we may not call _any_ GLib functions here */
1500 if (!use_color)
1501 return "";
1503 return "\033[0m";
1506 #ifdef G_OS_WIN32
1508 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1509 * so we need to check the name of the pipe if _isatty (fd) == 0
1512 static gboolean
1513 win32_is_pipe_tty (int fd)
1515 gboolean result = FALSE;
1516 int error;
1517 HANDLE h_fd;
1518 FILE_NAME_INFO *info = NULL;
1519 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1520 wchar_t *name = NULL;
1521 gint length;
1523 /* XXX: Remove once XP support really dropped */
1524 #if _WIN32_WINNT < 0x0600
1525 HANDLE h_kerneldll = NULL;
1526 fGetFileInformationByHandleEx *GetFileInformationByHandleEx;
1527 #endif
1529 h_fd = (HANDLE) _get_osfhandle (fd);
1531 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1532 goto done_query;
1534 /* The following check is available on Vista or later, so on XP, no color support */
1535 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1537 /* XXX: Remove once XP support really dropped */
1538 #if _WIN32_WINNT < 0x0600
1539 h_kerneldll = LoadLibraryW (L"kernel32.dll");
1541 if (h_kerneldll == NULL)
1542 goto done_query;
1544 GetFileInformationByHandleEx =
1545 (fGetFileInformationByHandleEx *) GetProcAddress (h_kerneldll, "GetFileInformationByHandleEx");
1547 if (GetFileInformationByHandleEx == NULL)
1548 goto done_query;
1549 #endif
1551 info = g_try_malloc (info_size);
1553 if (info == NULL ||
1554 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1555 goto done_query;
1557 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1558 name = info->FileName;
1560 length = wcslen (L"\\cygwin-");
1561 if (wcsncmp (name, L"\\cygwin-", length))
1563 length = wcslen (L"\\msys-");
1564 if (wcsncmp (name, L"\\msys-", length))
1565 goto done_query;
1568 name += length;
1569 length = wcsspn (name, L"0123456789abcdefABCDEF");
1570 if (length != 16)
1571 goto done_query;
1573 name += length;
1574 length = wcslen (L"-pty");
1575 if (wcsncmp (name, L"-pty", length))
1576 goto done_query;
1578 name += length;
1579 length = wcsspn (name, L"0123456789");
1580 if (length != 1)
1581 goto done_query;
1583 name += length;
1584 length = wcslen (L"-to-master");
1585 if (wcsncmp (name, L"-to-master", length))
1587 length = wcslen (L"-from-master");
1588 if (wcsncmp (name, L"-from-master", length))
1589 goto done_query;
1592 result = TRUE;
1594 done_query:
1595 if (info != NULL)
1596 g_free (info);
1598 /* XXX: Remove once XP support really dropped */
1599 #if _WIN32_WINNT < 0x0600
1600 if (h_kerneldll != NULL)
1601 FreeLibrary (h_kerneldll);
1602 #endif
1604 return result;
1606 #endif
1608 #pragma GCC diagnostic push
1609 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1612 * g_log_structured:
1613 * @log_domain: log domain, usually %G_LOG_DOMAIN
1614 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1615 * level
1616 * @...: key-value pairs of structured data to add to the log entry, followed
1617 * by the key "MESSAGE", followed by a printf()-style message format,
1618 * followed by parameters to insert in the format string
1620 * Log a message with structured data. The message will be passed through to
1621 * the log writer set by the application using g_log_set_writer_func(). If the
1622 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1623 * be aborted at the end of this function. If the log writer returns
1624 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1625 * See the documentation for #GLogWriterFunc for information on chaining
1626 * writers.
1628 * The structured data is provided as key–value pairs, where keys are UTF-8
1629 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1630 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1631 * structured data, use g_log_structured_array(). The keys for structured data
1632 * should follow the [systemd journal
1633 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1634 * specification. It is suggested that custom keys are namespaced according to
1635 * the code which sets them. For example, custom keys from GLib all have a
1636 * `GLIB_` prefix.
1638 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1639 * be converted into a
1640 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1641 * field. The format string will have its placeholders substituted for the provided
1642 * values and be converted into a
1643 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1644 * field.
1646 * Other fields you may commonly want to pass into this function:
1648 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1649 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1650 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1651 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1652 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1654 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1655 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1656 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1657 * glib.h.
1659 * For example:
1660 * |[<!-- language="C" -->
1661 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1662 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1663 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1664 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1665 * some_pointer, some_integer);
1666 * ]|
1668 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1669 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1670 * If adding a `MESSAGE_ID`, consider shipping a [message
1671 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1672 * your software.
1674 * To pass a user data pointer to the log writer function which is specific to
1675 * this logging call, you must use g_log_structured_array() and pass the pointer
1676 * as a field with #GLogField.length set to zero, otherwise it will be
1677 * interpreted as a string.
1679 * For example:
1680 * |[<!-- language="C" -->
1681 * const GLogField fields[] = {
1682 * { "MESSAGE", "This is a debug message.", -1 },
1683 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1684 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1685 * { "MY_APPLICATION_STATE", state_object, 0 },
1686 * };
1687 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1688 * ]|
1690 * Note also that, even if no other structured fields are specified, there
1691 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1692 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1693 * field for which printf()-style formatting is supported.
1695 * The default writer function for `stdout` and `stderr` will automatically
1696 * append a new-line character after the message, so you should not add one
1697 * manually to the format string.
1699 * Since: 2.50
1701 void
1702 g_log_structured (const gchar *log_domain,
1703 GLogLevelFlags log_level,
1704 ...)
1706 va_list args;
1707 gchar buffer[1025], *message_allocated = NULL;
1708 const char *format;
1709 const gchar *message;
1710 gpointer p;
1711 gsize n_fields, i;
1712 GLogField stack_fields[16];
1713 GLogField *fields = stack_fields;
1714 GLogField *fields_allocated = NULL;
1715 GArray *array = NULL;
1717 va_start (args, log_level);
1719 /* MESSAGE and PRIORITY are a given */
1720 n_fields = 2;
1722 if (log_domain)
1723 n_fields++;
1725 for (p = va_arg (args, gchar *), i = n_fields;
1726 strcmp (p, "MESSAGE") != 0;
1727 p = va_arg (args, gchar *), i++)
1729 GLogField field;
1730 const gchar *key = p;
1731 gconstpointer value = va_arg (args, gpointer);
1733 field.key = key;
1734 field.value = value;
1735 field.length = -1;
1737 if (i < 16)
1738 stack_fields[i] = field;
1739 else
1741 /* Don't allow dynamic allocation, since we're likely
1742 * in an out-of-memory situation. For lack of a better solution,
1743 * just ignore further key-value pairs.
1745 if (log_level & G_LOG_FLAG_RECURSION)
1746 continue;
1748 if (i == 16)
1750 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1751 g_array_append_vals (array, stack_fields, 16);
1754 g_array_append_val (array, field);
1758 n_fields = i;
1760 if (array)
1761 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1763 format = va_arg (args, gchar *);
1765 if (log_level & G_LOG_FLAG_RECURSION)
1767 /* we use a stack buffer of fixed size, since we're likely
1768 * in an out-of-memory situation
1770 gsize size G_GNUC_UNUSED;
1772 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1773 message = buffer;
1775 else
1777 message = message_allocated = g_strdup_vprintf (format, args);
1780 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1781 fields[0].key = "MESSAGE";
1782 fields[0].value = message;
1783 fields[0].length = -1;
1785 fields[1].key = "PRIORITY";
1786 fields[1].value = log_level_to_priority (log_level);
1787 fields[1].length = -1;
1789 if (log_domain)
1791 fields[2].key = "GLIB_DOMAIN";
1792 fields[2].value = log_domain;
1793 fields[2].length = -1;
1796 /* Log it. */
1797 g_log_structured_array (log_level, fields, n_fields);
1799 g_free (fields_allocated);
1800 g_free (message_allocated);
1802 va_end (args);
1806 * g_log_variant:
1807 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1808 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1809 * level
1810 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1811 * containing the key-value pairs of message data.
1813 * Log a message with structured data, accepting the data within a #GVariant. This
1814 * version is especially useful for use in other languages, via introspection.
1816 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1817 * contain the text shown to the user.
1819 * The values in the @fields dictionary are likely to be of type String
1820 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1821 * supported. In this case the message is handled as binary and will be forwarded
1822 * to the log writer as such. The size of the array should not be higher than
1823 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1824 * g_variant_print() will be used to convert the value into a string.
1826 * For more details on its usage and about the parameters, see g_log_structured().
1828 * Since: 2.50
1831 void
1832 g_log_variant (const gchar *log_domain,
1833 GLogLevelFlags log_level,
1834 GVariant *fields)
1836 GVariantIter iter;
1837 GVariant *value;
1838 gchar *key;
1839 GArray *fields_array;
1840 GLogField field;
1841 GSList *values_list, *print_list;
1843 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1845 values_list = print_list = NULL;
1846 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1848 field.key = "PRIORITY";
1849 field.value = log_level_to_priority (log_level);
1850 field.length = -1;
1851 g_array_append_val (fields_array, field);
1853 if (log_domain)
1855 field.key = "GLIB_DOMAIN";
1856 field.value = log_domain;
1857 field.length = -1;
1858 g_array_append_val (fields_array, field);
1861 g_variant_iter_init (&iter, fields);
1862 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1864 gboolean defer_unref = TRUE;
1866 field.key = key;
1867 field.length = -1;
1869 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1871 field.value = g_variant_get_string (value, NULL);
1873 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1875 gsize s;
1876 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1877 if (G_LIKELY (s <= G_MAXSSIZE))
1879 field.length = s;
1881 else
1883 _g_fprintf (stderr,
1884 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1885 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1886 " bytes.", s);
1887 field.length = G_MAXSSIZE;
1890 else
1892 char *s = g_variant_print (value, FALSE);
1893 field.value = s;
1894 print_list = g_slist_prepend (print_list, s);
1895 defer_unref = FALSE;
1898 g_array_append_val (fields_array, field);
1900 if (G_LIKELY (defer_unref))
1901 values_list = g_slist_prepend (values_list, value);
1902 else
1903 g_variant_unref (value);
1906 /* Log it. */
1907 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1909 g_array_free (fields_array, TRUE);
1910 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1911 g_slist_free_full (print_list, g_free);
1915 #pragma GCC diagnostic pop
1917 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1918 const GLogField *fields,
1919 gsize n_fields,
1920 gpointer user_data);
1923 * g_log_structured_array:
1924 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1925 * level
1926 * @fields: (array length=n_fields): key–value pairs of structured data to add
1927 * to the log message
1928 * @n_fields: number of elements in the @fields array
1930 * Log a message with structured data. The message will be passed through to the
1931 * log writer set by the application using g_log_set_writer_func(). If the
1932 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1933 * be aborted at the end of this function.
1935 * See g_log_structured() for more documentation.
1937 * This assumes that @log_level is already present in @fields (typically as the
1938 * `PRIORITY` field).
1940 * Since: 2.50
1942 void
1943 g_log_structured_array (GLogLevelFlags log_level,
1944 const GLogField *fields,
1945 gsize n_fields)
1947 GLogWriterFunc writer_func;
1948 gpointer writer_user_data;
1949 gboolean recursion;
1950 guint depth;
1952 if (n_fields == 0)
1953 return;
1955 /* Check for recursion and look up the writer function. */
1956 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1957 recursion = (depth > 0);
1959 g_mutex_lock (&g_messages_lock);
1961 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1962 writer_user_data = log_writer_user_data;
1964 g_mutex_unlock (&g_messages_lock);
1966 /* Write the log entry. */
1967 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1969 g_assert (writer_func != NULL);
1970 writer_func (log_level, fields, n_fields, writer_user_data);
1972 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1974 /* Abort if the message was fatal. */
1975 if (log_level & G_LOG_FATAL_MASK)
1976 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1980 * g_log_set_writer_func:
1981 * @func: log writer function, which must not be %NULL
1982 * @user_data: (closure func): user data to pass to @func
1983 * @user_data_free: (destroy func): function to free @user_data once it’s
1984 * finished with, if non-%NULL
1986 * Set a writer function which will be called to format and write out each log
1987 * message. Each program should set a writer function, or the default writer
1988 * (g_log_writer_default()) will be used.
1990 * Libraries **must not** call this function — only programs are allowed to
1991 * install a writer function, as there must be a single, central point where
1992 * log messages are formatted and outputted.
1994 * There can only be one writer function. It is an error to set more than one.
1996 * Since: 2.50
1998 void
1999 g_log_set_writer_func (GLogWriterFunc func,
2000 gpointer user_data,
2001 GDestroyNotify user_data_free)
2003 g_return_if_fail (func != NULL);
2005 g_mutex_lock (&g_messages_lock);
2006 log_writer_func = func;
2007 log_writer_user_data = user_data;
2008 log_writer_user_data_free = user_data_free;
2009 g_mutex_unlock (&g_messages_lock);
2013 * g_log_writer_supports_color:
2014 * @output_fd: output file descriptor to check
2016 * Check whether the given @output_fd file descriptor supports ANSI color
2017 * escape sequences. If so, they can safely be used when formatting log
2018 * messages.
2020 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2021 * Since: 2.50
2023 gboolean
2024 g_log_writer_supports_color (gint output_fd)
2026 #ifdef G_OS_WIN32
2027 gboolean result = FALSE;
2029 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2030 _invalid_parameter_handler oldHandler, newHandler;
2031 int prev_report_mode = 0;
2032 #endif
2034 #endif
2036 g_return_val_if_fail (output_fd >= 0, FALSE);
2038 /* FIXME: This check could easily be expanded in future to be more robust
2039 * against different types of terminal, which still vary in their color
2040 * support. cmd.exe on Windows, for example, supports ANSI colors only
2041 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2042 * The Windows 10 color support is supported on:
2043 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2044 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2045 * but not:
2046 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2047 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2049 * On UNIX systems, we probably want to use the functions from terminfo to
2050 * work out whether colors are supported.
2052 * Some examples:
2053 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2054 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2055 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2056 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2058 #ifdef G_OS_WIN32
2060 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2061 /* Set up our empty invalid parameter handler, for isatty(),
2062 * in case of bad fd's passed in for isatty(), so that
2063 * msvcrt80.dll+ won't abort the program
2065 newHandler = myInvalidParameterHandler;
2066 oldHandler = _set_invalid_parameter_handler (newHandler);
2068 /* Disable the message box for assertions. */
2069 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2070 #endif
2072 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2074 HANDLE h_output;
2075 DWORD dw_mode;
2077 if (_isatty (output_fd))
2079 h_output = (HANDLE) _get_osfhandle (output_fd);
2081 if (!GetConsoleMode (h_output, &dw_mode))
2082 goto reset_invalid_param_handler;
2084 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2085 result = TRUE;
2087 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2088 goto reset_invalid_param_handler;
2090 result = TRUE;
2094 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2095 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2096 * (bug 775468), on standard Windows consoles, such as cmd.exe
2098 if (!result)
2099 result = win32_is_pipe_tty (output_fd);
2101 reset_invalid_param_handler:
2102 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2103 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2104 _set_invalid_parameter_handler (oldHandler);
2105 #endif
2107 return result;
2108 #else
2109 return isatty (output_fd);
2110 #endif
2113 #if defined(__linux__) && !defined(__BIONIC__)
2114 static int journal_fd = -1;
2116 #ifndef SOCK_CLOEXEC
2117 #define SOCK_CLOEXEC 0
2118 #else
2119 #define HAVE_SOCK_CLOEXEC 1
2120 #endif
2122 static void
2123 open_journal (void)
2125 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2126 return;
2128 #ifndef HAVE_SOCK_CLOEXEC
2129 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2131 close (journal_fd);
2132 journal_fd = -1;
2134 #endif
2136 #endif
2139 * g_log_writer_is_journald:
2140 * @output_fd: output file descriptor to check
2142 * Check whether the given @output_fd file descriptor is a connection to the
2143 * systemd journal, or something else (like a log file or `stdout` or
2144 * `stderr`).
2146 * Invalid file descriptors are accepted and return %FALSE, which allows for
2147 * the following construct without needing any additional error handling:
2148 * |[<!-- language="C" -->
2149 * is_journald = g_log_writer_is_journald (fileno (stderr));
2150 * ]|
2152 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2153 * Since: 2.50
2155 gboolean
2156 g_log_writer_is_journald (gint output_fd)
2158 #if defined(__linux__) && !defined(__BIONIC__)
2159 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2160 * journal. See: https://github.com/systemd/systemd/issues/2473
2162 static gsize initialized;
2163 static gboolean fd_is_journal = FALSE;
2165 if (output_fd < 0)
2166 return FALSE;
2168 if (g_once_init_enter (&initialized))
2170 union {
2171 struct sockaddr_storage storage;
2172 struct sockaddr sa;
2173 struct sockaddr_un un;
2174 } addr;
2175 socklen_t addr_len = sizeof(addr);
2176 int err = getpeername (output_fd, &addr.sa, &addr_len);
2177 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2178 fd_is_journal = g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2180 g_once_init_leave (&initialized, TRUE);
2183 return fd_is_journal;
2184 #else
2185 return FALSE;
2186 #endif
2189 static void escape_string (GString *string);
2192 * g_log_writer_format_fields:
2193 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2194 * level
2195 * @fields: (array length=n_fields): key–value pairs of structured data forming
2196 * the log message
2197 * @n_fields: number of elements in the @fields array
2198 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2199 * message, %FALSE to not
2201 * Format a structured log message as a string suitable for outputting to the
2202 * terminal (or elsewhere). This will include the values of all fields it knows
2203 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2204 * documentation for g_log_structured()). It does not include values from
2205 * unknown fields.
2207 * The returned string does **not** have a trailing new-line character. It is
2208 * encoded in the character set of the current locale, which is not necessarily
2209 * UTF-8.
2211 * Returns: (transfer full): string containing the formatted log message, in
2212 * the character set of the current locale
2213 * Since: 2.50
2215 gchar *
2216 g_log_writer_format_fields (GLogLevelFlags log_level,
2217 const GLogField *fields,
2218 gsize n_fields,
2219 gboolean use_color)
2221 gsize i;
2222 const gchar *message = NULL;
2223 const gchar *log_domain = NULL;
2224 gchar level_prefix[STRING_BUFFER_SIZE];
2225 GString *gstring;
2226 gint64 now;
2227 time_t now_secs;
2228 struct tm *now_tm;
2229 gchar time_buf[128];
2231 /* Extract some common fields. */
2232 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2234 const GLogField *field = &fields[i];
2236 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2237 message = field->value;
2238 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2239 log_domain = field->value;
2242 /* Format things. */
2243 mklevel_prefix (level_prefix, log_level, use_color);
2245 gstring = g_string_new (NULL);
2246 if (log_level & ALERT_LEVELS)
2247 g_string_append (gstring, "\n");
2248 if (!log_domain)
2249 g_string_append (gstring, "** ");
2251 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2252 (log_level & G_LOG_LEVEL_MASK))
2254 const gchar *prg_name = g_get_prgname ();
2255 gulong pid = getpid ();
2257 if (prg_name == NULL)
2258 g_string_append_printf (gstring, "(process:%lu): ", pid);
2259 else
2260 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2263 if (log_domain != NULL)
2265 g_string_append (gstring, log_domain);
2266 g_string_append_c (gstring, '-');
2268 g_string_append (gstring, level_prefix);
2270 g_string_append (gstring, ": ");
2272 /* Timestamp */
2273 now = g_get_real_time ();
2274 now_secs = (time_t) (now / 1000000);
2275 now_tm = localtime (&now_secs);
2276 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2278 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2279 use_color ? "\033[34m" : "",
2280 time_buf, (gint) ((now / 1000) % 1000),
2281 color_reset (use_color));
2283 if (message == NULL)
2285 g_string_append (gstring, "(NULL) message");
2287 else
2289 GString *msg;
2290 const gchar *charset;
2292 msg = g_string_new (message);
2293 escape_string (msg);
2295 if (g_get_charset (&charset))
2297 /* charset is UTF-8 already */
2298 g_string_append (gstring, msg->str);
2300 else
2302 gchar *lstring = strdup_convert (msg->str, charset);
2303 g_string_append (gstring, lstring);
2304 g_free (lstring);
2307 g_string_free (msg, TRUE);
2310 return g_string_free (gstring, FALSE);
2313 /* Enable support for the journal if we're on a recent enough Linux */
2314 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2315 #define ENABLE_JOURNAL_SENDV
2316 #endif
2318 #ifdef ENABLE_JOURNAL_SENDV
2319 static int
2320 journal_sendv (struct iovec *iov,
2321 gsize iovlen)
2323 int buf_fd = -1;
2324 struct msghdr mh;
2325 struct sockaddr_un sa;
2326 union {
2327 struct cmsghdr cmsghdr;
2328 guint8 buf[CMSG_SPACE(sizeof(int))];
2329 } control;
2330 struct cmsghdr *cmsg;
2331 char path[] = "/dev/shm/journal.XXXXXX";
2333 if (journal_fd < 0)
2334 open_journal ();
2336 if (journal_fd < 0)
2337 return -1;
2339 memset (&sa, 0, sizeof (sa));
2340 sa.sun_family = AF_UNIX;
2341 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2342 return -1;
2344 memset (&mh, 0, sizeof (mh));
2345 mh.msg_name = &sa;
2346 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2347 mh.msg_iov = iov;
2348 mh.msg_iovlen = iovlen;
2350 retry:
2351 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2352 return 0;
2354 if (errno == EINTR)
2355 goto retry;
2357 if (errno != EMSGSIZE && errno != ENOBUFS)
2358 return -1;
2360 /* Message was too large, so dump to temporary file
2361 * and pass an FD to the journal
2363 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2364 return -1;
2366 if (unlink (path) < 0)
2368 close (buf_fd);
2369 return -1;
2372 if (writev (buf_fd, iov, iovlen) < 0)
2374 close (buf_fd);
2375 return -1;
2378 mh.msg_iov = NULL;
2379 mh.msg_iovlen = 0;
2381 memset (&control, 0, sizeof (control));
2382 mh.msg_control = &control;
2383 mh.msg_controllen = sizeof (control);
2385 cmsg = CMSG_FIRSTHDR (&mh);
2386 cmsg->cmsg_level = SOL_SOCKET;
2387 cmsg->cmsg_type = SCM_RIGHTS;
2388 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2389 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2391 mh.msg_controllen = cmsg->cmsg_len;
2393 retry2:
2394 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2395 return 0;
2397 if (errno == EINTR)
2398 goto retry2;
2400 return -1;
2402 #endif /* ENABLE_JOURNAL_SENDV */
2405 * g_log_writer_journald:
2406 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2407 * level
2408 * @fields: (array length=n_fields): key–value pairs of structured data forming
2409 * the log message
2410 * @n_fields: number of elements in the @fields array
2411 * @user_data: user data passed to g_log_set_writer_func()
2413 * Format a structured log message and send it to the systemd journal as a set
2414 * of key–value pairs. All fields are sent to the journal, but if a field has
2415 * length zero (indicating program-specific data) then only its key will be
2416 * sent.
2418 * This is suitable for use as a #GLogWriterFunc.
2420 * If GLib has been compiled without systemd support, this function is still
2421 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2423 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2424 * Since: 2.50
2426 GLogWriterOutput
2427 g_log_writer_journald (GLogLevelFlags log_level,
2428 const GLogField *fields,
2429 gsize n_fields,
2430 gpointer user_data)
2432 #ifdef ENABLE_JOURNAL_SENDV
2433 const char equals = '=';
2434 const char newline = '\n';
2435 gsize i, k;
2436 struct iovec *iov, *v;
2437 char *buf;
2438 gint retval;
2440 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2441 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2443 /* According to systemd.journal-fields(7), the journal allows fields in any
2444 * format (including arbitrary binary), but expects text fields to be UTF-8.
2445 * This is great, because we require input strings to be in UTF-8, so no
2446 * conversion is necessary and we don’t need to care about the current
2447 * locale’s character set.
2450 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2451 buf = g_alloca (32 * n_fields);
2453 k = 0;
2454 v = iov;
2455 for (i = 0; i < n_fields; i++)
2457 guint64 length;
2458 gboolean binary;
2460 if (fields[i].length < 0)
2462 length = strlen (fields[i].value);
2463 binary = strchr (fields[i].value, '\n') != NULL;
2465 else
2467 length = fields[i].length;
2468 binary = TRUE;
2471 if (binary)
2473 guint64 nstr;
2475 v[0].iov_base = (gpointer)fields[i].key;
2476 v[0].iov_len = strlen (fields[i].key);
2478 v[1].iov_base = (gpointer)&newline;
2479 v[1].iov_len = 1;
2481 nstr = GUINT64_TO_LE(length);
2482 memcpy (&buf[k], &nstr, sizeof (nstr));
2484 v[2].iov_base = &buf[k];
2485 v[2].iov_len = sizeof (nstr);
2486 v += 3;
2487 k += sizeof (nstr);
2489 else
2491 v[0].iov_base = (gpointer)fields[i].key;
2492 v[0].iov_len = strlen (fields[i].key);
2494 v[1].iov_base = (gpointer)&equals;
2495 v[1].iov_len = 1;
2496 v += 2;
2499 v[0].iov_base = (gpointer)fields[i].value;
2500 v[0].iov_len = length;
2502 v[1].iov_base = (gpointer)&newline;
2503 v[1].iov_len = 1;
2504 v += 2;
2507 retval = journal_sendv (iov, v - iov);
2509 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2510 #else
2511 return G_LOG_WRITER_UNHANDLED;
2512 #endif /* ENABLE_JOURNAL_SENDV */
2516 * g_log_writer_standard_streams:
2517 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2518 * level
2519 * @fields: (array length=n_fields): key–value pairs of structured data forming
2520 * the log message
2521 * @n_fields: number of elements in the @fields array
2522 * @user_data: user data passed to g_log_set_writer_func()
2524 * Format a structured log message and print it to either `stdout` or `stderr`,
2525 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2526 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2527 * which are understood by this function are included in the formatted string
2528 * which is printed.
2530 * If the output stream supports ANSI color escape sequences, they will be used
2531 * in the output.
2533 * A trailing new-line character is added to the log message when it is printed.
2535 * This is suitable for use as a #GLogWriterFunc.
2537 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2538 * Since: 2.50
2540 GLogWriterOutput
2541 g_log_writer_standard_streams (GLogLevelFlags log_level,
2542 const GLogField *fields,
2543 gsize n_fields,
2544 gpointer user_data)
2546 FILE *stream;
2547 gchar *out = NULL; /* in the current locale’s character set */
2549 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2550 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2552 stream = log_level_to_file (log_level);
2553 if (!stream || fileno (stream) < 0)
2554 return G_LOG_WRITER_UNHANDLED;
2556 out = g_log_writer_format_fields (log_level, fields, n_fields,
2557 g_log_writer_supports_color (fileno (stream)));
2558 _g_fprintf (stream, "%s\n", out);
2559 fflush (stream);
2560 g_free (out);
2562 return G_LOG_WRITER_HANDLED;
2565 /* The old g_log() API is implemented in terms of the new structured log API.
2566 * However, some of the checks do not line up between the two APIs: the
2567 * structured API only handles fatalness of messages for log levels; the old API
2568 * handles it per-domain as well. Consequently, we need to disable fatalness
2569 * handling in the structured log API when called from the old g_log() API.
2571 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2572 * the first field to g_log_structured_array(), if that is the case.
2574 static gboolean
2575 log_is_old_api (const GLogField *fields,
2576 gsize n_fields)
2578 return (n_fields >= 1 &&
2579 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2580 g_strcmp0 (fields[0].value, "1") == 0);
2584 * g_log_writer_default:
2585 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2586 * level
2587 * @fields: (array length=n_fields): key–value pairs of structured data forming
2588 * the log message
2589 * @n_fields: number of elements in the @fields array
2590 * @user_data: user data passed to g_log_set_writer_func()
2592 * Format a structured log message and output it to the default log destination
2593 * for the platform. On Linux, this is typically the systemd journal, falling
2594 * back to `stdout` or `stderr` if running from the terminal or if output is
2595 * being redirected to a file.
2597 * Support for other platform-specific logging mechanisms may be added in
2598 * future. Distributors of GLib may modify this function to impose their own
2599 * (documented) platform-specific log writing policies.
2601 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2602 * if no other is set using g_log_set_writer_func().
2604 * As with g_log_default_handler(), this function drops debug and informational
2605 * messages unless their log domain (or `all`) is listed in the space-separated
2606 * `G_MESSAGES_DEBUG` environment variable.
2608 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2609 * Since: 2.50
2611 GLogWriterOutput
2612 g_log_writer_default (GLogLevelFlags log_level,
2613 const GLogField *fields,
2614 gsize n_fields,
2615 gpointer user_data)
2617 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2618 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2620 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2621 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2623 const gchar *domains, *log_domain = NULL;
2624 gsize i;
2626 domains = g_getenv ("G_MESSAGES_DEBUG");
2628 if ((log_level & INFO_LEVELS) == 0 ||
2629 domains == NULL)
2630 return G_LOG_WRITER_HANDLED;
2632 for (i = 0; i < n_fields; i++)
2634 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2636 log_domain = fields[i].value;
2637 break;
2641 if (strcmp (domains, "all") != 0 &&
2642 (log_domain == NULL || !strstr (domains, log_domain)))
2643 return G_LOG_WRITER_HANDLED;
2646 /* Mark messages as fatal if they have a level set in
2647 * g_log_set_always_fatal().
2649 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2650 log_level |= G_LOG_FLAG_FATAL;
2652 /* Try logging to the systemd journal as first choice. */
2653 if (g_log_writer_is_journald (fileno (stderr)) &&
2654 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2655 G_LOG_WRITER_HANDLED)
2656 goto handled;
2658 /* FIXME: Add support for the Windows log. */
2660 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2661 G_LOG_WRITER_HANDLED)
2662 goto handled;
2664 return G_LOG_WRITER_UNHANDLED;
2666 handled:
2667 /* Abort if the message was fatal. */
2668 if (log_level & G_LOG_FLAG_FATAL)
2670 #ifdef G_OS_WIN32
2671 if (!g_test_initialized ())
2673 gchar *locale_msg = NULL;
2675 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2676 MessageBox (NULL, locale_msg, NULL,
2677 MB_ICONERROR | MB_SETFOREGROUND);
2678 g_free (locale_msg);
2680 #endif /* !G_OS_WIN32 */
2682 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2685 return G_LOG_WRITER_HANDLED;
2688 static GLogWriterOutput
2689 _g_log_writer_fallback (GLogLevelFlags log_level,
2690 const GLogField *fields,
2691 gsize n_fields,
2692 gpointer user_data)
2694 FILE *stream;
2695 gsize i;
2697 /* we cannot call _any_ GLib functions in this fallback handler,
2698 * which is why we skip UTF-8 conversion, etc.
2699 * since we either recursed or ran out of memory, we're in a pretty
2700 * pathologic situation anyways, what we can do is giving the
2701 * the process ID unconditionally however.
2704 stream = log_level_to_file (log_level);
2706 for (i = 0; i < n_fields; i++)
2708 const GLogField *field = &fields[i];
2710 /* Only print fields we definitely recognise, otherwise we could end up
2711 * printing a random non-string pointer provided by the user to be
2712 * interpreted by their writer function.
2714 if (strcmp (field->key, "MESSAGE") != 0 &&
2715 strcmp (field->key, "MESSAGE_ID") != 0 &&
2716 strcmp (field->key, "PRIORITY") != 0 &&
2717 strcmp (field->key, "CODE_FILE") != 0 &&
2718 strcmp (field->key, "CODE_LINE") != 0 &&
2719 strcmp (field->key, "CODE_FUNC") != 0 &&
2720 strcmp (field->key, "ERRNO") != 0 &&
2721 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2722 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2723 strcmp (field->key, "SYSLOG_PID") != 0 &&
2724 strcmp (field->key, "GLIB_DOMAIN") != 0)
2725 continue;
2727 write_string (stream, field->key);
2728 write_string (stream, "=");
2729 write_string_sized (stream, field->value, field->length);
2732 #ifndef G_OS_WIN32
2734 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2736 format_unsigned (pid_string, getpid (), 10);
2737 write_string (stream, "_PID=");
2738 write_string (stream, pid_string);
2740 #endif
2742 return G_LOG_WRITER_HANDLED;
2746 * g_return_if_fail_warning: (skip)
2747 * @log_domain: (nullable):
2748 * @pretty_function:
2749 * @expression: (nullable):
2751 void
2752 g_return_if_fail_warning (const char *log_domain,
2753 const char *pretty_function,
2754 const char *expression)
2756 g_log (log_domain,
2757 G_LOG_LEVEL_CRITICAL,
2758 "%s: assertion '%s' failed",
2759 pretty_function,
2760 expression);
2764 * g_warn_message: (skip)
2765 * @domain: (nullable):
2766 * @file:
2767 * @line:
2768 * @func:
2769 * @warnexpr: (nullable):
2771 void
2772 g_warn_message (const char *domain,
2773 const char *file,
2774 int line,
2775 const char *func,
2776 const char *warnexpr)
2778 char *s, lstr[32];
2779 g_snprintf (lstr, 32, "%d", line);
2780 if (warnexpr)
2781 s = g_strconcat ("(", file, ":", lstr, "):",
2782 func, func[0] ? ":" : "",
2783 " runtime check failed: (", warnexpr, ")", NULL);
2784 else
2785 s = g_strconcat ("(", file, ":", lstr, "):",
2786 func, func[0] ? ":" : "",
2787 " ", "code should not be reached", NULL);
2788 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2789 g_free (s);
2792 void
2793 g_assert_warning (const char *log_domain,
2794 const char *file,
2795 const int line,
2796 const char *pretty_function,
2797 const char *expression)
2799 if (expression)
2800 g_log (log_domain,
2801 G_LOG_LEVEL_ERROR,
2802 "file %s: line %d (%s): assertion failed: (%s)",
2803 file,
2804 line,
2805 pretty_function,
2806 expression);
2807 else
2808 g_log (log_domain,
2809 G_LOG_LEVEL_ERROR,
2810 "file %s: line %d (%s): should not be reached",
2811 file,
2812 line,
2813 pretty_function);
2814 _g_log_abort (FALSE);
2815 g_abort ();
2819 * g_test_expect_message:
2820 * @log_domain: (nullable): the log domain of the message
2821 * @log_level: the log level of the message
2822 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2824 * Indicates that a message with the given @log_domain and @log_level,
2825 * with text matching @pattern, is expected to be logged. When this
2826 * message is logged, it will not be printed, and the test case will
2827 * not abort.
2829 * This API may only be used with the old logging API (g_log() without
2830 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2831 * API. See [Testing for Messages][testing-for-messages].
2833 * Use g_test_assert_expected_messages() to assert that all
2834 * previously-expected messages have been seen and suppressed.
2836 * You can call this multiple times in a row, if multiple messages are
2837 * expected as a result of a single call. (The messages must appear in
2838 * the same order as the calls to g_test_expect_message().)
2840 * For example:
2842 * |[<!-- language="C" -->
2843 * // g_main_context_push_thread_default() should fail if the
2844 * // context is already owned by another thread.
2845 * g_test_expect_message (G_LOG_DOMAIN,
2846 * G_LOG_LEVEL_CRITICAL,
2847 * "assertion*acquired_context*failed");
2848 * g_main_context_push_thread_default (bad_context);
2849 * g_test_assert_expected_messages ();
2850 * ]|
2852 * Note that you cannot use this to test g_error() messages, since
2853 * g_error() intentionally never returns even if the program doesn't
2854 * abort; use g_test_trap_subprocess() in this case.
2856 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2857 * expected via g_test_expect_message() then they will be ignored.
2859 * Since: 2.34
2861 void
2862 g_test_expect_message (const gchar *log_domain,
2863 GLogLevelFlags log_level,
2864 const gchar *pattern)
2866 GTestExpectedMessage *expected;
2868 g_return_if_fail (log_level != 0);
2869 g_return_if_fail (pattern != NULL);
2870 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2872 expected = g_new (GTestExpectedMessage, 1);
2873 expected->log_domain = g_strdup (log_domain);
2874 expected->log_level = log_level;
2875 expected->pattern = g_strdup (pattern);
2877 expected_messages = g_slist_append (expected_messages, expected);
2880 void
2881 g_test_assert_expected_messages_internal (const char *domain,
2882 const char *file,
2883 int line,
2884 const char *func)
2886 if (expected_messages)
2888 GTestExpectedMessage *expected;
2889 gchar level_prefix[STRING_BUFFER_SIZE];
2890 gchar *message;
2892 expected = expected_messages->data;
2894 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2895 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2896 expected->log_domain ? expected->log_domain : "**",
2897 level_prefix, expected->pattern);
2898 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2899 g_free (message);
2904 * g_test_assert_expected_messages:
2906 * Asserts that all messages previously indicated via
2907 * g_test_expect_message() have been seen and suppressed.
2909 * This API may only be used with the old logging API (g_log() without
2910 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2911 * API. See [Testing for Messages][testing-for-messages].
2913 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2914 * expected via g_test_expect_message() then they will be ignored.
2916 * Since: 2.34
2919 void
2920 _g_log_fallback_handler (const gchar *log_domain,
2921 GLogLevelFlags log_level,
2922 const gchar *message,
2923 gpointer unused_data)
2925 gchar level_prefix[STRING_BUFFER_SIZE];
2926 #ifndef G_OS_WIN32
2927 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2928 #endif
2929 FILE *stream;
2931 /* we cannot call _any_ GLib functions in this fallback handler,
2932 * which is why we skip UTF-8 conversion, etc.
2933 * since we either recursed or ran out of memory, we're in a pretty
2934 * pathologic situation anyways, what we can do is giving the
2935 * the process ID unconditionally however.
2938 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2939 if (!message)
2940 message = "(NULL) message";
2942 #ifndef G_OS_WIN32
2943 format_unsigned (pid_string, getpid (), 10);
2944 #endif
2946 if (log_domain)
2947 write_string (stream, "\n");
2948 else
2949 write_string (stream, "\n** ");
2951 #ifndef G_OS_WIN32
2952 write_string (stream, "(process:");
2953 write_string (stream, pid_string);
2954 write_string (stream, "): ");
2955 #endif
2957 if (log_domain)
2959 write_string (stream, log_domain);
2960 write_string (stream, "-");
2962 write_string (stream, level_prefix);
2963 write_string (stream, ": ");
2964 write_string (stream, message);
2967 static void
2968 escape_string (GString *string)
2970 const char *p = string->str;
2971 gunichar wc;
2973 while (p < string->str + string->len)
2975 gboolean safe;
2977 wc = g_utf8_get_char_validated (p, -1);
2978 if (wc == (gunichar)-1 || wc == (gunichar)-2)
2980 gchar *tmp;
2981 guint pos;
2983 pos = p - string->str;
2985 /* Emit invalid UTF-8 as hex escapes
2987 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
2988 g_string_erase (string, pos, 1);
2989 g_string_insert (string, pos, tmp);
2991 p = string->str + (pos + 4); /* Skip over escape sequence */
2993 g_free (tmp);
2994 continue;
2996 if (wc == '\r')
2998 safe = *(p + 1) == '\n';
3000 else
3002 safe = CHAR_IS_SAFE (wc);
3005 if (!safe)
3007 gchar *tmp;
3008 guint pos;
3010 pos = p - string->str;
3012 /* Largest char we escape is 0x0a, so we don't have to worry
3013 * about 8-digit \Uxxxxyyyy
3015 tmp = g_strdup_printf ("\\u%04x", wc);
3016 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3017 g_string_insert (string, pos, tmp);
3018 g_free (tmp);
3020 p = string->str + (pos + 6); /* Skip over escape sequence */
3022 else
3023 p = g_utf8_next_char (p);
3028 * g_log_default_handler:
3029 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3030 * default "" application domain
3031 * @log_level: the level of the message
3032 * @message: (nullable): the message
3033 * @unused_data: (nullable): data passed from g_log() which is unused
3035 * The default log handler set up by GLib; g_log_set_default_handler()
3036 * allows to install an alternate default log handler.
3037 * This is used if no log handler has been set for the particular log
3038 * domain and log level combination. It outputs the message to stderr
3039 * or stdout and if the log level is fatal it calls abort(). It automatically
3040 * prints a new-line character after the message, so one does not need to be
3041 * manually included in @message.
3043 * The behavior of this log handler can be influenced by a number of
3044 * environment variables:
3046 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3047 * messages should be prefixed by the program name and PID of the
3048 * aplication.
3050 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3051 * which debug and informational messages are printed. By default
3052 * these messages are not printed.
3054 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3055 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3056 * the rest.
3058 * This has no effect if structured logging is enabled; see
3059 * [Using Structured Logging][using-structured-logging].
3061 void
3062 g_log_default_handler (const gchar *log_domain,
3063 GLogLevelFlags log_level,
3064 const gchar *message,
3065 gpointer unused_data)
3067 GLogField fields[4];
3068 int n_fields = 0;
3070 /* we can be called externally with recursion for whatever reason */
3071 if (log_level & G_LOG_FLAG_RECURSION)
3073 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3074 return;
3077 fields[0].key = "GLIB_OLD_LOG_API";
3078 fields[0].value = "1";
3079 fields[0].length = -1;
3080 n_fields++;
3082 fields[1].key = "MESSAGE";
3083 fields[1].value = message;
3084 fields[1].length = -1;
3085 n_fields++;
3087 fields[2].key = "PRIORITY";
3088 fields[2].value = log_level_to_priority (log_level);
3089 fields[2].length = -1;
3090 n_fields++;
3092 if (log_domain)
3094 fields[3].key = "GLIB_DOMAIN";
3095 fields[3].value = log_domain;
3096 fields[3].length = -1;
3097 n_fields++;
3100 /* Print out via the structured log API, but drop any fatal flags since we
3101 * have already handled them. The fatal handling in the structured logging
3102 * API is more coarse-grained than in the old g_log() API, so we don't want
3103 * to use it here.
3105 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3109 * g_set_print_handler:
3110 * @func: the new print handler
3112 * Sets the print handler.
3114 * Any messages passed to g_print() will be output via
3115 * the new handler. The default handler simply outputs
3116 * the message to stdout. By providing your own handler
3117 * you can redirect the output, to a GTK+ widget or a
3118 * log file for example.
3120 * Returns: the old print handler
3122 GPrintFunc
3123 g_set_print_handler (GPrintFunc func)
3125 GPrintFunc old_print_func;
3127 g_mutex_lock (&g_messages_lock);
3128 old_print_func = glib_print_func;
3129 glib_print_func = func;
3130 g_mutex_unlock (&g_messages_lock);
3132 return old_print_func;
3136 * g_print:
3137 * @format: the message format. See the printf() documentation
3138 * @...: the parameters to insert into the format string
3140 * Outputs a formatted message via the print handler.
3141 * The default print handler simply outputs the message to stdout, without
3142 * appending a trailing new-line character. Typically, @format should end with
3143 * its own new-line character.
3145 * g_print() should not be used from within libraries for debugging
3146 * messages, since it may be redirected by applications to special
3147 * purpose message windows or even files. Instead, libraries should
3148 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3149 * g_warning() and g_error().
3151 void
3152 g_print (const gchar *format,
3153 ...)
3155 va_list args;
3156 gchar *string;
3157 GPrintFunc local_glib_print_func;
3159 g_return_if_fail (format != NULL);
3161 va_start (args, format);
3162 string = g_strdup_vprintf (format, args);
3163 va_end (args);
3165 g_mutex_lock (&g_messages_lock);
3166 local_glib_print_func = glib_print_func;
3167 g_mutex_unlock (&g_messages_lock);
3169 if (local_glib_print_func)
3170 local_glib_print_func (string);
3171 else
3173 const gchar *charset;
3175 if (g_get_charset (&charset))
3176 fputs (string, stdout); /* charset is UTF-8 already */
3177 else
3179 gchar *lstring = strdup_convert (string, charset);
3181 fputs (lstring, stdout);
3182 g_free (lstring);
3184 fflush (stdout);
3186 g_free (string);
3190 * g_set_printerr_handler:
3191 * @func: the new error message handler
3193 * Sets the handler for printing error messages.
3195 * Any messages passed to g_printerr() will be output via
3196 * the new handler. The default handler simply outputs the
3197 * message to stderr. By providing your own handler you can
3198 * redirect the output, to a GTK+ widget or a log file for
3199 * example.
3201 * Returns: the old error message handler
3203 GPrintFunc
3204 g_set_printerr_handler (GPrintFunc func)
3206 GPrintFunc old_printerr_func;
3208 g_mutex_lock (&g_messages_lock);
3209 old_printerr_func = glib_printerr_func;
3210 glib_printerr_func = func;
3211 g_mutex_unlock (&g_messages_lock);
3213 return old_printerr_func;
3217 * g_printerr:
3218 * @format: the message format. See the printf() documentation
3219 * @...: the parameters to insert into the format string
3221 * Outputs a formatted message via the error message handler.
3222 * The default handler simply outputs the message to stderr, without appending
3223 * a trailing new-line character. Typically, @format should end with its own
3224 * new-line character.
3226 * g_printerr() should not be used from within libraries.
3227 * Instead g_log() or g_log_structured() should be used, or the convenience
3228 * macros g_message(), g_warning() and g_error().
3230 void
3231 g_printerr (const gchar *format,
3232 ...)
3234 va_list args;
3235 gchar *string;
3236 GPrintFunc local_glib_printerr_func;
3238 g_return_if_fail (format != NULL);
3240 va_start (args, format);
3241 string = g_strdup_vprintf (format, args);
3242 va_end (args);
3244 g_mutex_lock (&g_messages_lock);
3245 local_glib_printerr_func = glib_printerr_func;
3246 g_mutex_unlock (&g_messages_lock);
3248 if (local_glib_printerr_func)
3249 local_glib_printerr_func (string);
3250 else
3252 const gchar *charset;
3254 if (g_get_charset (&charset))
3255 fputs (string, stderr); /* charset is UTF-8 already */
3256 else
3258 gchar *lstring = strdup_convert (string, charset);
3260 fputs (lstring, stderr);
3261 g_free (lstring);
3263 fflush (stderr);
3265 g_free (string);
3269 * g_printf_string_upper_bound:
3270 * @format: the format string. See the printf() documentation
3271 * @args: the parameters to be inserted into the format string
3273 * Calculates the maximum space needed to store the output
3274 * of the sprintf() function.
3276 * Returns: the maximum space needed to store the formatted string
3278 gsize
3279 g_printf_string_upper_bound (const gchar *format,
3280 va_list args)
3282 gchar c;
3283 return _g_vsnprintf (&c, 1, format, args) + 1;