gmessages.c 105 KB
Newer Older
Owen Taylor's avatar
Owen Taylor committed
1
2
3
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
4
5
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
Owen Taylor's avatar
Owen Taylor committed
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
Owen Taylor's avatar
Owen Taylor committed
10
11
12
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
14
 * Lesser General Public License for more details.
Owen Taylor's avatar
Owen Taylor committed
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
Owen Taylor's avatar
Owen Taylor committed
18
 */
19

20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22
23
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25
26
 */

27
/*
28
29
30
 * MT safe
 */

31
/**
32
 * SECTION:messages
33
34
35
36
37
 * @Title: Message Output and Debugging Functions
 * @Short_description: functions to output messages and help debug applications
 *
 * These functions provide support for outputting messages.
 *
Matthias Clasen's avatar
Matthias Clasen committed
38
 * The g_return family of macros (g_return_if_fail(),
39
40
41
42
43
44
45
46
47
 * g_return_val_if_fail(), g_return_if_reached(),
 * g_return_val_if_reached()) should only be used for programming
 * errors, a typical use case is checking for invalid parameters at
 * the beginning of a public function. They should not be used if
 * you just mean "if (error) return", they should only be used if
 * you mean "if (bug in program) return". The program behavior is
 * generally considered undefined after one of these checks fails.
 * They are not intended for normal control flow, only to give a
 * perhaps-helpful warning before giving up.
48
49
50
51
52
53
54
 *
 * Structured logging output is supported using g_log_structured(). This differs
 * from the traditional g_log() API in that log messages are handled as a
 * collection of key–value pairs representing individual pieces of information,
 * rather than as a single string containing all the information in an arbitrary
 * format.
 *
55
56
 * The convenience macros g_info(), g_message(), g_debug(), g_warning() and g_error()
 * will use the traditional g_log() API unless you define the symbol
57
 * %G_LOG_USE_STRUCTURED before including `glib.h`. But note that even messages
58
59
 * logged through the traditional g_log() API are ultimatively passed to
 * g_log_structured(), so that all log messages end up in same destination.
60
61
 * If %G_LOG_USE_STRUCTURED is defined, g_test_expect_message() will become
 * ineffective for the wrapper macros g_warning() and friends (see
62
 * [Testing for Messages][testing-for-messages]).
63
 *
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 * The support for structured logging was motivated by the following needs (some
 * of which were supported previously; others weren’t):
 *  * Support for multiple logging levels.
 *  * Structured log support with the ability to add `MESSAGE_ID`s (see
 *    g_log_structured()).
 *  * Moving the responsibility for filtering log messages from the program to
 *    the log viewer — instead of libraries and programs installing log handlers
 *    (with g_log_set_handler()) which filter messages before output, all log
 *    messages are outputted, and the log viewer program (such as `journalctl`)
 *    must filter them. This is based on the idea that bugs are sometimes hard
 *    to reproduce, so it is better to log everything possible and then use
 *    tools to analyse the logs than it is to not be able to reproduce a bug to
 *    get additional log data. Code which uses logging in performance-critical
 *    sections should compile out the g_log_structured() calls in
 *    release builds, and compile them in in debugging builds.
 *  * A single writer function which handles all log messages in a process, from
 *    all libraries and program code; rather than multiple log handlers with
 *    poorly defined interactions between them. This allows a program to easily
 *    change its logging policy by changing the writer function, for example to
 *    log to an additional location or to change what logging output fallbacks
 *    are used. The log writer functions provided by GLib are exposed publicly
 *    so they can be used from programs’ log writers. This allows log writer
 *    policy and implementation to be kept separate.
 *  * If a library wants to add standard information to all of its log messages
 *    (such as library state) or to redact private data (such as passwords or
 *    network credentials), it should use a wrapper function around its
 *    g_log_structured() calls or implement that in the single log writer
 *    function.
 *  * If a program wants to pass context data from a g_log_structured() call to
 *    its log writer function so that, for example, it can use the correct
 *    server connection to submit logs to, that user data can be passed as a
 *    zero-length #GLogField to g_log_structured_array().
96
 *  * Color output needed to be supported on the terminal, to make reading
97
 *    through logs easier.
98
 *
99
 * ## Using Structured Logging ## {#using-structured-logging}
100
101
102
103
104
105
106
107
108
 *
 * To use structured logging (rather than the old-style logging), either use
 * the g_log_structured() and g_log_structured_array() functions; or define
 * `G_LOG_USE_STRUCTURED` before including any GLib header, and use the
 * g_message(), g_debug(), g_error() (etc.) macros.
 *
 * You do not need to define `G_LOG_USE_STRUCTURED` to use g_log_structured(),
 * but it is a good idea to avoid confusion.
 *
109
 * ## Log Domains ## {#log-domains}
110
111
112
113
114
115
116
117
118
119
120
 *
 * Log domains may be used to broadly split up the origins of log messages.
 * Typically, there are one or a few log domains per application or library.
 * %G_LOG_DOMAIN should be used to define the default log domain for the current
 * compilation unit — it is typically defined at the top of a source file, or in
 * the preprocessor flags for a group of source files.
 *
 * Log domains must be unique, and it is recommended that they are the
 * application or library name, optionally followed by a hyphen and a sub-domain
 * name. For example, `bloatpad` or `bloatpad-io`.
 *
121
 * ## Debug Message Output ## {#debug-message-output}
122
123
124
125
126
127
128
129
130
131
 *
 * The default log functions (g_log_default_handler() for the old-style API and
 * g_log_writer_default() for the structured API) both drop debug and
 * informational messages by default, unless the log domains of those messages
 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
 * `all`).
 *
 * It is recommended that custom log writer functions re-use the
 * `G_MESSAGES_DEBUG` environment variable, rather than inventing a custom one,
 * so that developers can re-use the same debugging techniques and tools across
132
133
 * projects. Since GLib 2.68, this can be implemented by dropping messages
 * for which g_log_writer_default_would_drop() returns %TRUE.
134
 *
135
 * ## Testing for Messages ## {#testing-for-messages}
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
 *
 * With the old g_log() API, g_test_expect_message() and
 * g_test_assert_expected_messages() could be used in simple cases to check
 * whether some code under test had emitted a given log message. These
 * functions have been deprecated with the structured logging API, for several
 * reasons:
 *  * They relied on an internal queue which was too inflexible for many use
 *    cases, where messages might be emitted in several orders, some
 *    messages might not be emitted deterministically, or messages might be
 *    emitted by unrelated log domains.
 *  * They do not support structured log fields.
 *  * Examining the log output of code is a bad approach to testing it, and
 *    while it might be necessary for legacy code which uses g_log(), it should
 *    be avoided for new code using g_log_structured().
 *
 * They will continue to work as before if g_log() is in use (and
 * %G_LOG_USE_STRUCTURED is not defined). They will do nothing if used with the
 * structured logging API.
 *
 * Examining the log output of code is discouraged: libraries should not emit to
 * `stderr` during defined behaviour, and hence this should not be tested. If
 * the log emissions of a library during undefined behaviour need to be tested,
 * they should be limited to asserting that the library aborts and prints a
 * suitable error message before aborting. This should be done with
 * g_test_trap_assert_stderr().
 *
 * If it is really necessary to test the structured log messages emitted by a
 * particular piece of code – and the code cannot be restructured to be more
 * suitable to more conventional unit testing – you should write a custom log
 * writer function (see g_log_set_writer_func()) which appends all log messages
 * to a queue. When you want to check the log messages, examine and clear the
 * queue, ignoring irrelevant log messages (for example, from log domains other
 * than the one under test).
169
170
 */

