gdate: Make integer comparisons explicit
[glib.git] / glib / gmessages.c
blobcbaed5da9db813f7e9377650d2390754e828af9f
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"; /* red */
1480 else if (log_level & G_LOG_LEVEL_CRITICAL)
1481 return "\033[1;35m"; /* magenta */
1482 else if (log_level & G_LOG_LEVEL_WARNING)
1483 return "\033[1;33m"; /* yellow */
1484 else if (log_level & G_LOG_LEVEL_MESSAGE)
1485 return "\033[1;32m"; /* green */
1486 else if (log_level & G_LOG_LEVEL_INFO)
1487 return "\033[1;32m"; /* green */
1488 else if (log_level & G_LOG_LEVEL_DEBUG)
1489 return "\033[1;32m"; /* green */
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));
1979 /* Semi-private helper function to implement the g_message() (etc.) macros
1980 * with support for G_GNUC_PRINTF so that @message_format can be checked
1981 * with -Wformat. */
1982 void
1983 g_log_structured_standard (const gchar *log_domain,
1984 GLogLevelFlags log_level,
1985 const gchar *file,
1986 const gchar *line,
1987 const gchar *func,
1988 const gchar *message_format,
1989 ...)
1991 GLogField fields[] =
1993 { "PRIORITY", log_level_to_priority (log_level), -1 },
1994 { "CODE_FILE", file, -1 },
1995 { "CODE_LINE", line, -1 },
1996 { "CODE_FUNC", func, -1 },
1997 /* Filled in later: */
1998 { "MESSAGE", NULL, -1 },
1999 /* If @log_domain is %NULL, we will not pass this field: */
2000 { "GLIB_DOMAIN", log_domain, -1 },
2002 gsize n_fields;
2003 gchar *message_allocated = NULL;
2004 gchar buffer[1025];
2005 va_list args;
2007 va_start (args, message_format);
2009 if (log_level & G_LOG_FLAG_RECURSION)
2011 /* we use a stack buffer of fixed size, since we're likely
2012 * in an out-of-memory situation
2014 gsize size G_GNUC_UNUSED;
2016 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
2017 fields[4].value = buffer;
2019 else
2021 fields[4].value = message_allocated = g_strdup_vprintf (message_format, args);
2024 va_end (args);
2026 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
2027 g_log_structured_array (log_level, fields, n_fields);
2029 g_free (message_allocated);
2033 * g_log_set_writer_func:
2034 * @func: log writer function, which must not be %NULL
2035 * @user_data: (closure func): user data to pass to @func
2036 * @user_data_free: (destroy func): function to free @user_data once it’s
2037 * finished with, if non-%NULL
2039 * Set a writer function which will be called to format and write out each log
2040 * message. Each program should set a writer function, or the default writer
2041 * (g_log_writer_default()) will be used.
2043 * Libraries **must not** call this function — only programs are allowed to
2044 * install a writer function, as there must be a single, central point where
2045 * log messages are formatted and outputted.
2047 * There can only be one writer function. It is an error to set more than one.
2049 * Since: 2.50
2051 void
2052 g_log_set_writer_func (GLogWriterFunc func,
2053 gpointer user_data,
2054 GDestroyNotify user_data_free)
2056 g_return_if_fail (func != NULL);
2058 g_mutex_lock (&g_messages_lock);
2059 log_writer_func = func;
2060 log_writer_user_data = user_data;
2061 log_writer_user_data_free = user_data_free;
2062 g_mutex_unlock (&g_messages_lock);
2066 * g_log_writer_supports_color:
2067 * @output_fd: output file descriptor to check
2069 * Check whether the given @output_fd file descriptor supports ANSI color
2070 * escape sequences. If so, they can safely be used when formatting log
2071 * messages.
2073 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2074 * Since: 2.50
2076 gboolean
2077 g_log_writer_supports_color (gint output_fd)
2079 #ifdef G_OS_WIN32
2080 gboolean result = FALSE;
2082 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2083 _invalid_parameter_handler oldHandler, newHandler;
2084 int prev_report_mode = 0;
2085 #endif
2087 #endif
2089 g_return_val_if_fail (output_fd >= 0, FALSE);
2091 /* FIXME: This check could easily be expanded in future to be more robust
2092 * against different types of terminal, which still vary in their color
2093 * support. cmd.exe on Windows, for example, supports ANSI colors only
2094 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2095 * The Windows 10 color support is supported on:
2096 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2097 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2098 * but not:
2099 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2100 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2102 * On UNIX systems, we probably want to use the functions from terminfo to
2103 * work out whether colors are supported.
2105 * Some examples:
2106 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2107 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2108 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2109 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2111 #ifdef G_OS_WIN32
2113 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2114 /* Set up our empty invalid parameter handler, for isatty(),
2115 * in case of bad fd's passed in for isatty(), so that
2116 * msvcrt80.dll+ won't abort the program
2118 newHandler = myInvalidParameterHandler;
2119 oldHandler = _set_invalid_parameter_handler (newHandler);
2121 /* Disable the message box for assertions. */
2122 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2123 #endif
2125 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2127 HANDLE h_output;
2128 DWORD dw_mode;
2130 if (_isatty (output_fd))
2132 h_output = (HANDLE) _get_osfhandle (output_fd);
2134 if (!GetConsoleMode (h_output, &dw_mode))
2135 goto reset_invalid_param_handler;
2137 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2138 result = TRUE;
2140 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2141 goto reset_invalid_param_handler;
2143 result = TRUE;
2147 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2148 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2149 * (bug 775468), on standard Windows consoles, such as cmd.exe
2151 if (!result)
2152 result = win32_is_pipe_tty (output_fd);
2154 reset_invalid_param_handler:
2155 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2156 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2157 _set_invalid_parameter_handler (oldHandler);
2158 #endif
2160 return result;
2161 #else
2162 return isatty (output_fd);
2163 #endif
2166 #if defined(__linux__) && !defined(__BIONIC__)
2167 static int journal_fd = -1;
2169 #ifndef SOCK_CLOEXEC
2170 #define SOCK_CLOEXEC 0
2171 #else
2172 #define HAVE_SOCK_CLOEXEC 1
2173 #endif
2175 static void
2176 open_journal (void)
2178 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2179 return;
2181 #ifndef HAVE_SOCK_CLOEXEC
2182 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2184 close (journal_fd);
2185 journal_fd = -1;
2187 #endif
2189 #endif
2192 * g_log_writer_is_journald:
2193 * @output_fd: output file descriptor to check
2195 * Check whether the given @output_fd file descriptor is a connection to the
2196 * systemd journal, or something else (like a log file or `stdout` or
2197 * `stderr`).
2199 * Invalid file descriptors are accepted and return %FALSE, which allows for
2200 * the following construct without needing any additional error handling:
2201 * |[<!-- language="C" -->
2202 * is_journald = g_log_writer_is_journald (fileno (stderr));
2203 * ]|
2205 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2206 * Since: 2.50
2208 gboolean
2209 g_log_writer_is_journald (gint output_fd)
2211 #if defined(__linux__) && !defined(__BIONIC__)
2212 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2213 * journal. See: https://github.com/systemd/systemd/issues/2473
2215 static gsize initialized;
2216 static gboolean fd_is_journal = FALSE;
2218 if (output_fd < 0)
2219 return FALSE;
2221 if (g_once_init_enter (&initialized))
2223 union {
2224 struct sockaddr_storage storage;
2225 struct sockaddr sa;
2226 struct sockaddr_un un;
2227 } addr;
2228 socklen_t addr_len = sizeof(addr);
2229 int err = getpeername (output_fd, &addr.sa, &addr_len);
2230 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2231 fd_is_journal = g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2233 g_once_init_leave (&initialized, TRUE);
2236 return fd_is_journal;
2237 #else
2238 return FALSE;
2239 #endif
2242 static void escape_string (GString *string);
2245 * g_log_writer_format_fields:
2246 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2247 * level
2248 * @fields: (array length=n_fields): key–value pairs of structured data forming
2249 * the log message
2250 * @n_fields: number of elements in the @fields array
2251 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2252 * message, %FALSE to not
2254 * Format a structured log message as a string suitable for outputting to the
2255 * terminal (or elsewhere). This will include the values of all fields it knows
2256 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2257 * documentation for g_log_structured()). It does not include values from
2258 * unknown fields.
2260 * The returned string does **not** have a trailing new-line character. It is
2261 * encoded in the character set of the current locale, which is not necessarily
2262 * UTF-8.
2264 * Returns: (transfer full): string containing the formatted log message, in
2265 * the character set of the current locale
2266 * Since: 2.50
2268 gchar *
2269 g_log_writer_format_fields (GLogLevelFlags log_level,
2270 const GLogField *fields,
2271 gsize n_fields,
2272 gboolean use_color)
2274 gsize i;
2275 const gchar *message = NULL;
2276 const gchar *log_domain = NULL;
2277 gchar level_prefix[STRING_BUFFER_SIZE];
2278 GString *gstring;
2279 gint64 now;
2280 time_t now_secs;
2281 struct tm *now_tm;
2282 gchar time_buf[128];
2284 /* Extract some common fields. */
2285 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2287 const GLogField *field = &fields[i];
2289 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2290 message = field->value;
2291 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2292 log_domain = field->value;
2295 /* Format things. */
2296 mklevel_prefix (level_prefix, log_level, use_color);
2298 gstring = g_string_new (NULL);
2299 if (log_level & ALERT_LEVELS)
2300 g_string_append (gstring, "\n");
2301 if (!log_domain)
2302 g_string_append (gstring, "** ");
2304 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2305 (log_level & G_LOG_LEVEL_MASK))
2307 const gchar *prg_name = g_get_prgname ();
2308 gulong pid = getpid ();
2310 if (prg_name == NULL)
2311 g_string_append_printf (gstring, "(process:%lu): ", pid);
2312 else
2313 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2316 if (log_domain != NULL)
2318 g_string_append (gstring, log_domain);
2319 g_string_append_c (gstring, '-');
2321 g_string_append (gstring, level_prefix);
2323 g_string_append (gstring, ": ");
2325 /* Timestamp */
2326 now = g_get_real_time ();
2327 now_secs = (time_t) (now / 1000000);
2328 now_tm = localtime (&now_secs);
2329 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2331 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2332 use_color ? "\033[34m" : "",
2333 time_buf, (gint) ((now / 1000) % 1000),
2334 color_reset (use_color));
2336 if (message == NULL)
2338 g_string_append (gstring, "(NULL) message");
2340 else
2342 GString *msg;
2343 const gchar *charset;
2345 msg = g_string_new (message);
2346 escape_string (msg);
2348 if (g_get_charset (&charset))
2350 /* charset is UTF-8 already */
2351 g_string_append (gstring, msg->str);
2353 else
2355 gchar *lstring = strdup_convert (msg->str, charset);
2356 g_string_append (gstring, lstring);
2357 g_free (lstring);
2360 g_string_free (msg, TRUE);
2363 return g_string_free (gstring, FALSE);
2366 /* Enable support for the journal if we're on a recent enough Linux */
2367 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2368 #define ENABLE_JOURNAL_SENDV
2369 #endif
2371 #ifdef ENABLE_JOURNAL_SENDV
2372 static int
2373 journal_sendv (struct iovec *iov,
2374 gsize iovlen)
2376 int buf_fd = -1;
2377 struct msghdr mh;
2378 struct sockaddr_un sa;
2379 union {
2380 struct cmsghdr cmsghdr;
2381 guint8 buf[CMSG_SPACE(sizeof(int))];
2382 } control;
2383 struct cmsghdr *cmsg;
2384 char path[] = "/dev/shm/journal.XXXXXX";
2386 if (journal_fd < 0)
2387 open_journal ();
2389 if (journal_fd < 0)
2390 return -1;
2392 memset (&sa, 0, sizeof (sa));
2393 sa.sun_family = AF_UNIX;
2394 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2395 return -1;
2397 memset (&mh, 0, sizeof (mh));
2398 mh.msg_name = &sa;
2399 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2400 mh.msg_iov = iov;
2401 mh.msg_iovlen = iovlen;
2403 retry:
2404 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2405 return 0;
2407 if (errno == EINTR)
2408 goto retry;
2410 if (errno != EMSGSIZE && errno != ENOBUFS)
2411 return -1;
2413 /* Message was too large, so dump to temporary file
2414 * and pass an FD to the journal
2416 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2417 return -1;
2419 if (unlink (path) < 0)
2421 close (buf_fd);
2422 return -1;
2425 if (writev (buf_fd, iov, iovlen) < 0)
2427 close (buf_fd);
2428 return -1;
2431 mh.msg_iov = NULL;
2432 mh.msg_iovlen = 0;
2434 memset (&control, 0, sizeof (control));
2435 mh.msg_control = &control;
2436 mh.msg_controllen = sizeof (control);
2438 cmsg = CMSG_FIRSTHDR (&mh);
2439 cmsg->cmsg_level = SOL_SOCKET;
2440 cmsg->cmsg_type = SCM_RIGHTS;
2441 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2442 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2444 mh.msg_controllen = cmsg->cmsg_len;
2446 retry2:
2447 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2448 return 0;
2450 if (errno == EINTR)
2451 goto retry2;
2453 return -1;
2455 #endif /* ENABLE_JOURNAL_SENDV */
2458 * g_log_writer_journald:
2459 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2460 * level
2461 * @fields: (array length=n_fields): key–value pairs of structured data forming
2462 * the log message
2463 * @n_fields: number of elements in the @fields array
2464 * @user_data: user data passed to g_log_set_writer_func()
2466 * Format a structured log message and send it to the systemd journal as a set
2467 * of key–value pairs. All fields are sent to the journal, but if a field has
2468 * length zero (indicating program-specific data) then only its key will be
2469 * sent.
2471 * This is suitable for use as a #GLogWriterFunc.
2473 * If GLib has been compiled without systemd support, this function is still
2474 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2476 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2477 * Since: 2.50
2479 GLogWriterOutput
2480 g_log_writer_journald (GLogLevelFlags log_level,
2481 const GLogField *fields,
2482 gsize n_fields,
2483 gpointer user_data)
2485 #ifdef ENABLE_JOURNAL_SENDV
2486 const char equals = '=';
2487 const char newline = '\n';
2488 gsize i, k;
2489 struct iovec *iov, *v;
2490 char *buf;
2491 gint retval;
2493 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2494 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2496 /* According to systemd.journal-fields(7), the journal allows fields in any
2497 * format (including arbitrary binary), but expects text fields to be UTF-8.
2498 * This is great, because we require input strings to be in UTF-8, so no
2499 * conversion is necessary and we don’t need to care about the current
2500 * locale’s character set.
2503 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2504 buf = g_alloca (32 * n_fields);
2506 k = 0;
2507 v = iov;
2508 for (i = 0; i < n_fields; i++)
2510 guint64 length;
2511 gboolean binary;
2513 if (fields[i].length < 0)
2515 length = strlen (fields[i].value);
2516 binary = strchr (fields[i].value, '\n') != NULL;
2518 else
2520 length = fields[i].length;
2521 binary = TRUE;
2524 if (binary)
2526 guint64 nstr;
2528 v[0].iov_base = (gpointer)fields[i].key;
2529 v[0].iov_len = strlen (fields[i].key);
2531 v[1].iov_base = (gpointer)&newline;
2532 v[1].iov_len = 1;
2534 nstr = GUINT64_TO_LE(length);
2535 memcpy (&buf[k], &nstr, sizeof (nstr));
2537 v[2].iov_base = &buf[k];
2538 v[2].iov_len = sizeof (nstr);
2539 v += 3;
2540 k += sizeof (nstr);
2542 else
2544 v[0].iov_base = (gpointer)fields[i].key;
2545 v[0].iov_len = strlen (fields[i].key);
2547 v[1].iov_base = (gpointer)&equals;
2548 v[1].iov_len = 1;
2549 v += 2;
2552 v[0].iov_base = (gpointer)fields[i].value;
2553 v[0].iov_len = length;
2555 v[1].iov_base = (gpointer)&newline;
2556 v[1].iov_len = 1;
2557 v += 2;
2560 retval = journal_sendv (iov, v - iov);
2562 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2563 #else
2564 return G_LOG_WRITER_UNHANDLED;
2565 #endif /* ENABLE_JOURNAL_SENDV */
2569 * g_log_writer_standard_streams:
2570 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2571 * level
2572 * @fields: (array length=n_fields): key–value pairs of structured data forming
2573 * the log message
2574 * @n_fields: number of elements in the @fields array
2575 * @user_data: user data passed to g_log_set_writer_func()
2577 * Format a structured log message and print it to either `stdout` or `stderr`,
2578 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2579 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2580 * which are understood by this function are included in the formatted string
2581 * which is printed.
2583 * If the output stream supports ANSI color escape sequences, they will be used
2584 * in the output.
2586 * A trailing new-line character is added to the log message when it is printed.
2588 * This is suitable for use as a #GLogWriterFunc.
2590 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2591 * Since: 2.50
2593 GLogWriterOutput
2594 g_log_writer_standard_streams (GLogLevelFlags log_level,
2595 const GLogField *fields,
2596 gsize n_fields,
2597 gpointer user_data)
2599 FILE *stream;
2600 gchar *out = NULL; /* in the current locale’s character set */
2602 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2603 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2605 stream = log_level_to_file (log_level);
2606 if (!stream || fileno (stream) < 0)
2607 return G_LOG_WRITER_UNHANDLED;
2609 out = g_log_writer_format_fields (log_level, fields, n_fields,
2610 g_log_writer_supports_color (fileno (stream)));
2611 _g_fprintf (stream, "%s\n", out);
2612 fflush (stream);
2613 g_free (out);
2615 return G_LOG_WRITER_HANDLED;
2618 /* The old g_log() API is implemented in terms of the new structured log API.
2619 * However, some of the checks do not line up between the two APIs: the
2620 * structured API only handles fatalness of messages for log levels; the old API
2621 * handles it per-domain as well. Consequently, we need to disable fatalness
2622 * handling in the structured log API when called from the old g_log() API.
2624 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2625 * the first field to g_log_structured_array(), if that is the case.
2627 static gboolean
2628 log_is_old_api (const GLogField *fields,
2629 gsize n_fields)
2631 return (n_fields >= 1 &&
2632 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2633 g_strcmp0 (fields[0].value, "1") == 0);
2637 * g_log_writer_default:
2638 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2639 * level
2640 * @fields: (array length=n_fields): key–value pairs of structured data forming
2641 * the log message
2642 * @n_fields: number of elements in the @fields array
2643 * @user_data: user data passed to g_log_set_writer_func()
2645 * Format a structured log message and output it to the default log destination
2646 * for the platform. On Linux, this is typically the systemd journal, falling
2647 * back to `stdout` or `stderr` if running from the terminal or if output is
2648 * being redirected to a file.
2650 * Support for other platform-specific logging mechanisms may be added in
2651 * future. Distributors of GLib may modify this function to impose their own
2652 * (documented) platform-specific log writing policies.
2654 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2655 * if no other is set using g_log_set_writer_func().
2657 * As with g_log_default_handler(), this function drops debug and informational
2658 * messages unless their log domain (or `all`) is listed in the space-separated
2659 * `G_MESSAGES_DEBUG` environment variable.
2661 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2662 * Since: 2.50
2664 GLogWriterOutput
2665 g_log_writer_default (GLogLevelFlags log_level,
2666 const GLogField *fields,
2667 gsize n_fields,
2668 gpointer user_data)
2670 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2671 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2673 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2674 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2676 const gchar *domains, *log_domain = NULL;
2677 gsize i;
2679 domains = g_getenv ("G_MESSAGES_DEBUG");
2681 if ((log_level & INFO_LEVELS) == 0 ||
2682 domains == NULL)
2683 return G_LOG_WRITER_HANDLED;
2685 for (i = 0; i < n_fields; i++)
2687 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2689 log_domain = fields[i].value;
2690 break;
2694 if (strcmp (domains, "all") != 0 &&
2695 (log_domain == NULL || !strstr (domains, log_domain)))
2696 return G_LOG_WRITER_HANDLED;
2699 /* Mark messages as fatal if they have a level set in
2700 * g_log_set_always_fatal().
2702 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2703 log_level |= G_LOG_FLAG_FATAL;
2705 /* Try logging to the systemd journal as first choice. */
2706 if (g_log_writer_is_journald (fileno (stderr)) &&
2707 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2708 G_LOG_WRITER_HANDLED)
2709 goto handled;
2711 /* FIXME: Add support for the Windows log. */
2713 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2714 G_LOG_WRITER_HANDLED)
2715 goto handled;
2717 return G_LOG_WRITER_UNHANDLED;
2719 handled:
2720 /* Abort if the message was fatal. */
2721 if (log_level & G_LOG_FLAG_FATAL)
2723 #ifdef G_OS_WIN32
2724 if (!g_test_initialized ())
2726 gchar *locale_msg = NULL;
2728 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2729 MessageBox (NULL, locale_msg, NULL,
2730 MB_ICONERROR | MB_SETFOREGROUND);
2731 g_free (locale_msg);
2733 #endif /* !G_OS_WIN32 */
2735 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2738 return G_LOG_WRITER_HANDLED;
2741 static GLogWriterOutput
2742 _g_log_writer_fallback (GLogLevelFlags log_level,
2743 const GLogField *fields,
2744 gsize n_fields,
2745 gpointer user_data)
2747 FILE *stream;
2748 gsize i;
2750 /* we cannot call _any_ GLib functions in this fallback handler,
2751 * which is why we skip UTF-8 conversion, etc.
2752 * since we either recursed or ran out of memory, we're in a pretty
2753 * pathologic situation anyways, what we can do is giving the
2754 * the process ID unconditionally however.
2757 stream = log_level_to_file (log_level);
2759 for (i = 0; i < n_fields; i++)
2761 const GLogField *field = &fields[i];
2763 /* Only print fields we definitely recognise, otherwise we could end up
2764 * printing a random non-string pointer provided by the user to be
2765 * interpreted by their writer function.
2767 if (strcmp (field->key, "MESSAGE") != 0 &&
2768 strcmp (field->key, "MESSAGE_ID") != 0 &&
2769 strcmp (field->key, "PRIORITY") != 0 &&
2770 strcmp (field->key, "CODE_FILE") != 0 &&
2771 strcmp (field->key, "CODE_LINE") != 0 &&
2772 strcmp (field->key, "CODE_FUNC") != 0 &&
2773 strcmp (field->key, "ERRNO") != 0 &&
2774 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2775 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2776 strcmp (field->key, "SYSLOG_PID") != 0 &&
2777 strcmp (field->key, "GLIB_DOMAIN") != 0)
2778 continue;
2780 write_string (stream, field->key);
2781 write_string (stream, "=");
2782 write_string_sized (stream, field->value, field->length);
2785 #ifndef G_OS_WIN32
2787 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2789 format_unsigned (pid_string, getpid (), 10);
2790 write_string (stream, "_PID=");
2791 write_string (stream, pid_string);
2793 #endif
2795 return G_LOG_WRITER_HANDLED;
2799 * g_return_if_fail_warning: (skip)
2800 * @log_domain: (nullable):
2801 * @pretty_function:
2802 * @expression: (nullable):
2804 void
2805 g_return_if_fail_warning (const char *log_domain,
2806 const char *pretty_function,
2807 const char *expression)
2809 g_log (log_domain,
2810 G_LOG_LEVEL_CRITICAL,
2811 "%s: assertion '%s' failed",
2812 pretty_function,
2813 expression);
2817 * g_warn_message: (skip)
2818 * @domain: (nullable):
2819 * @file:
2820 * @line:
2821 * @func:
2822 * @warnexpr: (nullable):
2824 void
2825 g_warn_message (const char *domain,
2826 const char *file,
2827 int line,
2828 const char *func,
2829 const char *warnexpr)
2831 char *s, lstr[32];
2832 g_snprintf (lstr, 32, "%d", line);
2833 if (warnexpr)
2834 s = g_strconcat ("(", file, ":", lstr, "):",
2835 func, func[0] ? ":" : "",
2836 " runtime check failed: (", warnexpr, ")", NULL);
2837 else
2838 s = g_strconcat ("(", file, ":", lstr, "):",
2839 func, func[0] ? ":" : "",
2840 " ", "code should not be reached", NULL);
2841 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2842 g_free (s);
2845 void
2846 g_assert_warning (const char *log_domain,
2847 const char *file,
2848 const int line,
2849 const char *pretty_function,
2850 const char *expression)
2852 if (expression)
2853 g_log (log_domain,
2854 G_LOG_LEVEL_ERROR,
2855 "file %s: line %d (%s): assertion failed: (%s)",
2856 file,
2857 line,
2858 pretty_function,
2859 expression);
2860 else
2861 g_log (log_domain,
2862 G_LOG_LEVEL_ERROR,
2863 "file %s: line %d (%s): should not be reached",
2864 file,
2865 line,
2866 pretty_function);
2867 _g_log_abort (FALSE);
2868 g_abort ();
2872 * g_test_expect_message:
2873 * @log_domain: (nullable): the log domain of the message
2874 * @log_level: the log level of the message
2875 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2877 * Indicates that a message with the given @log_domain and @log_level,
2878 * with text matching @pattern, is expected to be logged. When this
2879 * message is logged, it will not be printed, and the test case will
2880 * not abort.
2882 * This API may only be used with the old logging API (g_log() without
2883 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2884 * API. See [Testing for Messages][testing-for-messages].
2886 * Use g_test_assert_expected_messages() to assert that all
2887 * previously-expected messages have been seen and suppressed.
2889 * You can call this multiple times in a row, if multiple messages are
2890 * expected as a result of a single call. (The messages must appear in
2891 * the same order as the calls to g_test_expect_message().)
2893 * For example:
2895 * |[<!-- language="C" -->
2896 * // g_main_context_push_thread_default() should fail if the
2897 * // context is already owned by another thread.
2898 * g_test_expect_message (G_LOG_DOMAIN,
2899 * G_LOG_LEVEL_CRITICAL,
2900 * "assertion*acquired_context*failed");
2901 * g_main_context_push_thread_default (bad_context);
2902 * g_test_assert_expected_messages ();
2903 * ]|
2905 * Note that you cannot use this to test g_error() messages, since
2906 * g_error() intentionally never returns even if the program doesn't
2907 * abort; use g_test_trap_subprocess() in this case.
2909 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2910 * expected via g_test_expect_message() then they will be ignored.
2912 * Since: 2.34
2914 void
2915 g_test_expect_message (const gchar *log_domain,
2916 GLogLevelFlags log_level,
2917 const gchar *pattern)
2919 GTestExpectedMessage *expected;
2921 g_return_if_fail (log_level != 0);
2922 g_return_if_fail (pattern != NULL);
2923 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2925 expected = g_new (GTestExpectedMessage, 1);
2926 expected->log_domain = g_strdup (log_domain);
2927 expected->log_level = log_level;
2928 expected->pattern = g_strdup (pattern);
2930 expected_messages = g_slist_append (expected_messages, expected);
2933 void
2934 g_test_assert_expected_messages_internal (const char *domain,
2935 const char *file,
2936 int line,
2937 const char *func)
2939 if (expected_messages)
2941 GTestExpectedMessage *expected;
2942 gchar level_prefix[STRING_BUFFER_SIZE];
2943 gchar *message;
2945 expected = expected_messages->data;
2947 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2948 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2949 expected->log_domain ? expected->log_domain : "**",
2950 level_prefix, expected->pattern);
2951 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2952 g_free (message);
2957 * g_test_assert_expected_messages:
2959 * Asserts that all messages previously indicated via
2960 * g_test_expect_message() have been seen and suppressed.
2962 * This API may only be used with the old logging API (g_log() without
2963 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2964 * API. See [Testing for Messages][testing-for-messages].
2966 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2967 * expected via g_test_expect_message() then they will be ignored.
2969 * Since: 2.34
2972 void
2973 _g_log_fallback_handler (const gchar *log_domain,
2974 GLogLevelFlags log_level,
2975 const gchar *message,
2976 gpointer unused_data)
2978 gchar level_prefix[STRING_BUFFER_SIZE];
2979 #ifndef G_OS_WIN32
2980 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2981 #endif
2982 FILE *stream;
2984 /* we cannot call _any_ GLib functions in this fallback handler,
2985 * which is why we skip UTF-8 conversion, etc.
2986 * since we either recursed or ran out of memory, we're in a pretty
2987 * pathologic situation anyways, what we can do is giving the
2988 * the process ID unconditionally however.
2991 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2992 if (!message)
2993 message = "(NULL) message";
2995 #ifndef G_OS_WIN32
2996 format_unsigned (pid_string, getpid (), 10);
2997 #endif
2999 if (log_domain)
3000 write_string (stream, "\n");
3001 else
3002 write_string (stream, "\n** ");
3004 #ifndef G_OS_WIN32
3005 write_string (stream, "(process:");
3006 write_string (stream, pid_string);
3007 write_string (stream, "): ");
3008 #endif
3010 if (log_domain)
3012 write_string (stream, log_domain);
3013 write_string (stream, "-");
3015 write_string (stream, level_prefix);
3016 write_string (stream, ": ");
3017 write_string (stream, message);
3020 static void
3021 escape_string (GString *string)
3023 const char *p = string->str;
3024 gunichar wc;
3026 while (p < string->str + string->len)
3028 gboolean safe;
3030 wc = g_utf8_get_char_validated (p, -1);
3031 if (wc == (gunichar)-1 || wc == (gunichar)-2)
3033 gchar *tmp;
3034 guint pos;
3036 pos = p - string->str;
3038 /* Emit invalid UTF-8 as hex escapes
3040 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
3041 g_string_erase (string, pos, 1);
3042 g_string_insert (string, pos, tmp);
3044 p = string->str + (pos + 4); /* Skip over escape sequence */
3046 g_free (tmp);
3047 continue;
3049 if (wc == '\r')
3051 safe = *(p + 1) == '\n';
3053 else
3055 safe = CHAR_IS_SAFE (wc);
3058 if (!safe)
3060 gchar *tmp;
3061 guint pos;
3063 pos = p - string->str;
3065 /* Largest char we escape is 0x0a, so we don't have to worry
3066 * about 8-digit \Uxxxxyyyy
3068 tmp = g_strdup_printf ("\\u%04x", wc);
3069 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3070 g_string_insert (string, pos, tmp);
3071 g_free (tmp);
3073 p = string->str + (pos + 6); /* Skip over escape sequence */
3075 else
3076 p = g_utf8_next_char (p);
3081 * g_log_default_handler:
3082 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3083 * default "" application domain
3084 * @log_level: the level of the message
3085 * @message: (nullable): the message
3086 * @unused_data: (nullable): data passed from g_log() which is unused
3088 * The default log handler set up by GLib; g_log_set_default_handler()
3089 * allows to install an alternate default log handler.
3090 * This is used if no log handler has been set for the particular log
3091 * domain and log level combination. It outputs the message to stderr
3092 * or stdout and if the log level is fatal it calls abort(). It automatically
3093 * prints a new-line character after the message, so one does not need to be
3094 * manually included in @message.
3096 * The behavior of this log handler can be influenced by a number of
3097 * environment variables:
3099 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3100 * messages should be prefixed by the program name and PID of the
3101 * aplication.
3103 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3104 * which debug and informational messages are printed. By default
3105 * these messages are not printed.
3107 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3108 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3109 * the rest.
3111 * This has no effect if structured logging is enabled; see
3112 * [Using Structured Logging][using-structured-logging].
3114 void
3115 g_log_default_handler (const gchar *log_domain,
3116 GLogLevelFlags log_level,
3117 const gchar *message,
3118 gpointer unused_data)
3120 GLogField fields[4];
3121 int n_fields = 0;
3123 /* we can be called externally with recursion for whatever reason */
3124 if (log_level & G_LOG_FLAG_RECURSION)
3126 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3127 return;
3130 fields[0].key = "GLIB_OLD_LOG_API";
3131 fields[0].value = "1";
3132 fields[0].length = -1;
3133 n_fields++;
3135 fields[1].key = "MESSAGE";
3136 fields[1].value = message;
3137 fields[1].length = -1;
3138 n_fields++;
3140 fields[2].key = "PRIORITY";
3141 fields[2].value = log_level_to_priority (log_level);
3142 fields[2].length = -1;
3143 n_fields++;
3145 if (log_domain)
3147 fields[3].key = "GLIB_DOMAIN";
3148 fields[3].value = log_domain;
3149 fields[3].length = -1;
3150 n_fields++;
3153 /* Print out via the structured log API, but drop any fatal flags since we
3154 * have already handled them. The fatal handling in the structured logging
3155 * API is more coarse-grained than in the old g_log() API, so we don't want
3156 * to use it here.
3158 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3162 * g_set_print_handler:
3163 * @func: the new print handler
3165 * Sets the print handler.
3167 * Any messages passed to g_print() will be output via
3168 * the new handler. The default handler simply outputs
3169 * the message to stdout. By providing your own handler
3170 * you can redirect the output, to a GTK+ widget or a
3171 * log file for example.
3173 * Returns: the old print handler
3175 GPrintFunc
3176 g_set_print_handler (GPrintFunc func)
3178 GPrintFunc old_print_func;
3180 g_mutex_lock (&g_messages_lock);
3181 old_print_func = glib_print_func;
3182 glib_print_func = func;
3183 g_mutex_unlock (&g_messages_lock);
3185 return old_print_func;
3189 * g_print:
3190 * @format: the message format. See the printf() documentation
3191 * @...: the parameters to insert into the format string
3193 * Outputs a formatted message via the print handler.
3194 * The default print handler simply outputs the message to stdout, without
3195 * appending a trailing new-line character. Typically, @format should end with
3196 * its own new-line character.
3198 * g_print() should not be used from within libraries for debugging
3199 * messages, since it may be redirected by applications to special
3200 * purpose message windows or even files. Instead, libraries should
3201 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3202 * g_warning() and g_error().
3204 void
3205 g_print (const gchar *format,
3206 ...)
3208 va_list args;
3209 gchar *string;
3210 GPrintFunc local_glib_print_func;
3212 g_return_if_fail (format != NULL);
3214 va_start (args, format);
3215 string = g_strdup_vprintf (format, args);
3216 va_end (args);
3218 g_mutex_lock (&g_messages_lock);
3219 local_glib_print_func = glib_print_func;
3220 g_mutex_unlock (&g_messages_lock);
3222 if (local_glib_print_func)
3223 local_glib_print_func (string);
3224 else
3226 const gchar *charset;
3228 if (g_get_charset (&charset))
3229 fputs (string, stdout); /* charset is UTF-8 already */
3230 else
3232 gchar *lstring = strdup_convert (string, charset);
3234 fputs (lstring, stdout);
3235 g_free (lstring);
3237 fflush (stdout);
3239 g_free (string);
3243 * g_set_printerr_handler:
3244 * @func: the new error message handler
3246 * Sets the handler for printing error messages.
3248 * Any messages passed to g_printerr() will be output via
3249 * the new handler. The default handler simply outputs the
3250 * message to stderr. By providing your own handler you can
3251 * redirect the output, to a GTK+ widget or a log file for
3252 * example.
3254 * Returns: the old error message handler
3256 GPrintFunc
3257 g_set_printerr_handler (GPrintFunc func)
3259 GPrintFunc old_printerr_func;
3261 g_mutex_lock (&g_messages_lock);
3262 old_printerr_func = glib_printerr_func;
3263 glib_printerr_func = func;
3264 g_mutex_unlock (&g_messages_lock);
3266 return old_printerr_func;
3270 * g_printerr:
3271 * @format: the message format. See the printf() documentation
3272 * @...: the parameters to insert into the format string
3274 * Outputs a formatted message via the error message handler.
3275 * The default handler simply outputs the message to stderr, without appending
3276 * a trailing new-line character. Typically, @format should end with its own
3277 * new-line character.
3279 * g_printerr() should not be used from within libraries.
3280 * Instead g_log() or g_log_structured() should be used, or the convenience
3281 * macros g_message(), g_warning() and g_error().
3283 void
3284 g_printerr (const gchar *format,
3285 ...)
3287 va_list args;
3288 gchar *string;
3289 GPrintFunc local_glib_printerr_func;
3291 g_return_if_fail (format != NULL);
3293 va_start (args, format);
3294 string = g_strdup_vprintf (format, args);
3295 va_end (args);
3297 g_mutex_lock (&g_messages_lock);
3298 local_glib_printerr_func = glib_printerr_func;
3299 g_mutex_unlock (&g_messages_lock);
3301 if (local_glib_printerr_func)
3302 local_glib_printerr_func (string);
3303 else
3305 const gchar *charset;
3307 if (g_get_charset (&charset))
3308 fputs (string, stderr); /* charset is UTF-8 already */
3309 else
3311 gchar *lstring = strdup_convert (string, charset);
3313 fputs (lstring, stderr);
3314 g_free (lstring);
3316 fflush (stderr);
3318 g_free (string);
3322 * g_printf_string_upper_bound:
3323 * @format: the format string. See the printf() documentation
3324 * @args: the parameters to be inserted into the format string
3326 * Calculates the maximum space needed to store the output
3327 * of the sprintf() function.
3329 * Returns: the maximum space needed to store the formatted string
3331 gsize
3332 g_printf_string_upper_bound (const gchar *format,
3333 va_list args)
3335 gchar c;
3336 return _g_vsnprintf (&c, 1, format, args) + 1;