1 /*-------------------------------------------------------------------------
4 * error logging and reporting
6 * Because of the extremely high rate at which log messages can be generated,
7 * we need to be mindful of the performance cost of obtaining any information
8 * that may be logged. Also, it's important to keep in mind that this code may
9 * get called from within an aborted transaction, in which case operations
10 * such as syscache lookups are unsafe.
12 * Some notes about recursion and errors during error processing:
14 * We need to be robust about recursive-error scenarios --- for example,
15 * if we run out of memory, it's important to be able to report that fact.
16 * There are a number of considerations that go into this.
18 * First, distinguish between re-entrant use and actual recursion. It
19 * is possible for an error or warning message to be emitted while the
20 * parameters for an error message are being computed. In this case
21 * errstart has been called for the outer message, and some field values
22 * may have already been saved, but we are not actually recursing. We handle
23 * this by providing a (small) stack of ErrorData records. The inner message
24 * can be computed and sent without disturbing the state of the outer message.
25 * (If the inner message is actually an error, this isn't very interesting
26 * because control won't come back to the outer message generator ... but
27 * if the inner message is only debug or log data, this is critical.)
29 * Second, actual recursion will occur if an error is reported by one of
30 * the elog.c routines or something they call. By far the most probable
31 * scenario of this sort is "out of memory"; and it's also the nastiest
32 * to handle because we'd likely also run out of memory while trying to
33 * report this error! Our escape hatch for this case is to reset the
34 * ErrorContext to empty before trying to process the inner error. Since
35 * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
36 * we should be able to process an "out of memory" message successfully.
37 * Since we lose the prior error state due to the reset, we won't be able
38 * to return to processing the original error, but we wouldn't have anyway.
39 * (NOTE: the escape hatch is not used for recursive situations where the
40 * inner message is of less than ERROR severity; in that case we just
41 * try to process it and return normally. Usually this will work, but if
42 * it ends up in infinite recursion, we will PANIC due to error stack
46 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
47 * Portions Copyright (c) 1994, Regents of the University of California
51 * src/backend/utils/error/elog.c
53 *-------------------------------------------------------------------------
66 #include "access/transam.h"
67 #include "access/xact.h"
68 #include "libpq/libpq.h"
69 #include "libpq/pqformat.h"
70 #include "mb/pg_wchar.h"
71 #include "miscadmin.h"
72 #include "postmaster/postmaster.h"
73 #include "postmaster/syslogger.h"
74 #include "storage/ipc.h"
75 #include "storage/proc.h"
76 #include "tcop/tcopprot.h"
77 #include "utils/guc.h"
78 #include "utils/memutils.h"
79 #include "utils/ps_status.h"
83 #define _(x) err_gettext(x)
86 err_gettext(const char *str)
87 /* This extension allows gcc to check the format string for consistency with
88 the supplied arguments. */
89 __attribute__((format_arg(1)));
91 /* Global variables */
92 ErrorContextCallback *error_context_stack = NULL;
94 sigjmp_buf *PG_exception_stack = NULL;
96 extern bool redirection_done;
99 int Log_error_verbosity = PGERROR_VERBOSE;
100 char *Log_line_prefix = NULL; /* format for extra log line info */
101 int Log_destination = LOG_DESTINATION_STDERR;
106 * Max string length to send to syslog(). Note that this doesn't count the
107 * sequence-number prefix we add, and of course it doesn't count the prefix
108 * added by syslog itself. Solaris and sysklogd truncate the final message
109 * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
110 * other syslog implementations seem to have limits of 2KB or so.)
112 #ifndef PG_SYSLOG_LIMIT
113 #define PG_SYSLOG_LIMIT 900
116 static bool openlog_done = false;
117 static char *syslog_ident = NULL;
118 static int syslog_facility = LOG_LOCAL0;
120 static void write_syslog(int level, const char *line);
123 static void write_console(const char *line, int len);
126 extern char *event_source;
127 static void write_eventlog(int level, const char *line, int len);
130 /* We provide a small stack of ErrorData records for re-entrant cases */
131 #define ERRORDATA_STACK_SIZE 5
133 static ErrorData errordata[ERRORDATA_STACK_SIZE];
135 static int errordata_stack_depth = -1; /* index of topmost active frame */
137 static int recursion_depth = 0; /* to detect actual recursion */
139 /* buffers for formatted timestamps that might be used by both
140 * log_line_prefix and csv logs.
143 #define FORMATTED_TS_LEN 128
144 static char formatted_start_time[FORMATTED_TS_LEN];
145 static char formatted_log_time[FORMATTED_TS_LEN];
148 /* Macro for checking errordata_stack_depth is reasonable */
149 #define CHECK_STACK_DEPTH() \
151 if (errordata_stack_depth < 0) \
153 errordata_stack_depth = -1; \
154 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
159 static void log_line_prefix(StringInfo buf, ErrorData *edata);
160 static void send_message_to_server_log(ErrorData *edata);
161 static void send_message_to_frontend(ErrorData *edata);
162 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
163 static const char *useful_strerror(int errnum);
164 static const char *error_severity(int elevel);
165 static void append_with_tabs(StringInfo buf, const char *str);
166 static bool is_log_level_output(int elevel, int log_min_level);
167 static void write_pipe_chunks(char *data, int len, int dest);
168 static void write_csvlog(ErrorData *edata);
169 static void setup_formatted_log_time(void);
170 static void setup_formatted_start_time(void);
174 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
176 * This function exists to provide common control of various fallback steps
177 * that we take if we think we are facing infinite error recursion. See the
178 * callers for details.
181 in_error_recursion_trouble(void)
183 /* Pull the plug if recurse more than once */
184 return (recursion_depth > 2);
188 * One of those fallback steps is to stop trying to localize the error
189 * message, since there's a significant probability that that's exactly
190 * what's causing the recursion.
192 static inline const char *
193 err_gettext(const char *str)
196 if (in_error_recursion_trouble())
207 * errstart --- begin an error-reporting cycle
209 * Create a stack entry and store the given parameters in it. Subsequently,
210 * errmsg() and perhaps other routines will be called to further populate
211 * the stack entry. Finally, errfinish() will be called to actually process
214 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
215 * report (if it's a warning or lower and not to be reported anywhere).
218 errstart(int elevel, const char *filename, int lineno,
219 const char *funcname, const char *domain)
222 bool output_to_server;
223 bool output_to_client = false;
227 * Check some cases in which we want to promote an error into a more
228 * severe error. None of this logic applies for non-error messages.
233 * If we are inside a critical section, all errors become PANIC
234 * errors. See miscadmin.h.
236 if (CritSectionCount > 0)
240 * Check reasons for treating ERROR as FATAL:
242 * 1. we have no handler to pass the error to (implies we are in the
243 * postmaster or in backend startup).
245 * 2. ExitOnAnyError mode switch is set (initdb uses this).
247 * 3. the error occurred after proc_exit has begun to run. (It's
248 * proc_exit's responsibility to see that this doesn't turn into
249 * infinite recursion!)
253 if (PG_exception_stack == NULL ||
255 proc_exit_inprogress)
260 * If the error level is ERROR or more, errfinish is not going to
261 * return to caller; therefore, if there is any stacked error already
262 * in progress it will be lost. This is more or less okay, except we
263 * do not want to have a FATAL or PANIC error downgraded because the
264 * reporting process was interrupted by a lower-grade error. So check
265 * the stack and make sure we panic if panic is warranted.
267 for (i = 0; i <= errordata_stack_depth; i++)
268 elevel = Max(elevel, errordata[i].elevel);
272 * Now decide whether we need to process this report at all; if it's
273 * warning or less and not enabled for logging, just return FALSE without
274 * starting up any error logging machinery.
277 /* Determine whether message is enabled for server log output */
278 if (IsPostmasterEnvironment)
279 output_to_server = is_log_level_output(elevel, log_min_messages);
281 /* In bootstrap/standalone case, do not sort LOG out-of-order */
282 output_to_server = (elevel >= log_min_messages);
284 /* Determine whether message is enabled for client output */
285 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
288 * client_min_messages is honored only after we complete the
289 * authentication handshake. This is required both for security
290 * reasons and because many clients can't handle NOTICE messages
291 * during authentication.
293 if (ClientAuthInProgress)
294 output_to_client = (elevel >= ERROR);
296 output_to_client = (elevel >= client_min_messages ||
300 /* Skip processing effort if non-error message will not be output */
301 if (elevel < ERROR && !output_to_server && !output_to_client)
305 * Okay, crank up a stack entry to store the info in.
308 if (recursion_depth++ > 0 && elevel >= ERROR)
311 * Ooops, error during error processing. Clear ErrorContext as
312 * discussed at top of file. We will not return to the original
313 * error's reporter or handler, so we don't need it.
315 MemoryContextReset(ErrorContext);
318 * Infinite error recursion might be due to something broken in a
319 * context traceback routine. Abandon them too. We also abandon
320 * attempting to print the error statement (which, if long, could
321 * itself be the source of the recursive failure).
323 if (in_error_recursion_trouble())
325 error_context_stack = NULL;
326 debug_query_string = NULL;
329 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
332 * Wups, stack not big enough. We treat this as a PANIC condition
333 * because it suggests an infinite loop of errors during error
336 errordata_stack_depth = -1; /* make room on stack */
337 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
340 /* Initialize data for this error frame */
341 edata = &errordata[errordata_stack_depth];
342 MemSet(edata, 0, sizeof(ErrorData));
343 edata->elevel = elevel;
344 edata->output_to_server = output_to_server;
345 edata->output_to_client = output_to_client;
350 /* keep only base name, useful especially for vpath builds */
351 slash = strrchr(filename, '/');
352 edata->filename = slash ? slash + 1 : filename;
354 edata->lineno = lineno;
355 edata->funcname = funcname;
356 /* the default text domain is the backend's */
357 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
358 /* Select default errcode based on elevel */
360 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
361 else if (elevel == WARNING)
362 edata->sqlerrcode = ERRCODE_WARNING;
364 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
365 /* errno is saved here so that error parameter eval can't change it */
366 edata->saved_errno = errno;
373 * errfinish --- end an error-reporting cycle
375 * Produce the appropriate error report(s) and pop the error stack.
377 * If elevel is ERROR or worse, control does not return to the caller.
378 * See elog.h for the error level definitions.
381 errfinish(int dummy,...)
383 ErrorData *edata = &errordata[errordata_stack_depth];
384 int elevel = edata->elevel;
385 MemoryContext oldcontext;
386 ErrorContextCallback *econtext;
392 * Do processing in ErrorContext, which we hope has enough reserved space
393 * to report an error.
395 oldcontext = MemoryContextSwitchTo(ErrorContext);
398 * Call any context callback functions. Errors occurring in callback
399 * functions will be treated as recursive errors --- this ensures we will
400 * avoid infinite recursion (see errstart).
402 for (econtext = error_context_stack;
404 econtext = econtext->previous)
405 (*econtext->callback) (econtext->arg);
408 * If ERROR (not more nor less) we pass it off to the current handler.
409 * Printing it and popping the stack is the responsibility of the handler.
414 * We do some minimal cleanup before longjmp'ing so that handlers can
415 * execute in a reasonably sane state.
418 /* This is just in case the error came while waiting for input */
419 ImmediateInterruptOK = false;
422 * Reset InterruptHoldoffCount in case we ereport'd from inside an
423 * interrupt holdoff section. (We assume here that no handler will
424 * itself be inside a holdoff section. If necessary, such a handler
425 * could save and restore InterruptHoldoffCount for itself, but this
426 * should make life easier for most.)
428 InterruptHoldoffCount = 0;
430 CritSectionCount = 0; /* should be unnecessary, but... */
433 * Note that we leave CurrentMemoryContext set to ErrorContext. The
434 * handler should reset it to something else soon.
442 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
443 * progress, so that we can report the message before dying. (Without
444 * this, pq_putmessage will refuse to send the message at all, which is
445 * what we want for NOTICE messages, but not for fatal exits.) This hack
446 * is necessary because of poor design of old-style copy protocol. Note
447 * we must do this even if client is fool enough to have set
448 * client_min_messages above FATAL, so don't look at output_to_client.
450 if (elevel >= FATAL && whereToSendOutput == DestRemote)
453 /* Emit the message to the right places */
456 /* Now free up subsidiary data attached to stack entry, and release it */
458 pfree(edata->message);
460 pfree(edata->detail);
461 if (edata->detail_log)
462 pfree(edata->detail_log);
466 pfree(edata->context);
467 if (edata->internalquery)
468 pfree(edata->internalquery);
470 errordata_stack_depth--;
472 /* Exit error-handling context */
473 MemoryContextSwitchTo(oldcontext);
477 * Perform error recovery action as specified by elevel.
482 * For a FATAL error, we let proc_exit clean up and exit.
484 ImmediateInterruptOK = false;
487 * If we just reported a startup failure, the client will disconnect
488 * on receiving it, so don't send any more to the client.
490 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
491 whereToSendOutput = DestNone;
494 * fflush here is just to improve the odds that we get to see the
495 * error message, in case things are so hosed that proc_exit crashes.
496 * Any other code you might be tempted to add here should probably be
497 * in an on_proc_exit or on_shmem_exit callback instead.
503 * Do normal process-exit cleanup, then return exit code 1 to indicate
504 * FATAL termination. The postmaster may or may not consider this
505 * worthy of panic, depending on which subprocess returns it.
513 * Serious crash time. Postmaster will observe SIGABRT process exit
514 * status and kill the other backends too.
516 * XXX: what if we are *in* the postmaster? abort() won't kill our
519 ImmediateInterruptOK = false;
526 * We reach here if elevel <= WARNING. OK to return to caller.
528 * But check for cancel/die interrupt first --- this is so that the user
529 * can stop a query emitting tons of notice or warning messages, even if
530 * it's in a loop that otherwise fails to check for interrupts.
532 CHECK_FOR_INTERRUPTS();
537 * errcode --- add SQLSTATE error code to the current error
539 * The code is expected to be represented as per MAKE_SQLSTATE().
542 errcode(int sqlerrcode)
544 ErrorData *edata = &errordata[errordata_stack_depth];
546 /* we don't bother incrementing recursion_depth */
549 edata->sqlerrcode = sqlerrcode;
551 return 0; /* return value does not matter */
556 * errcode_for_file_access --- add SQLSTATE error code to the current error
558 * The SQLSTATE code is chosen based on the saved errno value. We assume
559 * that the failing operation was some type of disk file access.
561 * NOTE: the primary error message string should generally include %m
565 errcode_for_file_access(void)
567 ErrorData *edata = &errordata[errordata_stack_depth];
569 /* we don't bother incrementing recursion_depth */
572 switch (edata->saved_errno)
574 /* Permission-denied failures */
575 case EPERM: /* Not super-user */
576 case EACCES: /* Permission denied */
578 case EROFS: /* Read only file system */
580 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
584 case ENOENT: /* No such file or directory */
585 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
589 case EEXIST: /* File exists */
590 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
593 /* Wrong object type or state */
594 case ENOTDIR: /* Not a directory */
595 case EISDIR: /* Is a directory */
596 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
597 case ENOTEMPTY: /* Directory not empty */
599 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
602 /* Insufficient resources */
603 case ENOSPC: /* No space left on device */
604 edata->sqlerrcode = ERRCODE_DISK_FULL;
607 case ENFILE: /* File table overflow */
608 case EMFILE: /* Too many open files */
609 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
612 /* Hardware failure */
613 case EIO: /* I/O error */
614 edata->sqlerrcode = ERRCODE_IO_ERROR;
617 /* All else is classified as internal errors */
619 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
623 return 0; /* return value does not matter */
627 * errcode_for_socket_access --- add SQLSTATE error code to the current error
629 * The SQLSTATE code is chosen based on the saved errno value. We assume
630 * that the failing operation was some type of socket access.
632 * NOTE: the primary error message string should generally include %m
636 errcode_for_socket_access(void)
638 ErrorData *edata = &errordata[errordata_stack_depth];
640 /* we don't bother incrementing recursion_depth */
643 switch (edata->saved_errno)
645 /* Loss of connection */
650 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
653 /* All else is classified as internal errors */
655 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
659 return 0; /* return value does not matter */
664 * This macro handles expansion of a format string and associated parameters;
665 * it's common code for errmsg(), errdetail(), etc. Must be called inside
666 * a routine that is declared like "const char *fmt, ..." and has an edata
667 * pointer set up. The message is assigned to edata->targetfield, or
668 * appended to it if appendval is true. The message is subject to translation
669 * if translateit is true.
671 * Note: we pstrdup the buffer rather than just transferring its storage
672 * to the edata field because the buffer might be considerably larger than
675 #define EVALUATE_MESSAGE(targetfield, appendval, translateit) \
678 StringInfoData buf; \
679 /* Internationalize the error format string */ \
680 if (translateit && !in_error_recursion_trouble()) \
681 fmt = dgettext(edata->domain, fmt); \
682 /* Expand %m in format string */ \
683 fmtbuf = expand_fmt_string(fmt, edata); \
684 initStringInfo(&buf); \
685 if ((appendval) && edata->targetfield) { \
686 appendStringInfoString(&buf, edata->targetfield); \
687 appendStringInfoChar(&buf, '\n'); \
689 /* Generate actual output --- have to use appendStringInfoVA */ \
694 va_start(args, fmt); \
695 success = appendStringInfoVA(&buf, fmtbuf, args); \
699 enlargeStringInfo(&buf, buf.maxlen); \
701 /* Done with expanded fmt */ \
703 /* Save the completed message into the stack item */ \
704 if (edata->targetfield) \
705 pfree(edata->targetfield); \
706 edata->targetfield = pstrdup(buf.data); \
711 * Same as above, except for pluralized error messages. The calling routine
712 * must be declared like "const char *fmt_singular, const char *fmt_plural,
713 * unsigned long n, ...". Translation is assumed always wanted.
715 #define EVALUATE_MESSAGE_PLURAL(targetfield, appendval) \
719 StringInfoData buf; \
720 /* Internationalize the error format string */ \
721 if (!in_error_recursion_trouble()) \
722 fmt = dngettext(edata->domain, fmt_singular, fmt_plural, n); \
724 fmt = (n == 1 ? fmt_singular : fmt_plural); \
725 /* Expand %m in format string */ \
726 fmtbuf = expand_fmt_string(fmt, edata); \
727 initStringInfo(&buf); \
728 if ((appendval) && edata->targetfield) { \
729 appendStringInfoString(&buf, edata->targetfield); \
730 appendStringInfoChar(&buf, '\n'); \
732 /* Generate actual output --- have to use appendStringInfoVA */ \
738 success = appendStringInfoVA(&buf, fmtbuf, args); \
742 enlargeStringInfo(&buf, buf.maxlen); \
744 /* Done with expanded fmt */ \
746 /* Save the completed message into the stack item */ \
747 if (edata->targetfield) \
748 pfree(edata->targetfield); \
749 edata->targetfield = pstrdup(buf.data); \
755 * errmsg --- add a primary error message text to the current error
757 * In addition to the usual %-escapes recognized by printf, "%m" in
758 * fmt is replaced by the error message for the caller's value of errno.
760 * Note: no newline is needed at the end of the fmt string, since
761 * ereport will provide one for the output methods that need it.
764 errmsg(const char *fmt,...)
766 ErrorData *edata = &errordata[errordata_stack_depth];
767 MemoryContext oldcontext;
771 oldcontext = MemoryContextSwitchTo(ErrorContext);
773 EVALUATE_MESSAGE(message, false, true);
775 MemoryContextSwitchTo(oldcontext);
777 return 0; /* return value does not matter */
782 * errmsg_internal --- add a primary error message text to the current error
784 * This is exactly like errmsg() except that strings passed to errmsg_internal
785 * are not translated, and are customarily left out of the
786 * internationalization message dictionary. This should be used for "can't
787 * happen" cases that are probably not worth spending translation effort on.
788 * We also use this for certain cases where we *must* not try to translate
789 * the message because the translation would fail and result in infinite
793 errmsg_internal(const char *fmt,...)
795 ErrorData *edata = &errordata[errordata_stack_depth];
796 MemoryContext oldcontext;
800 oldcontext = MemoryContextSwitchTo(ErrorContext);
802 EVALUATE_MESSAGE(message, false, false);
804 MemoryContextSwitchTo(oldcontext);
806 return 0; /* return value does not matter */
811 * errmsg_plural --- add a primary error message text to the current error,
812 * with support for pluralization of the message text
815 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
818 ErrorData *edata = &errordata[errordata_stack_depth];
819 MemoryContext oldcontext;
823 oldcontext = MemoryContextSwitchTo(ErrorContext);
825 EVALUATE_MESSAGE_PLURAL(message, false);
827 MemoryContextSwitchTo(oldcontext);
829 return 0; /* return value does not matter */
834 * errdetail --- add a detail error message text to the current error
837 errdetail(const char *fmt,...)
839 ErrorData *edata = &errordata[errordata_stack_depth];
840 MemoryContext oldcontext;
844 oldcontext = MemoryContextSwitchTo(ErrorContext);
846 EVALUATE_MESSAGE(detail, false, true);
848 MemoryContextSwitchTo(oldcontext);
850 return 0; /* return value does not matter */
855 * errdetail_internal --- add a detail error message text to the current error
857 * This is exactly like errdetail() except that strings passed to
858 * errdetail_internal are not translated, and are customarily left out of the
859 * internationalization message dictionary. This should be used for detail
860 * messages that seem not worth translating for one reason or another
861 * (typically, that they don't seem to be useful to average users).
864 errdetail_internal(const char *fmt,...)
866 ErrorData *edata = &errordata[errordata_stack_depth];
867 MemoryContext oldcontext;
871 oldcontext = MemoryContextSwitchTo(ErrorContext);
873 EVALUATE_MESSAGE(detail, false, false);
875 MemoryContextSwitchTo(oldcontext);
877 return 0; /* return value does not matter */
882 * errdetail_log --- add a detail_log error message text to the current error
885 errdetail_log(const char *fmt,...)
887 ErrorData *edata = &errordata[errordata_stack_depth];
888 MemoryContext oldcontext;
892 oldcontext = MemoryContextSwitchTo(ErrorContext);
894 EVALUATE_MESSAGE(detail_log, false, true);
896 MemoryContextSwitchTo(oldcontext);
898 return 0; /* return value does not matter */
903 * errdetail_plural --- add a detail error message text to the current error,
904 * with support for pluralization of the message text
907 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
910 ErrorData *edata = &errordata[errordata_stack_depth];
911 MemoryContext oldcontext;
915 oldcontext = MemoryContextSwitchTo(ErrorContext);
917 EVALUATE_MESSAGE_PLURAL(detail, false);
919 MemoryContextSwitchTo(oldcontext);
921 return 0; /* return value does not matter */
926 * errhint --- add a hint error message text to the current error
929 errhint(const char *fmt,...)
931 ErrorData *edata = &errordata[errordata_stack_depth];
932 MemoryContext oldcontext;
936 oldcontext = MemoryContextSwitchTo(ErrorContext);
938 EVALUATE_MESSAGE(hint, false, true);
940 MemoryContextSwitchTo(oldcontext);
942 return 0; /* return value does not matter */
947 * errcontext --- add a context error message text to the current error
949 * Unlike other cases, multiple calls are allowed to build up a stack of
950 * context information. We assume earlier calls represent more-closely-nested
954 errcontext(const char *fmt,...)
956 ErrorData *edata = &errordata[errordata_stack_depth];
957 MemoryContext oldcontext;
961 oldcontext = MemoryContextSwitchTo(ErrorContext);
963 EVALUATE_MESSAGE(context, true, true);
965 MemoryContextSwitchTo(oldcontext);
967 return 0; /* return value does not matter */
972 * errhidestmt --- optionally suppress STATEMENT: field of log entry
974 * This should be called if the message text already includes the statement.
977 errhidestmt(bool hide_stmt)
979 ErrorData *edata = &errordata[errordata_stack_depth];
981 /* we don't bother incrementing recursion_depth */
984 edata->hide_stmt = hide_stmt;
986 return 0; /* return value does not matter */
991 * errfunction --- add reporting function name to the current error
993 * This is used when backwards compatibility demands that the function
994 * name appear in messages sent to old-protocol clients. Note that the
995 * passed string is expected to be a non-freeable constant string.
998 errfunction(const char *funcname)
1000 ErrorData *edata = &errordata[errordata_stack_depth];
1002 /* we don't bother incrementing recursion_depth */
1003 CHECK_STACK_DEPTH();
1005 edata->funcname = funcname;
1006 edata->show_funcname = true;
1008 return 0; /* return value does not matter */
1012 * errposition --- add cursor position to the current error
1015 errposition(int cursorpos)
1017 ErrorData *edata = &errordata[errordata_stack_depth];
1019 /* we don't bother incrementing recursion_depth */
1020 CHECK_STACK_DEPTH();
1022 edata->cursorpos = cursorpos;
1024 return 0; /* return value does not matter */
1028 * internalerrposition --- add internal cursor position to the current error
1031 internalerrposition(int cursorpos)
1033 ErrorData *edata = &errordata[errordata_stack_depth];
1035 /* we don't bother incrementing recursion_depth */
1036 CHECK_STACK_DEPTH();
1038 edata->internalpos = cursorpos;
1040 return 0; /* return value does not matter */
1044 * internalerrquery --- add internal query text to the current error
1046 * Can also pass NULL to drop the internal query text entry. This case
1047 * is intended for use in error callback subroutines that are editorializing
1048 * on the layout of the error report.
1051 internalerrquery(const char *query)
1053 ErrorData *edata = &errordata[errordata_stack_depth];
1055 /* we don't bother incrementing recursion_depth */
1056 CHECK_STACK_DEPTH();
1058 if (edata->internalquery)
1060 pfree(edata->internalquery);
1061 edata->internalquery = NULL;
1065 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1067 return 0; /* return value does not matter */
1071 * geterrcode --- return the currently set SQLSTATE error code
1073 * This is only intended for use in error callback subroutines, since there
1074 * is no other place outside elog.c where the concept is meaningful.
1079 ErrorData *edata = &errordata[errordata_stack_depth];
1081 /* we don't bother incrementing recursion_depth */
1082 CHECK_STACK_DEPTH();
1084 return edata->sqlerrcode;
1088 * geterrposition --- return the currently set error position (0 if none)
1090 * This is only intended for use in error callback subroutines, since there
1091 * is no other place outside elog.c where the concept is meaningful.
1094 geterrposition(void)
1096 ErrorData *edata = &errordata[errordata_stack_depth];
1098 /* we don't bother incrementing recursion_depth */
1099 CHECK_STACK_DEPTH();
1101 return edata->cursorpos;
1105 * getinternalerrposition --- same for internal error position
1107 * This is only intended for use in error callback subroutines, since there
1108 * is no other place outside elog.c where the concept is meaningful.
1111 getinternalerrposition(void)
1113 ErrorData *edata = &errordata[errordata_stack_depth];
1115 /* we don't bother incrementing recursion_depth */
1116 CHECK_STACK_DEPTH();
1118 return edata->internalpos;
1123 * elog_start --- startup for old-style API
1125 * All that we do here is stash the hidden filename/lineno/funcname
1126 * arguments into a stack entry.
1128 * We need this to be separate from elog_finish because there's no other
1129 * portable way to deal with inserting extra arguments into the elog call.
1130 * (If macros with variable numbers of arguments were portable, it'd be
1131 * easy, but they aren't.)
1134 elog_start(const char *filename, int lineno, const char *funcname)
1138 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1141 * Wups, stack not big enough. We treat this as a PANIC condition
1142 * because it suggests an infinite loop of errors during error
1143 * recovery. Note that the message is intentionally not localized,
1144 * else failure to convert it to client encoding could cause further
1147 errordata_stack_depth = -1; /* make room on stack */
1148 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1151 edata = &errordata[errordata_stack_depth];
1156 /* keep only base name, useful especially for vpath builds */
1157 slash = strrchr(filename, '/');
1158 edata->filename = slash ? slash + 1 : filename;
1160 edata->lineno = lineno;
1161 edata->funcname = funcname;
1162 /* errno is saved now so that error parameter eval can't change it */
1163 edata->saved_errno = errno;
1167 * elog_finish --- finish up for old-style API
1170 elog_finish(int elevel, const char *fmt,...)
1172 ErrorData *edata = &errordata[errordata_stack_depth];
1173 MemoryContext oldcontext;
1175 CHECK_STACK_DEPTH();
1178 * Do errstart() to see if we actually want to report the message.
1180 errordata_stack_depth--;
1181 errno = edata->saved_errno;
1182 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1183 return; /* nothing to do */
1186 * Format error message just like errmsg_internal().
1189 oldcontext = MemoryContextSwitchTo(ErrorContext);
1191 EVALUATE_MESSAGE(message, false, false);
1193 MemoryContextSwitchTo(oldcontext);
1197 * And let errfinish() finish up.
1204 * Functions to allow construction of error message strings separately from
1205 * the ereport() call itself.
1207 * The expected calling convention is
1209 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1211 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1212 * assume that any functions called in the arguments of format_elog_string()
1213 * cannot result in re-entrant use of these functions --- otherwise the wrong
1214 * text domain might be used, or the wrong errno substituted for %m. This is
1215 * okay for the current usage with GUC check hooks, but might need further
1218 * The result of format_elog_string() is stored in ErrorContext, and will
1219 * therefore survive until FlushErrorState() is called.
1221 static int save_format_errnumber;
1222 static const char *save_format_domain;
1225 pre_format_elog_string(int errnumber, const char *domain)
1227 /* Save errno before evaluation of argument functions can change it */
1228 save_format_errnumber = errnumber;
1229 /* Save caller's text domain */
1230 save_format_domain = domain;
1234 format_elog_string(const char *fmt,...)
1238 MemoryContext oldcontext;
1240 /* Initialize a mostly-dummy error frame */
1242 MemSet(edata, 0, sizeof(ErrorData));
1243 /* the default text domain is the backend's */
1244 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1245 /* set the errno to be used to interpret %m */
1246 edata->saved_errno = save_format_errnumber;
1248 oldcontext = MemoryContextSwitchTo(ErrorContext);
1250 EVALUATE_MESSAGE(message, false, true);
1252 MemoryContextSwitchTo(oldcontext);
1254 return edata->message;
1259 * Actual output of the top-of-stack error message
1261 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1262 * if the error is caught by somebody). For all other severity levels this
1263 * is called by errfinish.
1266 EmitErrorReport(void)
1268 ErrorData *edata = &errordata[errordata_stack_depth];
1269 MemoryContext oldcontext;
1272 CHECK_STACK_DEPTH();
1273 oldcontext = MemoryContextSwitchTo(ErrorContext);
1275 /* Send to server log, if enabled */
1276 if (edata->output_to_server)
1277 send_message_to_server_log(edata);
1279 /* Send to client, if enabled */
1280 if (edata->output_to_client)
1281 send_message_to_frontend(edata);
1283 MemoryContextSwitchTo(oldcontext);
1288 * CopyErrorData --- obtain a copy of the topmost error stack entry
1290 * This is only for use in error handler code. The data is copied into the
1291 * current memory context, so callers should always switch away from
1292 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1297 ErrorData *edata = &errordata[errordata_stack_depth];
1298 ErrorData *newedata;
1301 * we don't increment recursion_depth because out-of-memory here does not
1302 * indicate a problem within the error subsystem.
1304 CHECK_STACK_DEPTH();
1306 Assert(CurrentMemoryContext != ErrorContext);
1308 /* Copy the struct itself */
1309 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1310 memcpy(newedata, edata, sizeof(ErrorData));
1312 /* Make copies of separately-allocated fields */
1313 if (newedata->message)
1314 newedata->message = pstrdup(newedata->message);
1315 if (newedata->detail)
1316 newedata->detail = pstrdup(newedata->detail);
1317 if (newedata->detail_log)
1318 newedata->detail_log = pstrdup(newedata->detail_log);
1320 newedata->hint = pstrdup(newedata->hint);
1321 if (newedata->context)
1322 newedata->context = pstrdup(newedata->context);
1323 if (newedata->internalquery)
1324 newedata->internalquery = pstrdup(newedata->internalquery);
1330 * FreeErrorData --- free the structure returned by CopyErrorData.
1332 * Error handlers should use this in preference to assuming they know all
1333 * the separately-allocated fields.
1336 FreeErrorData(ErrorData *edata)
1339 pfree(edata->message);
1341 pfree(edata->detail);
1342 if (edata->detail_log)
1343 pfree(edata->detail_log);
1347 pfree(edata->context);
1348 if (edata->internalquery)
1349 pfree(edata->internalquery);
1354 * FlushErrorState --- flush the error state after error recovery
1356 * This should be called by an error handler after it's done processing
1357 * the error; or as soon as it's done CopyErrorData, if it intends to
1358 * do stuff that is likely to provoke another error. You are not "out" of
1359 * the error subsystem until you have done this.
1362 FlushErrorState(void)
1365 * Reset stack to empty. The only case where it would be more than one
1366 * deep is if we serviced an error that interrupted construction of
1367 * another message. We assume control escaped out of that message
1368 * construction and won't ever go back.
1370 errordata_stack_depth = -1;
1371 recursion_depth = 0;
1372 /* Delete all data in ErrorContext */
1373 MemoryContextResetAndDeleteChildren(ErrorContext);
1377 * ReThrowError --- re-throw a previously copied error
1379 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1380 * subsystem, then do some processing, and finally ReThrowError to re-throw
1381 * the original error. This is slower than just PG_RE_THROW() but should
1382 * be used if the "some processing" is likely to incur another error.
1385 ReThrowError(ErrorData *edata)
1387 ErrorData *newedata;
1389 Assert(edata->elevel == ERROR);
1391 /* Push the data back into the error context */
1393 MemoryContextSwitchTo(ErrorContext);
1395 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1398 * Wups, stack not big enough. We treat this as a PANIC condition
1399 * because it suggests an infinite loop of errors during error
1402 errordata_stack_depth = -1; /* make room on stack */
1403 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1406 newedata = &errordata[errordata_stack_depth];
1407 memcpy(newedata, edata, sizeof(ErrorData));
1409 /* Make copies of separately-allocated fields */
1410 if (newedata->message)
1411 newedata->message = pstrdup(newedata->message);
1412 if (newedata->detail)
1413 newedata->detail = pstrdup(newedata->detail);
1414 if (newedata->detail_log)
1415 newedata->detail_log = pstrdup(newedata->detail_log);
1417 newedata->hint = pstrdup(newedata->hint);
1418 if (newedata->context)
1419 newedata->context = pstrdup(newedata->context);
1420 if (newedata->internalquery)
1421 newedata->internalquery = pstrdup(newedata->internalquery);
1428 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1433 /* If possible, throw the error to the next outer setjmp handler */
1434 if (PG_exception_stack != NULL)
1435 siglongjmp(*PG_exception_stack, 1);
1439 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1440 * we have now exited only to discover that there is no outer setjmp
1441 * handler to pass the error to. Had the error been thrown outside
1442 * the block to begin with, we'd have promoted the error to FATAL, so
1443 * the correct behavior is to make it FATAL now; that is, emit it and
1444 * then call proc_exit.
1446 ErrorData *edata = &errordata[errordata_stack_depth];
1448 Assert(errordata_stack_depth >= 0);
1449 Assert(edata->elevel == ERROR);
1450 edata->elevel = FATAL;
1453 * At least in principle, the increase in severity could have changed
1454 * where-to-output decisions, so recalculate. This should stay in
1455 * sync with errstart(), which see for comments.
1457 if (IsPostmasterEnvironment)
1458 edata->output_to_server = is_log_level_output(FATAL,
1461 edata->output_to_server = (FATAL >= log_min_messages);
1462 if (whereToSendOutput == DestRemote)
1464 if (ClientAuthInProgress)
1465 edata->output_to_client = true;
1467 edata->output_to_client = (FATAL >= client_min_messages);
1471 * We can use errfinish() for the rest, but we don't want it to call
1472 * any error context routines a second time. Since we know we are
1473 * about to exit, it should be OK to just clear the context stack.
1475 error_context_stack = NULL;
1480 /* We mustn't return... */
1481 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1482 __FILE__, __LINE__);
1485 * Since ExceptionalCondition isn't declared noreturn because of
1486 * TrapMacro(), we need this to keep gcc from complaining.
1493 * Initialization of error output file
1501 if (OutputFileName[0])
1504 * A debug-output file name was given.
1506 * Make sure we can write the file, and find out if it's a tty.
1508 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1511 (errcode_for_file_access(),
1512 errmsg("could not open file \"%s\": %m", OutputFileName)));
1517 * Redirect our stderr to the debug output file.
1519 if (!freopen(OutputFileName, "a", stderr))
1521 (errcode_for_file_access(),
1522 errmsg("could not reopen file \"%s\" as stderr: %m",
1526 * If the file is a tty and we're running under the postmaster, try to
1527 * send stdout there as well (if it isn't a tty then stderr will block
1528 * out stdout, so we may as well let stdout go wherever it was going
1531 if (istty && IsUnderPostmaster)
1532 if (!freopen(OutputFileName, "a", stdout))
1534 (errcode_for_file_access(),
1535 errmsg("could not reopen file \"%s\" as stdout: %m",
1544 * Set or update the parameters for syslog logging
1547 set_syslog_parameters(const char *ident, int facility)
1550 * guc.c is likely to call us repeatedly with same parameters, so don't
1551 * thrash the syslog connection unnecessarily. Also, we do not re-open
1552 * the connection until needed, since this routine will get called whether
1553 * or not Log_destination actually mentions syslog.
1555 * Note that we make our own copy of the ident string rather than relying
1556 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1557 * accidentally free a string that syslog is still using.
1559 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1560 syslog_facility != facility)
1565 openlog_done = false;
1569 syslog_ident = strdup(ident);
1570 /* if the strdup fails, we will cope in write_syslog() */
1571 syslog_facility = facility;
1577 * Write a message line to syslog
1580 write_syslog(int level, const char *line)
1582 static unsigned long seq = 0;
1587 /* Open syslog connection if not done yet */
1590 openlog(syslog_ident ? syslog_ident : "postgres",
1591 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1593 openlog_done = true;
1597 * We add a sequence number to each log message to suppress "same"
1603 * Our problem here is that many syslog implementations don't handle long
1604 * messages in an acceptable manner. While this function doesn't help that
1605 * fact, it does work around by splitting up messages into smaller pieces.
1607 * We divide into multiple syslog() calls if message is too long or if the
1608 * message contains embedded newline(s).
1611 nlpos = strchr(line, '\n');
1612 if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1618 char buf[PG_SYSLOG_LIMIT + 1];
1622 /* if we start at a newline, move ahead one char */
1623 if (line[0] == '\n')
1627 /* we need to recompute the next newline's position, too */
1628 nlpos = strchr(line, '\n');
1632 /* copy one line, or as much as will fit, to buf */
1634 buflen = nlpos - line;
1637 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1638 memcpy(buf, line, buflen);
1641 /* trim to multibyte letter boundary */
1642 buflen = pg_mbcliplen(buf, buflen, buflen);
1647 /* already word boundary? */
1648 if (line[buflen] != '\0' &&
1649 !isspace((unsigned char) line[buflen]))
1651 /* try to divide at word boundary */
1653 while (i > 0 && !isspace((unsigned char) buf[i]))
1656 if (i > 0) /* else couldn't divide word boundary */
1665 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1672 /* message short enough */
1673 syslog(level, "[%lu] %s", seq, line);
1676 #endif /* HAVE_SYSLOG */
1680 * Write a message line to the windows event log
1683 write_eventlog(int level, const char *line, int len)
1686 int eventlevel = EVENTLOG_ERROR_TYPE;
1687 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1689 if (evtHandle == INVALID_HANDLE_VALUE)
1691 evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
1692 if (evtHandle == NULL)
1694 evtHandle = INVALID_HANDLE_VALUE;
1710 eventlevel = EVENTLOG_INFORMATION_TYPE;
1713 eventlevel = EVENTLOG_WARNING_TYPE;
1719 eventlevel = EVENTLOG_ERROR_TYPE;
1724 * Convert message to UTF16 text and write it with ReportEventW, but
1725 * fall-back into ReportEventA if conversion failed.
1727 * Also verify that we are not on our way into error recursion trouble due
1728 * to error messages thrown deep inside pgwin32_toUTF16().
1730 if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1731 !in_error_recursion_trouble())
1733 utf16 = pgwin32_toUTF16(line, len, NULL);
1736 ReportEventW(evtHandle,
1739 0, /* All events are Id 0 */
1750 ReportEventA(evtHandle,
1753 0, /* All events are Id 0 */
1763 write_console(const char *line, int len)
1770 * WriteConsoleW() will fail if stdout is redirected, so just fall through
1771 * to writing unconverted to the logfile in this case.
1773 * Since we palloc the structure required for conversion, also fall
1774 * through to writing unconverted if we have not yet set up
1775 * CurrentMemoryContext.
1777 if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1778 !in_error_recursion_trouble() &&
1779 !redirection_done &&
1780 CurrentMemoryContext != NULL)
1785 utf16 = pgwin32_toUTF16(line, len, &utf16len);
1791 stdHandle = GetStdHandle(STD_ERROR_HANDLE);
1792 if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
1799 * In case WriteConsoleW() failed, fall back to writing the
1800 * message unconverted.
1808 * Conversion on non-win32 platforms is not implemented yet. It requires
1809 * non-throw version of pg_do_encoding_conversion(), that converts
1810 * unconvertable characters to '?' without errors.
1815 * We ignore any error from write() here. We have no useful way to report
1816 * it ... certainly whining on stderr isn't likely to be productive.
1818 rc = write(fileno(stderr), line, len);
1823 * setup formatted_log_time, for consistent times between CSV and regular logs
1826 setup_formatted_log_time(void)
1829 pg_time_t stamp_time;
1832 gettimeofday(&tv, NULL);
1833 stamp_time = (pg_time_t) tv.tv_sec;
1836 * Note: we expect that guc.c will ensure that log_timezone is set up
1837 * (at least with a minimal GMT value) before Log_line_prefix can become
1838 * nonempty or CSV mode can be selected.
1840 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1841 /* leave room for milliseconds... */
1842 "%Y-%m-%d %H:%M:%S %Z",
1843 pg_localtime(&stamp_time, log_timezone));
1845 /* 'paste' milliseconds into place... */
1846 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1847 strncpy(formatted_log_time + 19, msbuf, 4);
1851 * setup formatted_start_time
1854 setup_formatted_start_time(void)
1856 pg_time_t stamp_time = (pg_time_t) MyStartTime;
1859 * Note: we expect that guc.c will ensure that log_timezone is set up
1860 * (at least with a minimal GMT value) before Log_line_prefix can become
1861 * nonempty or CSV mode can be selected.
1863 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1864 "%Y-%m-%d %H:%M:%S %Z",
1865 pg_localtime(&stamp_time, log_timezone));
1869 * Format tag info for log lines; append to the provided buffer.
1872 log_line_prefix(StringInfo buf, ErrorData *edata)
1874 /* static counter for line numbers */
1875 static long log_line_number = 0;
1877 /* has counter been reset in current process? */
1878 static int log_my_pid = 0;
1884 * This is one of the few places where we'd rather not inherit a static
1885 * variable's value from the postmaster. But since we will, reset it when
1886 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1887 * reset the formatted start timestamp too.
1889 if (log_my_pid != MyProcPid)
1891 log_line_number = 0;
1892 log_my_pid = MyProcPid;
1893 formatted_start_time[0] = '\0';
1897 if (Log_line_prefix == NULL)
1898 return; /* in case guc hasn't run yet */
1900 format_len = strlen(Log_line_prefix);
1902 for (i = 0; i < format_len; i++)
1904 if (Log_line_prefix[i] != '%')
1906 /* literal char, just copy */
1907 appendStringInfoChar(buf, Log_line_prefix[i]);
1910 /* go to char after '%' */
1912 if (i >= format_len)
1913 break; /* format error - ignore it */
1915 /* process the option */
1916 switch (Log_line_prefix[i])
1921 const char *appname = application_name;
1923 if (appname == NULL || *appname == '\0')
1924 appname = _("[unknown]");
1925 appendStringInfoString(buf, appname);
1931 const char *username = MyProcPort->user_name;
1933 if (username == NULL || *username == '\0')
1934 username = _("[unknown]");
1935 appendStringInfoString(buf, username);
1941 const char *dbname = MyProcPort->database_name;
1943 if (dbname == NULL || *dbname == '\0')
1944 dbname = _("[unknown]");
1945 appendStringInfoString(buf, dbname);
1949 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1952 appendStringInfo(buf, "%d", MyProcPid);
1955 appendStringInfo(buf, "%ld", log_line_number);
1958 setup_formatted_log_time();
1959 appendStringInfoString(buf, formatted_log_time);
1963 pg_time_t stamp_time = (pg_time_t) time(NULL);
1966 pg_strftime(strfbuf, sizeof(strfbuf),
1967 "%Y-%m-%d %H:%M:%S %Z",
1968 pg_localtime(&stamp_time, log_timezone));
1969 appendStringInfoString(buf, strfbuf);
1973 if (formatted_start_time[0] == '\0')
1974 setup_formatted_start_time();
1975 appendStringInfoString(buf, formatted_start_time);
1983 psdisp = get_ps_display(&displen);
1984 appendBinaryStringInfo(buf, psdisp, displen);
1988 if (MyProcPort && MyProcPort->remote_host)
1990 appendStringInfoString(buf, MyProcPort->remote_host);
1991 if (MyProcPort->remote_port &&
1992 MyProcPort->remote_port[0] != '\0')
1993 appendStringInfo(buf, "(%s)",
1994 MyProcPort->remote_port);
1998 if (MyProcPort && MyProcPort->remote_host)
1999 appendStringInfoString(buf, MyProcPort->remote_host);
2002 /* in postmaster and friends, stop if %q is seen */
2003 /* in a backend, just ignore */
2004 if (MyProcPort == NULL)
2008 /* keep VXID format in sync with lockfuncs.c */
2009 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2010 appendStringInfo(buf, "%d/%u",
2011 MyProc->backendId, MyProc->lxid);
2014 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2017 appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2020 appendStringInfoChar(buf, '%');
2023 /* format error - ignore it */
2030 * append a CSV'd version of a string to a StringInfo
2031 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2032 * If it's NULL, append nothing.
2035 appendCSVLiteral(StringInfo buf, const char *data)
2037 const char *p = data;
2040 /* avoid confusing an empty string with NULL */
2044 appendStringInfoCharMacro(buf, '"');
2045 while ((c = *p++) != '\0')
2048 appendStringInfoCharMacro(buf, '"');
2049 appendStringInfoCharMacro(buf, c);
2051 appendStringInfoCharMacro(buf, '"');
2055 * Constructs the error message, depending on the Errordata it gets, in a CSV
2056 * format which is described in doc/src/sgml/config.sgml.
2059 write_csvlog(ErrorData *edata)
2062 bool print_stmt = false;
2064 /* static counter for line numbers */
2065 static long log_line_number = 0;
2067 /* has counter been reset in current process? */
2068 static int log_my_pid = 0;
2071 * This is one of the few places where we'd rather not inherit a static
2072 * variable's value from the postmaster. But since we will, reset it when
2073 * MyProcPid changes.
2075 if (log_my_pid != MyProcPid)
2077 log_line_number = 0;
2078 log_my_pid = MyProcPid;
2079 formatted_start_time[0] = '\0';
2083 initStringInfo(&buf);
2086 * timestamp with milliseconds
2088 * Check if the timestamp is already calculated for the syslog message,
2089 * and use it if so. Otherwise, get the current timestamp. This is done
2090 * to put same timestamp in both syslog and csvlog messages.
2092 if (formatted_log_time[0] == '\0')
2093 setup_formatted_log_time();
2095 appendStringInfoString(&buf, formatted_log_time);
2096 appendStringInfoChar(&buf, ',');
2100 appendCSVLiteral(&buf, MyProcPort->user_name);
2101 appendStringInfoChar(&buf, ',');
2105 appendCSVLiteral(&buf, MyProcPort->database_name);
2106 appendStringInfoChar(&buf, ',');
2110 appendStringInfo(&buf, "%d", MyProcPid);
2111 appendStringInfoChar(&buf, ',');
2113 /* Remote host and port */
2114 if (MyProcPort && MyProcPort->remote_host)
2116 appendStringInfoChar(&buf, '"');
2117 appendStringInfoString(&buf, MyProcPort->remote_host);
2118 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2120 appendStringInfoChar(&buf, ':');
2121 appendStringInfoString(&buf, MyProcPort->remote_port);
2123 appendStringInfoChar(&buf, '"');
2125 appendStringInfoChar(&buf, ',');
2128 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2129 appendStringInfoChar(&buf, ',');
2132 appendStringInfo(&buf, "%ld", log_line_number);
2133 appendStringInfoChar(&buf, ',');
2138 StringInfoData msgbuf;
2142 initStringInfo(&msgbuf);
2144 psdisp = get_ps_display(&displen);
2145 appendBinaryStringInfo(&msgbuf, psdisp, displen);
2146 appendCSVLiteral(&buf, msgbuf.data);
2150 appendStringInfoChar(&buf, ',');
2152 /* session start timestamp */
2153 if (formatted_start_time[0] == '\0')
2154 setup_formatted_start_time();
2155 appendStringInfoString(&buf, formatted_start_time);
2156 appendStringInfoChar(&buf, ',');
2158 /* Virtual transaction id */
2159 /* keep VXID format in sync with lockfuncs.c */
2160 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2161 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2162 appendStringInfoChar(&buf, ',');
2164 /* Transaction id */
2165 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2166 appendStringInfoChar(&buf, ',');
2168 /* Error severity */
2169 appendStringInfoString(&buf, error_severity(edata->elevel));
2170 appendStringInfoChar(&buf, ',');
2172 /* SQL state code */
2173 appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2174 appendStringInfoChar(&buf, ',');
2177 appendCSVLiteral(&buf, edata->message);
2178 appendStringInfoChar(&buf, ',');
2180 /* errdetail or errdetail_log */
2181 if (edata->detail_log)
2182 appendCSVLiteral(&buf, edata->detail_log);
2184 appendCSVLiteral(&buf, edata->detail);
2185 appendStringInfoChar(&buf, ',');
2188 appendCSVLiteral(&buf, edata->hint);
2189 appendStringInfoChar(&buf, ',');
2191 /* internal query */
2192 appendCSVLiteral(&buf, edata->internalquery);
2193 appendStringInfoChar(&buf, ',');
2195 /* if printed internal query, print internal pos too */
2196 if (edata->internalpos > 0 && edata->internalquery != NULL)
2197 appendStringInfo(&buf, "%d", edata->internalpos);
2198 appendStringInfoChar(&buf, ',');
2201 appendCSVLiteral(&buf, edata->context);
2202 appendStringInfoChar(&buf, ',');
2204 /* user query --- only reported if not disabled by the caller */
2205 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2206 debug_query_string != NULL &&
2210 appendCSVLiteral(&buf, debug_query_string);
2211 appendStringInfoChar(&buf, ',');
2212 if (print_stmt && edata->cursorpos > 0)
2213 appendStringInfo(&buf, "%d", edata->cursorpos);
2214 appendStringInfoChar(&buf, ',');
2216 /* file error location */
2217 if (Log_error_verbosity >= PGERROR_VERBOSE)
2219 StringInfoData msgbuf;
2221 initStringInfo(&msgbuf);
2223 if (edata->funcname && edata->filename)
2224 appendStringInfo(&msgbuf, "%s, %s:%d",
2225 edata->funcname, edata->filename,
2227 else if (edata->filename)
2228 appendStringInfo(&msgbuf, "%s:%d",
2229 edata->filename, edata->lineno);
2230 appendCSVLiteral(&buf, msgbuf.data);
2233 appendStringInfoChar(&buf, ',');
2235 /* application name */
2236 if (application_name)
2237 appendCSVLiteral(&buf, application_name);
2239 appendStringInfoChar(&buf, '\n');
2241 /* If in the syslogger process, try to write messages direct to file */
2243 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2245 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2251 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2255 unpack_sql_state(int sql_state)
2257 static char buf[12];
2260 for (i = 0; i < 5; i++)
2262 buf[i] = PGUNSIXBIT(sql_state);
2272 * Write error report to server's log
2275 send_message_to_server_log(ErrorData *edata)
2279 initStringInfo(&buf);
2281 formatted_log_time[0] = '\0';
2283 log_line_prefix(&buf, edata);
2284 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2286 if (Log_error_verbosity >= PGERROR_VERBOSE)
2287 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2290 append_with_tabs(&buf, edata->message);
2292 append_with_tabs(&buf, _("missing error text"));
2294 if (edata->cursorpos > 0)
2295 appendStringInfo(&buf, _(" at character %d"),
2297 else if (edata->internalpos > 0)
2298 appendStringInfo(&buf, _(" at character %d"),
2299 edata->internalpos);
2301 appendStringInfoChar(&buf, '\n');
2303 if (Log_error_verbosity >= PGERROR_DEFAULT)
2305 if (edata->detail_log)
2307 log_line_prefix(&buf, edata);
2308 appendStringInfoString(&buf, _("DETAIL: "));
2309 append_with_tabs(&buf, edata->detail_log);
2310 appendStringInfoChar(&buf, '\n');
2312 else if (edata->detail)
2314 log_line_prefix(&buf, edata);
2315 appendStringInfoString(&buf, _("DETAIL: "));
2316 append_with_tabs(&buf, edata->detail);
2317 appendStringInfoChar(&buf, '\n');
2321 log_line_prefix(&buf, edata);
2322 appendStringInfoString(&buf, _("HINT: "));
2323 append_with_tabs(&buf, edata->hint);
2324 appendStringInfoChar(&buf, '\n');
2326 if (edata->internalquery)
2328 log_line_prefix(&buf, edata);
2329 appendStringInfoString(&buf, _("QUERY: "));
2330 append_with_tabs(&buf, edata->internalquery);
2331 appendStringInfoChar(&buf, '\n');
2335 log_line_prefix(&buf, edata);
2336 appendStringInfoString(&buf, _("CONTEXT: "));
2337 append_with_tabs(&buf, edata->context);
2338 appendStringInfoChar(&buf, '\n');
2340 if (Log_error_verbosity >= PGERROR_VERBOSE)
2342 /* assume no newlines in funcname or filename... */
2343 if (edata->funcname && edata->filename)
2345 log_line_prefix(&buf, edata);
2346 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2347 edata->funcname, edata->filename,
2350 else if (edata->filename)
2352 log_line_prefix(&buf, edata);
2353 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2354 edata->filename, edata->lineno);
2360 * If the user wants the query that generated this error logged, do it.
2362 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2363 debug_query_string != NULL &&
2366 log_line_prefix(&buf, edata);
2367 appendStringInfoString(&buf, _("STATEMENT: "));
2368 append_with_tabs(&buf, debug_query_string);
2369 appendStringInfoChar(&buf, '\n');
2373 /* Write to syslog, if enabled */
2374 if (Log_destination & LOG_DESTINATION_SYSLOG)
2378 switch (edata->elevel)
2385 syslog_level = LOG_DEBUG;
2390 syslog_level = LOG_INFO;
2394 syslog_level = LOG_NOTICE;
2397 syslog_level = LOG_WARNING;
2400 syslog_level = LOG_ERR;
2404 syslog_level = LOG_CRIT;
2408 write_syslog(syslog_level, buf.data);
2410 #endif /* HAVE_SYSLOG */
2413 /* Write to eventlog, if enabled */
2414 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2416 write_eventlog(edata->elevel, buf.data, buf.len);
2420 /* Write to stderr, if enabled */
2421 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2424 * Use the chunking protocol if we know the syslogger should be
2425 * catching stderr output, and we are not ourselves the syslogger.
2426 * Otherwise, just do a vanilla write to stderr.
2428 if (redirection_done && !am_syslogger)
2429 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2433 * In a win32 service environment, there is no usable stderr. Capture
2434 * anything going there and write it to the eventlog instead.
2436 * If stderr redirection is active, it was OK to write to stderr above
2437 * because that's really a pipe to the syslogger process.
2439 else if (pgwin32_is_service())
2440 write_eventlog(edata->elevel, buf.data, buf.len);
2443 write_console(buf.data, buf.len);
2446 /* If in the syslogger process, try to write messages direct to file */
2448 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2450 /* Write to CSV log if enabled */
2451 if (Log_destination & LOG_DESTINATION_CSVLOG)
2453 if (redirection_done || am_syslogger)
2456 * send CSV data if it's safe to do so (syslogger doesn't need the
2457 * pipe). First get back the space in the message buffer.
2460 write_csvlog(edata);
2465 * syslogger not up (yet), so just dump the message to stderr,
2466 * unless we already did so above.
2468 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2469 whereToSendOutput != DestDebug)
2470 write_console(buf.data, buf.len);
2481 * Send data to the syslogger using the chunked protocol
2483 * Note: when there are multiple backends writing into the syslogger pipe,
2484 * it's critical that each write go into the pipe indivisibly, and not
2485 * get interleaved with data from other processes. Fortunately, the POSIX
2486 * spec requires that writes to pipes be atomic so long as they are not
2487 * more than PIPE_BUF bytes long. So we divide long messages into chunks
2488 * that are no more than that length, and send one chunk per write() call.
2489 * The collector process knows how to reassemble the chunks.
2491 * Because of the atomic write requirement, there are only two possible
2492 * results from write() here: -1 for failure, or the requested number of
2493 * bytes. There is not really anything we can do about a failure; retry would
2494 * probably be an infinite loop, and we can't even report the error usefully.
2495 * (There is noplace else we could send it!) So we might as well just ignore
2496 * the result from write(). However, on some platforms you get a compiler
2497 * warning from ignoring write()'s result, so do a little dance with casting
2498 * rc to void to shut up the compiler.
2501 write_pipe_chunks(char *data, int len, int dest)
2504 int fd = fileno(stderr);
2509 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2510 p.proto.pid = MyProcPid;
2512 /* write all but the last chunk */
2513 while (len > PIPE_MAX_PAYLOAD)
2515 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2516 p.proto.len = PIPE_MAX_PAYLOAD;
2517 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2518 rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2520 data += PIPE_MAX_PAYLOAD;
2521 len -= PIPE_MAX_PAYLOAD;
2524 /* write the last chunk */
2525 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2527 memcpy(p.proto.data, data, len);
2528 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
2534 * Append a text string to the error report being built for the client.
2536 * This is ordinarily identical to pq_sendstring(), but if we are in
2537 * error recursion trouble we skip encoding conversion, because of the
2538 * possibility that the problem is a failure in the encoding conversion
2539 * subsystem itself. Code elsewhere should ensure that the passed-in
2540 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2541 * in such cases. (In particular, we disable localization of error messages
2542 * to help ensure that's true.)
2545 err_sendstring(StringInfo buf, const char *str)
2547 if (in_error_recursion_trouble())
2548 pq_send_ascii_string(buf, str);
2550 pq_sendstring(buf, str);
2554 * Write error report to client
2557 send_message_to_frontend(ErrorData *edata)
2559 StringInfoData msgbuf;
2561 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2562 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2564 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2566 /* New style with separate fields */
2571 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2572 err_sendstring(&msgbuf, error_severity(edata->elevel));
2574 /* unpack MAKE_SQLSTATE code */
2575 ssval = edata->sqlerrcode;
2576 for (i = 0; i < 5; i++)
2578 tbuf[i] = PGUNSIXBIT(ssval);
2583 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2584 err_sendstring(&msgbuf, tbuf);
2586 /* M field is required per protocol, so always send something */
2587 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2589 err_sendstring(&msgbuf, edata->message);
2591 err_sendstring(&msgbuf, _("missing error text"));
2595 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2596 err_sendstring(&msgbuf, edata->detail);
2599 /* detail_log is intentionally not used here */
2603 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2604 err_sendstring(&msgbuf, edata->hint);
2609 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2610 err_sendstring(&msgbuf, edata->context);
2613 if (edata->cursorpos > 0)
2615 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2616 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2617 err_sendstring(&msgbuf, tbuf);
2620 if (edata->internalpos > 0)
2622 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2623 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2624 err_sendstring(&msgbuf, tbuf);
2627 if (edata->internalquery)
2629 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2630 err_sendstring(&msgbuf, edata->internalquery);
2633 if (edata->filename)
2635 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2636 err_sendstring(&msgbuf, edata->filename);
2639 if (edata->lineno > 0)
2641 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2642 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2643 err_sendstring(&msgbuf, tbuf);
2646 if (edata->funcname)
2648 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2649 err_sendstring(&msgbuf, edata->funcname);
2652 pq_sendbyte(&msgbuf, '\0'); /* terminator */
2656 /* Old style --- gin up a backwards-compatible message */
2659 initStringInfo(&buf);
2661 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2663 if (edata->show_funcname && edata->funcname)
2664 appendStringInfo(&buf, "%s: ", edata->funcname);
2667 appendStringInfoString(&buf, edata->message);
2669 appendStringInfoString(&buf, _("missing error text"));
2671 if (edata->cursorpos > 0)
2672 appendStringInfo(&buf, _(" at character %d"),
2674 else if (edata->internalpos > 0)
2675 appendStringInfo(&buf, _(" at character %d"),
2676 edata->internalpos);
2678 appendStringInfoChar(&buf, '\n');
2680 err_sendstring(&msgbuf, buf.data);
2685 pq_endmessage(&msgbuf);
2688 * This flush is normally not necessary, since postgres.c will flush out
2689 * waiting data when control returns to the main loop. But it seems best
2690 * to leave it here, so that the client has some clue what happened if the
2691 * backend dies before getting back to the main loop ... error/notice
2692 * messages should not be a performance-critical path anyway, so an extra
2693 * flush won't hurt much ...
2700 * Support routines for formatting error messages.
2705 * expand_fmt_string --- process special format codes in a format string
2707 * We must replace %m with the appropriate strerror string, since vsnprintf
2708 * won't know what to do with it.
2710 * The result is a palloc'd string.
2713 expand_fmt_string(const char *fmt, ErrorData *edata)
2718 initStringInfo(&buf);
2720 for (cp = fmt; *cp; cp++)
2722 if (cp[0] == '%' && cp[1] != '\0')
2728 * Replace %m by system error string. If there are any %'s in
2729 * the string, we'd better double them so that vsnprintf won't
2734 cp2 = useful_strerror(edata->saved_errno);
2738 appendStringInfoCharMacro(&buf, '%');
2739 appendStringInfoCharMacro(&buf, *cp2);
2744 /* copy % and next char --- this avoids trouble with %%m */
2745 appendStringInfoCharMacro(&buf, '%');
2746 appendStringInfoCharMacro(&buf, *cp);
2750 appendStringInfoCharMacro(&buf, *cp);
2758 * A slightly cleaned-up version of strerror()
2761 useful_strerror(int errnum)
2763 /* this buffer is only used if errno has a bogus value */
2764 static char errorstr_buf[48];
2768 /* Winsock error code range, per WinError.h */
2769 if (errnum >= 10000 && errnum <= 11999)
2770 return pgwin32_socket_strerror(errnum);
2772 str = strerror(errnum);
2775 * Some strerror()s return an empty string for out-of-range errno. This is
2776 * ANSI C spec compliant, but not exactly useful.
2778 if (str == NULL || *str == '\0')
2780 snprintf(errorstr_buf, sizeof(errorstr_buf),
2782 translator: This string will be truncated at 47
2783 characters expanded. */
2784 _("operating system error %d"), errnum);
2793 * error_severity --- get localized string representing elevel
2796 error_severity(int elevel)
2807 prefix = _("DEBUG");
2817 prefix = _("NOTICE");
2820 prefix = _("WARNING");
2823 prefix = _("ERROR");
2826 prefix = _("FATAL");
2829 prefix = _("PANIC");
2843 * Append the string to the StringInfo buffer, inserting a tab after any
2847 append_with_tabs(StringInfo buf, const char *str)
2851 while ((ch = *str++) != '\0')
2853 appendStringInfoCharMacro(buf, ch);
2855 appendStringInfoCharMacro(buf, '\t');
2861 * Write errors to stderr (or by equal means when stderr is
2862 * not available). Used before ereport/elog can be used
2863 * safely (memory context, GUC load etc)
2866 write_stderr(const char *fmt,...)
2871 char errbuf[2048]; /* Arbitrary size? */
2878 /* On Unix, we just fprintf to stderr */
2879 vfprintf(stderr, fmt, ap);
2882 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2885 * On Win32, we print to stderr if running on a console, or write to
2886 * eventlog if running as a service
2888 if (pgwin32_is_service()) /* Running as a service */
2890 write_eventlog(ERROR, errbuf, strlen(errbuf));
2894 /* Not running as service, write to stderr */
2895 write_console(errbuf, strlen(errbuf));
2904 * is_log_level_output -- is elevel logically >= log_min_level?
2906 * We use this for tests that should consider LOG to sort out-of-order,
2907 * between ERROR and FATAL. Generally this is the right thing for testing
2908 * whether a message should go to the postmaster log, whereas a simple >=
2909 * test is correct for testing whether the message should go to the client.
2912 is_log_level_output(int elevel, int log_min_level)
2914 if (elevel == LOG || elevel == COMMERROR)
2916 if (log_min_level == LOG || log_min_level <= ERROR)
2919 else if (log_min_level == LOG)
2922 if (elevel >= FATAL)
2925 /* Neither is LOG */
2926 else if (elevel >= log_min_level)
2933 * Adjust the level of a recovery-related message per trace_recovery_messages.
2935 * The argument is the default log level of the message, eg, DEBUG2. (This
2936 * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
2937 * If the level is >= trace_recovery_messages, we return LOG, causing the
2938 * message to be logged unconditionally (for most settings of
2939 * log_min_messages). Otherwise, we return the argument unchanged.
2940 * The message will then be shown based on the setting of log_min_messages.
2942 * Intention is to keep this for at least the whole of the 9.0 production
2943 * release, so we can more easily diagnose production problems in the field.
2944 * It should go away eventually, though, because it's an ugly and
2945 * hard-to-explain kluge.
2948 trace_recovery(int trace_level)
2950 if (trace_level < LOG &&
2951 trace_level >= trace_recovery_messages)