171
#include "config.h"
172

173
#include <stdlib.h>
Owen Taylor's avatar
Owen Taylor committed
174
175
176
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
177
#include <signal.h>
178
179
#include <locale.h>
#include <errno.h>
180

181
#if defined(__linux__) && !defined(__BIONIC__)
Matthias Clasen's avatar
Matthias Clasen committed
182
183
184
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
Matthias Clasen's avatar
Matthias Clasen committed
185
186
#include <fcntl.h>
#include <sys/uio.h>
187
#endif
188

Matthias Clasen's avatar
Matthias Clasen committed
189
#include "glib-init.h"
190
#include "galloca.h"
191
#include "gbacktrace.h"
Matthias Clasen's avatar
Matthias Clasen committed
192
#include "gcharset.h"
193
#include "gconvert.h"
194
#include "genviron.h"
195
#include "gmain.h"
196
197
198
199
200
201
#include "gmem.h"
#include "gprintfint.h"
#include "gtestutils.h"
#include "gthread.h"
#include "gstrfuncs.h"
#include "gstring.h"
202
#include "gpattern.h"
203
#include "gthreadprivate.h"
204

205
206
207
208
#ifdef G_OS_UNIX
#include <unistd.h>
#endif

209
210
211
212
#ifdef G_OS_WIN32
#include <process.h>		/* For getpid() */
#include <io.h>
#  include <windows.h>
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif

#if defined (_MSC_VER) && (_MSC_VER >=1400)
/* This is ugly, but we need it for isatty() in case we have bad fd's,
 * otherwise Windows will abort() the program on msvcrt80.dll and later
 */
#include <crtdbg.h>

_GLIB_EXTERN void
myInvalidParameterHandler(const wchar_t *expression,
                          const wchar_t *function,
                          const wchar_t *file,
                          unsigned int   line,
                          uintptr_t      pReserved)
{
}
#endif

#include "gwin32.h"
235
236
#endif

Matthias Clasen's avatar
Matthias Clasen committed
237
238
239
/**
 * G_LOG_DOMAIN:
 *
240
 * Defines the log domain. See [Log Domains](#log-domains).
Matthias Clasen's avatar
Matthias Clasen committed
241
 *
242
 * Libraries should define this so that any messages
Matthias Clasen's avatar
Matthias Clasen committed
243
244
245
246
 * which they log can be differentiated from messages from other
 * libraries and application code. But be careful not to define
 * it in any public header files.
 *
247
248
249
250
251
252
253
254
255
 * Log domains must be unique, and it is recommended that they are the
 * application or library name, optionally followed by a hyphen and a sub-domain
 * name. For example, `bloatpad` or `bloatpad-io`.
 *
 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
 * environment variable.
 *
 * For example, GTK+ uses this in its `Makefile.am`:
Matthias Clasen's avatar
Matthias Clasen committed
256
 * |[
257
 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
Matthias Clasen's avatar
Matthias Clasen committed
258
 * ]|
259
 *
260
 * Applications can choose to leave it as the default %NULL (or `""`)
261
262
263
264
 * domain. However, defining the domain offers the same advantages as
 * above.
 *

Matthias Clasen's avatar
Matthias Clasen committed
265
266
267
268
269
270
 */

/**
 * G_LOG_FATAL_MASK:
 *
 * GLib log levels that are considered fatal by default.
271
272
273
 *
 * This is not used if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
274
275
276
277
278
279
280
281
282
283
284
 */

/**
 * GLogFunc:
 * @log_domain: the log domain of the message
 * @log_level: the log level of the message (including the
 *     fatal and recursion flags)
 * @message: the message to process
 * @user_data: user data, set in g_log_set_handler()
 *
 * Specifies the prototype of log handler functions.
285
286
287
288
289
290
 *
 * The default log handler, g_log_default_handler(), automatically appends a
 * new-line character to @message when printing it. It is advised that any
 * custom log handler functions behave similarly, so that logging calls in user
 * code do not need modifying to add a new-line character to the message if the
 * log handler is changed.
291
292
293
 *
 * This is not used if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
294
295
296
297
298
299
300
301
 */

/**
 * GLogLevelFlags:
 * @G_LOG_FLAG_RECURSION: internal flag
 * @G_LOG_FLAG_FATAL: internal flag
 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
 *     This level is also used for messages produced by g_assert().
302
303
 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
 *     g_critical().
Matthias Clasen's avatar
Matthias Clasen committed
304
305
306
307
 *     This level is also used for messages produced by g_return_if_fail()
 *     and g_return_val_if_fail().
 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
308
 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
Matthias Clasen's avatar
Matthias Clasen committed
309
310
311
312
313
314
315
316
317
 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
 * @G_LOG_LEVEL_MASK: a mask including all log levels
 *
 * Flags specifying the level of log messages.
 *
 * It is possible to change how GLib treats messages of the various
 * levels using g_log_set_handler() and g_log_set_fatal_mask().
 */

318
319
320
321
322
323
324
/**
 * G_LOG_LEVEL_USER_SHIFT:
 *
 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
 * Higher bits can be used for user-defined log levels.
 */

Matthias Clasen's avatar
Matthias Clasen committed
325
326
327
328
329
330
/**
 * g_message:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
 * A convenience function/macro to log a normal message.
331
332
333
334
 *
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.
335
336
337
338
 *
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
339
340
341
342
343
344
345
 */

/**
 * g_warning:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
346
347
 * A convenience function/macro to log a warning message. The message should
 * typically *not* be translated to the user's language.
Matthias Clasen's avatar
Matthias Clasen committed
348
 *
349
350
351
352
 * This is not intended for end user error reporting. Use of #GError is
 * preferred for that instead, as it allows calling functions to perform actions
 * conditional on the type of error.
 *
353
354
355
356
357
358
359
360
361
362
 * Warning messages are intended to be used in the event of unexpected
 * external conditions (system misconfiguration, missing files,
 * other trusted programs violating protocol, invalid contents in
 * trusted files, etc.)
 *
 * If attempting to deal with programmer errors (for example, incorrect function
 * parameters) then you should use %G_LOG_LEVEL_CRITICAL instead.
 *
 * g_warn_if_reached() and g_warn_if_fail() log at %G_LOG_LEVEL_WARNING.
 *
Matthias Clasen's avatar
Matthias Clasen committed
363
 * You can make warnings fatal at runtime by setting the `G_DEBUG`
364
 * environment variable (see
365
366
367
368
369
370
371
372
 * [Running GLib Applications](glib-running.html)):
 *
 * |[
 *   G_DEBUG=fatal-warnings gdb ./my-program
 * ]|
 *
 * Any unrelated failures can be skipped over in
 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
373
 *
Matthias Clasen's avatar
Matthias Clasen committed
374
375
376
 * If g_log_default_handler() is used as the log handler function,
 * a newline character will automatically be appended to @..., and
 * need not be entered manually.
377
378
379
380
 *
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
381
382
383
384
385
386
387
 */

/**
 * g_critical:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
388
 * Logs a "critical warning" (%G_LOG_LEVEL_CRITICAL).
Matthias Clasen's avatar
Matthias Clasen committed
389
 *
390
391
392
393
394
395
396
397
398
 * Critical warnings are intended to be used in the event of an error
 * that originated in the current process (a programmer error).
 * Logging of a critical error is by definition an indication of a bug
 * somewhere in the current program (or its libraries).
 *
 * g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and
 * g_return_val_if_reached() log at %G_LOG_LEVEL_CRITICAL.
 *
 * You can make critical warnings fatal at runtime by
Matthias Clasen's avatar
Matthias Clasen committed
399
 * setting the `G_DEBUG` environment variable (see
400
401
402
403
404
405
 * [Running GLib Applications](glib-running.html)):
 *
 * |[
 *   G_DEBUG=fatal-warnings gdb ./my-program
 * ]|
 *
406
407
 * You can also use g_log_set_always_fatal().
 *
408
409
 * Any unrelated failures can be skipped over in
 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
410
 *
411
412
413
 * The message should typically *not* be translated to the
 * user's language.
 *
414
415
416
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.
417
418
419
420
 *
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
421
422
423
424
425
426
427
 */

/**
 * g_error:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
428
429
 * A convenience function/macro to log an error message. The message should
 * typically *not* be translated to the user's language.
Matthias Clasen's avatar
Matthias Clasen committed
430
 *
431
432
433
434
 * This is not intended for end user error reporting. Use of #GError is
 * preferred for that instead, as it allows calling functions to perform actions
 * conditional on the type of error.
 *
435
436
 * Error messages are always fatal, resulting in a call to G_BREAKPOINT()
 * to terminate the application. This function will
Matthias Clasen's avatar
Matthias Clasen committed
437
438
439
440
 * result in a core dump; don't use it for errors you expect.
 * Using this function indicates a bug in your program, i.e.
 * an assertion failure.
 *
441
442
443
444
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.
 *
445
446
447
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
448
449
 */

450
451
452
453
454
455
456
457
458
459
460
/**
 * g_info:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
 * A convenience function/macro to log an informational message. Seldom used.
 *
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.
 *
461
462
463
 * Such messages are suppressed by the g_log_default_handler() and
 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
 * set appropriately.
464
 *
465
466
467
468
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
 *
469
470
471
 * Since: 2.40
 */

Matthias Clasen's avatar
Matthias Clasen committed
472
473
474
475
476
/**
 * g_debug:
 * @...: format string, followed by parameters to insert
 *     into the format string (as with printf())
 *
477
478
 * A convenience function/macro to log a debug message. The message should
 * typically *not* be translated to the user's language.
Matthias Clasen's avatar
Matthias Clasen committed
479
 *
480
481
482
483
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.
 *
484
485
486
 * Such messages are suppressed by the g_log_default_handler() and
 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
 * set appropriately.
487
 *
488
489
490
491
 * If structured logging is enabled, this will use g_log_structured();
 * otherwise it will use g_log(). See
 * [Using Structured Logging][using-structured-logging].
 *
Matthias Clasen's avatar
Matthias Clasen committed
492
493
494
 * Since: 2.6
 */

495
496
497
498
/* --- structures --- */
typedef struct _GLogDomain	GLogDomain;
typedef struct _GLogHandler	GLogHandler;
struct _GLogDomain
Owen Taylor's avatar
Owen Taylor committed
499
{
500
501
502
503
504
505
506
507
508
509
510
  gchar		*log_domain;
  GLogLevelFlags fatal_mask;
  GLogHandler	*handlers;
  GLogDomain	*next;
};
struct _GLogHandler
{
  guint		 id;
  GLogLevelFlags log_level;
  GLogFunc	 log_func;
  gpointer	 data;
Matthias Clasen's avatar
Matthias Clasen committed
511
  GDestroyNotify destroy;
512
513
514
515
516
  GLogHandler	*next;
};


/* --- variables --- */
Allison Karlitskaya's avatar
Allison Karlitskaya committed
517
static GMutex         g_messages_lock;
518
519
520
static GLogDomain    *g_log_domains = NULL;
static GPrintFunc     glib_print_func = NULL;
static GPrintFunc     glib_printerr_func = NULL;
Allison Karlitskaya's avatar
Allison Karlitskaya committed
521
static GPrivate       g_log_depth;
522
static GPrivate       g_log_structured_depth;
523
524
static GLogFunc       default_log_func = g_log_default_handler;
static gpointer       default_log_data = NULL;
525
526
static GTestLogFatalFunc fatal_log_func = NULL;
static gpointer          fatal_log_data;
527
528
529
static GLogWriterFunc log_writer_func = g_log_writer_default;
static gpointer       log_writer_user_data = NULL;
static GDestroyNotify log_writer_user_data_free = NULL;
530
static gboolean       g_log_debug_enabled = FALSE;  /* (atomic) */
531

532
/* --- functions --- */
533

534
static void _g_log_abort (gboolean breakpoint);
535
536

static void
537
_g_log_abort (gboolean breakpoint)
538
{
539
540
  gboolean debugger_present;

541
542
543
544
545
546
547
548
549
  if (g_test_subprocess ())
    {
      /* If this is a test case subprocess then it probably caused
       * this error message on purpose, so just exit() rather than
       * abort()ing, to avoid triggering any system crash-reporting
       * daemon.
       */
      _exit (1);
    }
550

551
552
553
554
555
556
557
558
#ifdef G_OS_WIN32
  debugger_present = IsDebuggerPresent ();
#else
  /* Assume GDB is attached. */
  debugger_present = TRUE;
#endif /* !G_OS_WIN32 */

  if (debugger_present && breakpoint)
559
    G_BREAKPOINT ();
560
  else
561
    g_abort ();
562
563
}

564
#ifdef G_OS_WIN32
565
static gboolean win32_keep_fatal_message = FALSE;
566
567

/* This default message will usually be overwritten. */
568
569
/* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
 * called with huge strings, is it?
570
571
572
 */
static gchar  fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
static gchar *fatal_msg_ptr = fatal_msg_buf;
573

574
575
#undef write
static inline int
576
dowrite (int          fd,
577
578
	 const void  *buf,
	 unsigned int len)
579
{
580
  if (win32_keep_fatal_message)
581
582
583
584
585
586
587
    {
      memcpy (fatal_msg_ptr, buf, len);
      fatal_msg_ptr += len;
      *fatal_msg_ptr = 0;
      return len;
    }

588
  write (fd, buf, len);
589
590
591

  return len;
}
592
593
#define write(fd, buf, len) dowrite(fd, buf, len)

594
#endif
595

596
static void
597
write_string (FILE        *stream,
598
	      const gchar *string)
599
{
600
  fputs (string, stream);
601
602
}

603
604
605
606
607
608
609
610
611
612
613
614
static void
write_string_sized (FILE        *stream,
                    const gchar *string,
                    gssize       length)
{
  /* Is it nul-terminated? */
  if (length < 0)
    write_string (stream, string);
  else
    fwrite (string, 1, length, stream);
}

615
616
static GLogDomain*
g_log_find_domain_L (const gchar *log_domain)
617
{
618
  GLogDomain *domain;
619
  
620
621
  domain = g_log_domains;
  while (domain)
Owen Taylor's avatar
Owen Taylor committed
622
    {
623
      if (strcmp (domain->log_domain, log_domain) == 0)
624
	return domain;
625
      domain = domain->next;
Owen Taylor's avatar
Owen Taylor committed
626
    }
627
628
629
  return NULL;
}

630
631
static GLogDomain*
g_log_domain_new_L (const gchar *log_domain)
632
{
633
  GLogDomain *domain;
634

635
636
637
638
  domain = g_new (GLogDomain, 1);
  domain->log_domain = g_strdup (log_domain);
  domain->fatal_mask = G_LOG_FATAL_MASK;
  domain->handlers = NULL;
639
  
640
641
642
643
644
  domain->next = g_log_domains;
  g_log_domains = domain;
  
  return domain;
}
Owen Taylor's avatar
Owen Taylor committed
645

646
647
static void
g_log_domain_check_free_L (GLogDomain *domain)
648
649
650
{
  if (domain->fatal_mask == G_LOG_FATAL_MASK &&
      domain->handlers == NULL)
Owen Taylor's avatar
Owen Taylor committed
651
    {
652
      GLogDomain *last, *work;
653
      
654
655
      last = NULL;  

656
657
658
659
660
661
662
663
664
665
666
667
668
      work = g_log_domains;
      while (work)
	{
	  if (work == domain)
	    {
	      if (last)
		last->next = domain->next;
	      else
		g_log_domains = domain->next;
	      g_free (domain->log_domain);
	      g_free (domain);
	      break;
	    }
669
670
	  last = work;
	  work = last->next;
671
	}  
Owen Taylor's avatar
Owen Taylor committed
672
    }
673
674
}

675
676
677
678
static GLogFunc
g_log_domain_get_handler_L (GLogDomain	*domain,
			    GLogLevelFlags log_level,
			    gpointer	*data)
679
680
{
  if (domain && log_level)
Owen Taylor's avatar
Owen Taylor committed
681
    {
682
      GLogHandler *handler;
683
684
685
686
687
688
689
690
691
692
693
      
      handler = domain->handlers;
      while (handler)
	{
	  if ((handler->log_level & log_level) == log_level)
	    {
	      *data = handler->data;
	      return handler->log_func;
	    }
	  handler = handler->next;
	}
Owen Taylor's avatar
Owen Taylor committed
694
    }
695
696
697

  *data = default_log_data;
  return default_log_func;
698
699
}

Matthias Clasen's avatar
Matthias Clasen committed
700
701
702
703
704
705
706
707
708
709
710
/**
 * g_log_set_always_fatal:
 * @fatal_mask: the mask containing bits set for each level
 *     of error which is to be fatal
 *
 * Sets the message levels which are always fatal, in any log domain.
 * When a message with any of these levels is logged the program terminates.
 * You can only set the levels defined by GLib to be fatal.
 * %G_LOG_LEVEL_ERROR is always fatal.
 *
 * You can also make some message levels fatal at runtime by setting
Matthias Clasen's avatar
Matthias Clasen committed
711
 * the `G_DEBUG` environment variable (see
712
 * [Running GLib Applications](glib-running.html)).
Matthias Clasen's avatar
Matthias Clasen committed
713
 *
714
715
716
717
718
719
 * Libraries should not call this function, as it affects all messages logged
 * by a process, including those from other libraries.
 *
 * Structured log messages (using g_log_structured() and
 * g_log_structured_array()) are fatal only if the default log writer is used;
 * otherwise it is up to the writer function to determine which log messages
720
 * are fatal. See [Using Structured Logging][using-structured-logging].
721
 *
Matthias Clasen's avatar
Matthias Clasen committed
722
723
 * Returns: the old fatal mask
 */
724
725
726
727
728
GLogLevelFlags
g_log_set_always_fatal (GLogLevelFlags fatal_mask)
{
  GLogLevelFlags old_mask;

729
730
731
  /* restrict the global mask to levels that are known to glib
   * since this setting applies to all domains
   */
732
733
734
735
736
737
  fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
  /* force errors to be fatal */
  fatal_mask |= G_LOG_LEVEL_ERROR;
  /* remove bogus flag */
  fatal_mask &= ~G_LOG_FLAG_FATAL;

738
  g_mutex_lock (&g_messages_lock);
739
740
  old_mask = g_log_always_fatal;
  g_log_always_fatal = fatal_mask;
741
  g_mutex_unlock (&g_messages_lock);
742
743
744
745

  return old_mask;
}

Matthias Clasen's avatar
Matthias Clasen committed
746
747
748
749
750
751
752
753
/**
 * g_log_set_fatal_mask:
 * @log_domain: the log domain
 * @fatal_mask: the new fatal mask
 *
 * Sets the log levels which are fatal in the given domain.
 * %G_LOG_LEVEL_ERROR is always fatal.
 *
754
755
756
 * This has no effect on structured log messages (using g_log_structured() or
 * g_log_structured_array()). To change the fatal behaviour for specific log
 * messages, programs must install a custom log writer function using
757
758
 * g_log_set_writer_func(). See
 * [Using Structured Logging][using-structured-logging].
759
 *
760
761
762
763
764
 * This function is mostly intended to be used with
 * %G_LOG_LEVEL_CRITICAL.  You should typically not set
 * %G_LOG_LEVEL_WARNING, %G_LOG_LEVEL_MESSAGE, %G_LOG_LEVEL_INFO or
 * %G_LOG_LEVEL_DEBUG as fatal except inside of test programs.
 *
Matthias Clasen's avatar
Matthias Clasen committed
765
766
 * Returns: the old fatal mask for the log domain
 */
767
GLogLevelFlags
768
769
g_log_set_fatal_mask (const gchar   *log_domain,
		      GLogLevelFlags fatal_mask)
770
771
{
  GLogLevelFlags old_flags;
772
  GLogDomain *domain;
773
774
775
  
  if (!log_domain)
    log_domain = "";
776

777
778
779
780
781
  /* force errors to be fatal */
  fatal_mask |= G_LOG_LEVEL_ERROR;
  /* remove bogus flag */
  fatal_mask &= ~G_LOG_FLAG_FATAL;
  
782
  g_mutex_lock (&g_messages_lock);
783

784
  domain = g_log_find_domain_L (log_domain);
785
  if (!domain)
786
    domain = g_log_domain_new_L (log_domain);
787
788
789
  old_flags = domain->fatal_mask;
  
  domain->fatal_mask = fatal_mask;
790
  g_log_domain_check_free_L (domain);
791

792
  g_mutex_unlock (&g_messages_lock);
793

794
795
  return old_flags;
}
Owen Taylor's avatar
Owen Taylor committed
796

Matthias Clasen's avatar
Matthias Clasen committed
797
798
/**
 * g_log_set_handler:
799
 * @log_domain: (nullable): the log domain, or %NULL for the default ""
800
 *    application domain
Matthias Clasen's avatar
Matthias Clasen committed
801
 * @log_levels: the log levels to apply the log handler for.
802
803
804
 *    To handle fatal and recursive messages as well, combine
 *    the log levels with the %G_LOG_FLAG_FATAL and
 *    %G_LOG_FLAG_RECURSION bit flags.
Matthias Clasen's avatar
Matthias Clasen committed
805
806
807
808
 * @log_func: the log handler function
 * @user_data: data passed to the log handler
 *
 * Sets the log handler for a domain and a set of log levels.
809
 *
Matthias Clasen's avatar
Matthias Clasen committed
810
 * To handle fatal and recursive messages the @log_levels parameter
811
 * must be combined with the %G_LOG_FLAG_FATAL and %G_LOG_FLAG_RECURSION
Matthias Clasen's avatar
Matthias Clasen committed
812
813
 * bit flags.
 *
814
 * Note that since the %G_LOG_LEVEL_ERROR log level is always fatal, if
Matthias Clasen's avatar
Matthias Clasen committed
815
 * you want to set a handler for this log level you must combine it with
816
 * %G_LOG_FLAG_FATAL.
Matthias Clasen's avatar
Matthias Clasen committed
817
 *
818
819
820
 * This has no effect if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
 *
821
822
 * Here is an example for adding a log handler for all warning messages
 * in the default domain:
823
 *
824
 * |[<!-- language="C" --> 
Matthias Clasen's avatar
Matthias Clasen committed
825
826
 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
 *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
827
 * ]|
Matthias Clasen's avatar
Matthias Clasen committed
828
 *
829
 * This example adds a log handler for all critical messages from GTK+:
830
 *
831
 * |[<!-- language="C" --> 
Matthias Clasen's avatar
Matthias Clasen committed
832
833
 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
 *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
834
 * ]|
Matthias Clasen's avatar
Matthias Clasen committed
835
 *
836
 * This example adds a log handler for all messages from GLib:
837
 *
838
 * |[<!-- language="C" --> 
Matthias Clasen's avatar
Matthias Clasen committed
839
840
 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
 *                    | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
841
 * ]|
Matthias Clasen's avatar
Matthias Clasen committed
842
843
844
 *
 * Returns: the id of the new handler
 */
845
guint
846
g_log_set_handler (const gchar	 *log_domain,
Matthias Clasen's avatar
Matthias Clasen committed
847
848
849
850
851
852
853
854
855
                   GLogLevelFlags log_levels,
                   GLogFunc       log_func,
                   gpointer       user_data)
{
  return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
}

/**
 * g_log_set_handler_full: (rename-to g_log_set_handler)
856
 * @log_domain: (nullable): the log domain, or %NULL for the default ""
857
 *   application domain
Matthias Clasen's avatar
Matthias Clasen committed
858
 * @log_levels: the log levels to apply the log handler for.
859
860
861
 *   To handle fatal and recursive messages as well, combine
 *   the log levels with the %G_LOG_FLAG_FATAL and
 *   %G_LOG_FLAG_RECURSION bit flags.
Matthias Clasen's avatar
Matthias Clasen committed
862
863
864
865
 * @log_func: the log handler function
 * @user_data: data passed to the log handler
 * @destroy: destroy notify for @user_data, or %NULL
 *
866
 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
Matthias Clasen's avatar
Matthias Clasen committed
867
 *
868
869
870
 * This has no effect if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
 *
Matthias Clasen's avatar
Matthias Clasen committed
871
872
 * Returns: the id of the new handler
 *
873
 * Since: 2.46
Matthias Clasen's avatar
Matthias Clasen committed
874
875
876
877
878
879
880
 */
guint
g_log_set_handler_full (const gchar    *log_domain,
                        GLogLevelFlags  log_levels,
                        GLogFunc        log_func,
                        gpointer        user_data,
                        GDestroyNotify  destroy)
881
882
{
  static guint handler_id = 0;
883
884
  GLogDomain *domain;
  GLogHandler *handler;
885
886
887
888
889
890
  
  g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
  g_return_val_if_fail (log_func != NULL, 0);
  
  if (!log_domain)
    log_domain = "";
891
892
893

  handler = g_new (GLogHandler, 1);

894
  g_mutex_lock (&g_messages_lock);
895

896
  domain = g_log_find_domain_L (log_domain);
897
  if (!domain)
898
    domain = g_log_domain_new_L (log_domain);
899
900
901
902
903
  
  handler->id = ++handler_id;
  handler->log_level = log_levels;
  handler->log_func = log_func;
  handler->data = user_data;
Matthias Clasen's avatar
Matthias Clasen committed
904
  handler->destroy = destroy;
905
906
  handler->next = domain->handlers;
  domain->handlers = handler;
907

908
  g_mutex_unlock (&g_messages_lock);
909
910
  
  return handler_id;
Owen Taylor's avatar
Owen Taylor committed
911
912
}

Matthias Clasen's avatar
Matthias Clasen committed
913
914
/**
 * g_log_set_default_handler:
915
 * @log_func: the log handler function
Matthias Clasen's avatar
Matthias Clasen committed
916
917
918
919
920
921
922
 * @user_data: data passed to the log handler
 *
 * Installs a default log handler which is used if no
 * log handler has been set for the particular log domain
 * and log level combination. By default, GLib uses
 * g_log_default_handler() as default log handler.
 *
923
924
925
 * This has no effect if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
 *
Matthias Clasen's avatar
Matthias Clasen committed
926
927
928
929
 * Returns: the previous default log handler
 *
 * Since: 2.6
 */
930
931
932
933
934
935
GLogFunc
g_log_set_default_handler (GLogFunc log_func,
			   gpointer user_data)
{
  GLogFunc old_log_func;
  
936
  g_mutex_lock (&g_messages_lock);
937
938
939
  old_log_func = default_log_func;
  default_log_func = log_func;
  default_log_data = user_data;
940
  g_mutex_unlock (&g_messages_lock);
941
942
943
944
  
  return old_log_func;
}

945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
/**
 * g_test_log_set_fatal_handler:
 * @log_func: the log handler function.
 * @user_data: data passed to the log handler.
 *
 * Installs a non-error fatal log handler which can be
 * used to decide whether log messages which are counted
 * as fatal abort the program.
 *
 * The use case here is that you are running a test case
 * that depends on particular libraries or circumstances
 * and cannot prevent certain known critical or warning
 * messages. So you install a handler that compares the
 * domain and message to precisely not abort in such a case.
 *
 * Note that the handler is reset at the beginning of
 * any test case, so you have to set it inside each test
 * function which needs the special behavior.
 *
 * This handler has no effect on g_error messages.
 *
966
967
968
 * This handler also has no effect on structured log messages (using
 * g_log_structured() or g_log_structured_array()). To change the fatal
 * behaviour for specific log messages, programs must install a custom log
969
970
 * writer function using g_log_set_writer_func().See
 * [Using Structured Logging][using-structured-logging].
971
 *
972
973
974
975
976
977
 * Since: 2.22
 **/
void
g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
                              gpointer          user_data)
{
978
  g_mutex_lock (&g_messages_lock);
979
980
  fatal_log_func = log_func;
  fatal_log_data = user_data;
981
  g_mutex_unlock (&g_messages_lock);
982
983
}

Matthias Clasen's avatar
Matthias Clasen committed
984
985
986
987
988
989
990
/**
 * g_log_remove_handler:
 * @log_domain: the log domain
 * @handler_id: the id of the handler, which was returned
 *     in g_log_set_handler()
 *
 * Removes the log handler.
991
992
993
 *
 * This has no effect if structured logging is enabled; see
 * [Using Structured Logging][using-structured-logging].
Matthias Clasen's avatar
Matthias Clasen committed
994
 */
Owen Taylor's avatar
Owen Taylor committed
995
void
996
997
g_log_remove_handler (const gchar *log_domain,
		      guint	   handler_id)
Owen Taylor's avatar
Owen Taylor committed
998
{
999
  GLogDomain *domain;
1000
1001
1002
1003
1004
1005
  
  g_return_if_fail (handler_id > 0);
  
  if (!log_domain)
    log_domain = "";
  
1006
  g_mutex_lock (&g_messages_lock);
1007
  domain = g_log_find_domain_L (log_domain);
1008
1009
  if (domain)
    {
1010
      GLogHandler *work, *last;
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
      
      last = NULL;
      work = domain->handlers;
      while (work)
	{
	  if (work->id == handler_id)
	    {
	      if (last)
		last->next = work->next;
	      else
		domain->handlers = work->next;
1022
	      g_log_domain_check_free_L (domain); 
1023
	      g_mutex_unlock (&g_messages_lock);
Matthias Clasen's avatar
Matthias Clasen committed
1024
1025
              if (work->destroy)
                work->destroy (work->data);
1026
	      g_free (work);
1027
1028
	      return;
	    }
1029
1030
	  last = work;
	  work = last->next;
1031
	}
1032
    } 
1033
  g_mutex_unlock (&g_messages_lock);
1034
  g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1035
	     G_STRLOC, handler_id, log_domain);
1036
}
Owen Taylor's avatar
Owen Taylor committed
1037

1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
#define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
			    (wc == 0x7f) || \
			    (wc >= 0x80 && wc < 0xa0)))
     
static gchar*
strdup_convert (const gchar *string,
		const gchar *charset)
{
  if (!g_utf8_validate (string, -1, NULL))
    {
      GString *gstring = g_string_new ("[Invalid UTF-8] ");
      guchar *p;

      for (p = (guchar *)string; *p; p++)
	{
	  if (CHAR_IS_SAFE(*p) &&
	      !(*p == '\r' && *(p + 1) != '\n') &&
	      *p < 0x80)
	    g_string_append_c (gstring, *p);
	  else
	    g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
	}
      
      return g_string_free (gstring, FALSE);
    }
  else
    {
      GError *err = NULL;
      
      gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
      if (result)
	return result;
      else
	{
	  /* Not thread-safe, but doesn't matter if we print the warning twice
	   */
	  static gboolean warned = FALSE; 
	  if (!warned)
	    {
	      warned = TRUE;
	      _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
	    }
	  g_error_free (err);
	  
	  return g_strdup (string);
	}
    }
}

/* For a radix of 8 we need at most 3 output bytes for 1 input
 * byte. Additionally we might need up to 2 output bytes for the
 * readix prefix and 1 byte for the trailing NULL.
 */
#define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)

static void
format_unsigned (gchar  *buf,
		 gulong  num,
		 guint   radix)
{
  gulong tmp;
  gchar c;
  gint i, n;

  /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */

  if (radix != 8 && radix != 10 && radix != 16)
    {
      *buf = '\000';
      return;
    }
  
  if (!num)
    {
      *buf++ = '0';
      *buf = '\000';
      return;
    } 
  
  if (radix == 16)
    {
      *buf++ = '0';
      *buf++ = 'x';
    }
  else if (radix == 8)
    {
      *buf++ = '0';
    }
	
  n = 0;
  tmp = num;
  while (tmp)
    {
      tmp /= radix;
      n++;
    }

  i = n;

  /* Again we can't use g_assert; actually this check should _never_ fail. */
  if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
    {
      *buf = '\000';
      return;
    }

  while (num)
    {
      i--;
      c = (num % radix);
      if (c < 10)
	buf[i] = c + '0';
      else
	buf[i] = c + 'a' - 10;
      num /= radix;
    }
  
  buf[n] = '\000';
}

/* string size big enough to hold level prefix */
#define	STRING_BUFFER_SIZE	(FORMAT_UNSIGNED_BUFSIZE + 32)

#define	ALERT_LEVELS		(G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)

/* these are emitted by the default log handler */
#define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
/* these are filtered by G_MESSAGES_DEBUG by the default log handler */
#define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)

1168
1169
1170
1171
static const gchar *log_level_to_color (GLogLevelFlags log_level,
                                        gboolean       use_color);
static const gchar *color_reset        (gboolean       use_color);

1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
static gboolean gmessages_use_stderr = FALSE;

/**
 * g_log_writer_default_set_use_stderr:
 * @use_stderr: If %TRUE, use `stderr` for log messages that would
 *  normally have appeared on `stdout`
 *
 * Configure whether the built-in log functions
 * (g_log_default_handler() for the old-style API, and both
 * g_log_writer_default() and g_log_writer_standard_streams() for the
 * structured API) will output all log messages to `stderr`.
 *
 * By default, log messages of levels %G_LOG_LEVEL_INFO and
 * %G_LOG_LEVEL_DEBUG are sent to `stdout`, and other log messages are
 * sent to `stderr`. This is problematic for applications that intend
 * to reserve `stdout` for structured output such as JSON or XML.
 *
 * This function sets global state. It is not thread-aware, and should be
 * called at the very start of a program, before creating any other threads
 * or creating objects that could create worker threads of their own.
 *
 * Since: 2.68
 */
void
g_log_writer_default_set_use_stderr (gboolean use_stderr)
{
  g_return_if_fail (g_thread_n_created () == 0);
  gmessages_use_stderr = use_stderr;
}

1202
static FILE *
1203
mklevel_prefix (gchar          level_prefix[STRING_BUFFER_SIZE],
1204
1205
                GLogLevelFlags log_level,
                gboolean       use_color)
1206
{
1207
  gboolean to_stdout = !gmessages_use_stderr;
1208
1209
1210

  /* we may not call _any_ GLib functions here */

1211
1212
  strcpy (level_prefix, log_level_to_color (log_level, use_color));

1213
1214
1215
  switch (log_level & G_LOG_LEVEL_MASK)
    {
    case G_LOG_LEVEL_ERROR:
1216
      strcat (level_prefix, "ERROR");
1217
1218
1219
      to_stdout = FALSE;
      break;
    case G_LOG_LEVEL_CRITICAL:
1220
      strcat (level_prefix, "CRITICAL");
1221
1222
1223
      to_stdout = FALSE;
      break;
    case G_LOG_LEVEL_WARNING:
1224
      strcat (level_prefix, "WARNING");
1225
1226
1227
      to_stdout = FALSE;
      break;
    case G_LOG_LEVEL_MESSAGE:
1228
      strcat (level_prefix, "Message");
1229
1230
1231
      to_stdout = FALSE;
      break;
    case G_LOG_LEVEL_INFO:
1232
      strcat (level_prefix, "INFO");
1233
1234
      break;
    case G_LOG_LEVEL_DEBUG:
1235
      strcat (level_prefix, "DEBUG");
1236
1237
1238
1239
      break;
    default:
      if (log_level)
	{
1240
	  strcat (level_prefix, "LOG-");
1241
1242
1243
	  format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
	}
      else
1244
	strcat (level_prefix, "LOG");
1245
1246
      break;
    }
1247
1248
1249

  strcat (level_prefix, color_reset (use_color));

1250
1251
1252
1253
1254
1255
  if (log_level & G_LOG_FLAG_RECURSION)
    strcat (level_prefix, " (recursed)");
  if (log_level & ALERT_LEVELS)
    strcat (level_prefix, " **");

#ifdef G_OS_WIN32
1256
1257
  if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
    win32_keep_fatal_message = TRUE;
1258
#endif
1259
  return to_stdout ? stdout : stderr;
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
}

typedef struct {
  gchar          *log_domain;
  GLogLevelFlags  log_level;
  gchar          *pattern;
} GTestExpectedMessage;

static GSList *expected_messages = NULL;

Matthias Clasen's avatar
Matthias Clasen committed
1270
1271
/**
 * g_logv:
1272
1273
 * @log_domain: (nullable): the log domain, or %NULL for the default ""
 * application domain
Matthias Clasen's avatar
Matthias Clasen committed
1274
1275
1276
1277
1278
1279
 * @log_level: the log level
 * @format: the message format. See the printf() documentation
 * @args: the parameters to insert into the format string
 *
 * Logs an error or debugging message.
 *
1280
1281
1282
 * If the log level has been set as fatal, G_BREAKPOINT() is called
 * to terminate the program. See the documentation for G_BREAKPOINT() for
 * details of the debugging options this provides.
1283
1284
1285
1286
 *
 * If g_log_default_handler() is used as the log handler function, a new-line
 * character will automatically be appended to @..., and need not be entered
 * manually.