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-2016, 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)
85 static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
86 static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
88 /* Global variables */
89 ErrorContextCallback *error_context_stack = NULL;
91 sigjmp_buf *PG_exception_stack = NULL;
93 extern bool redirection_done;
96 * Hook for intercepting messages before they are sent to the server log.
97 * Note that the hook will not get called for messages that are suppressed
98 * by log_min_messages. Also note that logging hooks implemented in preload
99 * libraries will miss any log messages that are generated before the
102 emit_log_hook_type emit_log_hook = NULL;
105 int Log_error_verbosity = PGERROR_VERBOSE;
106 char *Log_line_prefix = NULL; /* format for extra log line info */
107 int Log_destination = LOG_DESTINATION_STDERR;
108 char *Log_destination_string = NULL;
109 bool syslog_sequence_numbers = true;
110 bool syslog_split_messages = true;
115 * Max string length to send to syslog(). Note that this doesn't count the
116 * sequence-number prefix we add, and of course it doesn't count the prefix
117 * added by syslog itself. Solaris and sysklogd truncate the final message
118 * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
119 * other syslog implementations seem to have limits of 2KB or so.)
121 #ifndef PG_SYSLOG_LIMIT
122 #define PG_SYSLOG_LIMIT 900
125 static bool openlog_done = false;
126 static char *syslog_ident = NULL;
127 static int syslog_facility = LOG_LOCAL0;
129 static void write_syslog(int level, const char *line);
132 static void write_console(const char *line, int len);
135 extern char *event_source;
136 static void write_eventlog(int level, const char *line, int len);
139 /* We provide a small stack of ErrorData records for re-entrant cases */
140 #define ERRORDATA_STACK_SIZE 5
142 static ErrorData errordata[ERRORDATA_STACK_SIZE];
144 static int errordata_stack_depth = -1; /* index of topmost active frame */
146 static int recursion_depth = 0; /* to detect actual recursion */
149 * Saved timeval and buffers for formatted timestamps that might be used by
150 * both log_line_prefix and csv logs.
153 static struct timeval saved_timeval;
154 static bool saved_timeval_set = false;
156 #define FORMATTED_TS_LEN 128
157 static char formatted_start_time[FORMATTED_TS_LEN];
158 static char formatted_log_time[FORMATTED_TS_LEN];
161 /* Macro for checking errordata_stack_depth is reasonable */
162 #define CHECK_STACK_DEPTH() \
164 if (errordata_stack_depth < 0) \
166 errordata_stack_depth = -1; \
167 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
172 static const char *process_log_prefix_padding(const char *p, int *padding);
173 static void log_line_prefix(StringInfo buf, ErrorData *edata);
174 static void send_message_to_server_log(ErrorData *edata);
175 static void send_message_to_frontend(ErrorData *edata);
176 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
177 static const char *useful_strerror(int errnum);
178 static const char *get_errno_symbol(int errnum);
179 static const char *error_severity(int elevel);
180 static void append_with_tabs(StringInfo buf, const char *str);
181 static bool is_log_level_output(int elevel, int log_min_level);
182 static void write_pipe_chunks(char *data, int len, int dest);
183 static void write_csvlog(ErrorData *edata);
184 static void setup_formatted_log_time(void);
185 static void setup_formatted_start_time(void);
189 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
191 * This function exists to provide common control of various fallback steps
192 * that we take if we think we are facing infinite error recursion. See the
193 * callers for details.
196 in_error_recursion_trouble(void)
198 /* Pull the plug if recurse more than once */
199 return (recursion_depth > 2);
203 * One of those fallback steps is to stop trying to localize the error
204 * message, since there's a significant probability that that's exactly
205 * what's causing the recursion.
207 static inline const char *
208 err_gettext(const char *str)
211 if (in_error_recursion_trouble())
222 * errstart --- begin an error-reporting cycle
224 * Create a stack entry and store the given parameters in it. Subsequently,
225 * errmsg() and perhaps other routines will be called to further populate
226 * the stack entry. Finally, errfinish() will be called to actually process
229 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
230 * report (if it's a warning or lower and not to be reported anywhere).
233 errstart(int elevel, const char *filename, int lineno,
234 const char *funcname, const char *domain)
237 bool output_to_server;
238 bool output_to_client = false;
242 * Check some cases in which we want to promote an error into a more
243 * severe error. None of this logic applies for non-error messages.
248 * If we are inside a critical section, all errors become PANIC
249 * errors. See miscadmin.h.
251 if (CritSectionCount > 0)
255 * Check reasons for treating ERROR as FATAL:
257 * 1. we have no handler to pass the error to (implies we are in the
258 * postmaster or in backend startup).
260 * 2. ExitOnAnyError mode switch is set (initdb uses this).
262 * 3. the error occurred after proc_exit has begun to run. (It's
263 * proc_exit's responsibility to see that this doesn't turn into
264 * infinite recursion!)
268 if (PG_exception_stack == NULL ||
270 proc_exit_inprogress)
275 * If the error level is ERROR or more, errfinish is not going to
276 * return to caller; therefore, if there is any stacked error already
277 * in progress it will be lost. This is more or less okay, except we
278 * do not want to have a FATAL or PANIC error downgraded because the
279 * reporting process was interrupted by a lower-grade error. So check
280 * the stack and make sure we panic if panic is warranted.
282 for (i = 0; i <= errordata_stack_depth; i++)
283 elevel = Max(elevel, errordata[i].elevel);
287 * Now decide whether we need to process this report at all; if it's
288 * warning or less and not enabled for logging, just return FALSE without
289 * starting up any error logging machinery.
292 /* Determine whether message is enabled for server log output */
293 output_to_server = is_log_level_output(elevel, log_min_messages);
295 /* Determine whether message is enabled for client output */
296 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
299 * client_min_messages is honored only after we complete the
300 * authentication handshake. This is required both for security
301 * reasons and because many clients can't handle NOTICE messages
302 * during authentication.
304 if (ClientAuthInProgress)
305 output_to_client = (elevel >= ERROR);
307 output_to_client = (elevel >= client_min_messages ||
311 /* Skip processing effort if non-error message will not be output */
312 if (elevel < ERROR && !output_to_server && !output_to_client)
316 * We need to do some actual work. Make sure that memory context
317 * initialization has finished, else we can't do anything useful.
319 if (ErrorContext == NULL)
321 /* Ooops, hard crash time; very little we can do safely here */
322 write_stderr("error occurred at %s:%d before error message processing is available\n",
323 filename ? filename : "(unknown file)", lineno);
328 * Okay, crank up a stack entry to store the info in.
331 if (recursion_depth++ > 0 && elevel >= ERROR)
334 * Ooops, error during error processing. Clear ErrorContext as
335 * discussed at top of file. We will not return to the original
336 * error's reporter or handler, so we don't need it.
338 MemoryContextReset(ErrorContext);
341 * Infinite error recursion might be due to something broken in a
342 * context traceback routine. Abandon them too. We also abandon
343 * attempting to print the error statement (which, if long, could
344 * itself be the source of the recursive failure).
346 if (in_error_recursion_trouble())
348 error_context_stack = NULL;
349 debug_query_string = NULL;
352 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
355 * Wups, stack not big enough. We treat this as a PANIC condition
356 * because it suggests an infinite loop of errors during error
359 errordata_stack_depth = -1; /* make room on stack */
360 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
363 /* Initialize data for this error frame */
364 edata = &errordata[errordata_stack_depth];
365 MemSet(edata, 0, sizeof(ErrorData));
366 edata->elevel = elevel;
367 edata->output_to_server = output_to_server;
368 edata->output_to_client = output_to_client;
373 /* keep only base name, useful especially for vpath builds */
374 slash = strrchr(filename, '/');
376 filename = slash + 1;
378 edata->filename = filename;
379 edata->lineno = lineno;
380 edata->funcname = funcname;
381 /* the default text domain is the backend's */
382 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
383 /* initialize context_domain the same way (see set_errcontext_domain()) */
384 edata->context_domain = edata->domain;
385 /* Select default errcode based on elevel */
387 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
388 else if (elevel == WARNING)
389 edata->sqlerrcode = ERRCODE_WARNING;
391 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
392 /* errno is saved here so that error parameter eval can't change it */
393 edata->saved_errno = errno;
396 * Any allocations for this error state level should go into ErrorContext
398 edata->assoc_context = ErrorContext;
405 * errfinish --- end an error-reporting cycle
407 * Produce the appropriate error report(s) and pop the error stack.
409 * If elevel is ERROR or worse, control does not return to the caller.
410 * See elog.h for the error level definitions.
413 errfinish(int dummy,...)
415 ErrorData *edata = &errordata[errordata_stack_depth];
417 MemoryContext oldcontext;
418 ErrorContextCallback *econtext;
422 elevel = edata->elevel;
425 * Do processing in ErrorContext, which we hope has enough reserved space
426 * to report an error.
428 oldcontext = MemoryContextSwitchTo(ErrorContext);
431 * Call any context callback functions. Errors occurring in callback
432 * functions will be treated as recursive errors --- this ensures we will
433 * avoid infinite recursion (see errstart).
435 for (econtext = error_context_stack;
437 econtext = econtext->previous)
438 (*econtext->callback) (econtext->arg);
441 * If ERROR (not more nor less) we pass it off to the current handler.
442 * Printing it and popping the stack is the responsibility of the handler.
447 * We do some minimal cleanup before longjmp'ing so that handlers can
448 * execute in a reasonably sane state.
450 * Reset InterruptHoldoffCount in case we ereport'd from inside an
451 * interrupt holdoff section. (We assume here that no handler will
452 * itself be inside a holdoff section. If necessary, such a handler
453 * could save and restore InterruptHoldoffCount for itself, but this
454 * should make life easier for most.)
456 InterruptHoldoffCount = 0;
457 QueryCancelHoldoffCount = 0;
459 CritSectionCount = 0; /* should be unnecessary, but... */
462 * Note that we leave CurrentMemoryContext set to ErrorContext. The
463 * handler should reset it to something else soon.
471 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
472 * progress, so that we can report the message before dying. (Without
473 * this, pq_putmessage will refuse to send the message at all, which is
474 * what we want for NOTICE messages, but not for fatal exits.) This hack
475 * is necessary because of poor design of old-style copy protocol. Note
476 * we must do this even if client is fool enough to have set
477 * client_min_messages above FATAL, so don't look at output_to_client.
479 if (elevel >= FATAL && whereToSendOutput == DestRemote)
482 /* Emit the message to the right places */
485 /* Now free up subsidiary data attached to stack entry, and release it */
487 pfree(edata->message);
489 pfree(edata->detail);
490 if (edata->detail_log)
491 pfree(edata->detail_log);
495 pfree(edata->context);
496 if (edata->schema_name)
497 pfree(edata->schema_name);
498 if (edata->table_name)
499 pfree(edata->table_name);
500 if (edata->column_name)
501 pfree(edata->column_name);
502 if (edata->datatype_name)
503 pfree(edata->datatype_name);
504 if (edata->constraint_name)
505 pfree(edata->constraint_name);
506 if (edata->internalquery)
507 pfree(edata->internalquery);
509 errordata_stack_depth--;
511 /* Exit error-handling context */
512 MemoryContextSwitchTo(oldcontext);
516 * Perform error recovery action as specified by elevel.
521 * For a FATAL error, we let proc_exit clean up and exit.
523 * If we just reported a startup failure, the client will disconnect
524 * on receiving it, so don't send any more to the client.
526 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
527 whereToSendOutput = DestNone;
530 * fflush here is just to improve the odds that we get to see the
531 * error message, in case things are so hosed that proc_exit crashes.
532 * Any other code you might be tempted to add here should probably be
533 * in an on_proc_exit or on_shmem_exit callback instead.
539 * Do normal process-exit cleanup, then return exit code 1 to indicate
540 * FATAL termination. The postmaster may or may not consider this
541 * worthy of panic, depending on which subprocess returns it.
549 * Serious crash time. Postmaster will observe SIGABRT process exit
550 * status and kill the other backends too.
552 * XXX: what if we are *in* the postmaster? abort() won't kill our
561 * Check for cancel/die interrupt first --- this is so that the user can
562 * stop a query emitting tons of notice or warning messages, even if it's
563 * in a loop that otherwise fails to check for interrupts.
565 CHECK_FOR_INTERRUPTS();
570 * errcode --- add SQLSTATE error code to the current error
572 * The code is expected to be represented as per MAKE_SQLSTATE().
575 errcode(int sqlerrcode)
577 ErrorData *edata = &errordata[errordata_stack_depth];
579 /* we don't bother incrementing recursion_depth */
582 edata->sqlerrcode = sqlerrcode;
584 return 0; /* return value does not matter */
589 * errcode_for_file_access --- add SQLSTATE error code to the current error
591 * The SQLSTATE code is chosen based on the saved errno value. We assume
592 * that the failing operation was some type of disk file access.
594 * NOTE: the primary error message string should generally include %m
598 errcode_for_file_access(void)
600 ErrorData *edata = &errordata[errordata_stack_depth];
602 /* we don't bother incrementing recursion_depth */
605 switch (edata->saved_errno)
607 /* Permission-denied failures */
608 case EPERM: /* Not super-user */
609 case EACCES: /* Permission denied */
611 case EROFS: /* Read only file system */
613 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
617 case ENOENT: /* No such file or directory */
618 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
622 case EEXIST: /* File exists */
623 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
626 /* Wrong object type or state */
627 case ENOTDIR: /* Not a directory */
628 case EISDIR: /* Is a directory */
629 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
630 case ENOTEMPTY: /* Directory not empty */
632 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
635 /* Insufficient resources */
636 case ENOSPC: /* No space left on device */
637 edata->sqlerrcode = ERRCODE_DISK_FULL;
640 case ENFILE: /* File table overflow */
641 case EMFILE: /* Too many open files */
642 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
645 /* Hardware failure */
646 case EIO: /* I/O error */
647 edata->sqlerrcode = ERRCODE_IO_ERROR;
650 /* All else is classified as internal errors */
652 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
656 return 0; /* return value does not matter */
660 * errcode_for_socket_access --- add SQLSTATE error code to the current error
662 * The SQLSTATE code is chosen based on the saved errno value. We assume
663 * that the failing operation was some type of socket access.
665 * NOTE: the primary error message string should generally include %m
669 errcode_for_socket_access(void)
671 ErrorData *edata = &errordata[errordata_stack_depth];
673 /* we don't bother incrementing recursion_depth */
676 switch (edata->saved_errno)
678 /* Loss of connection */
683 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
686 /* All else is classified as internal errors */
688 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
692 return 0; /* return value does not matter */
697 * This macro handles expansion of a format string and associated parameters;
698 * it's common code for errmsg(), errdetail(), etc. Must be called inside
699 * a routine that is declared like "const char *fmt, ..." and has an edata
700 * pointer set up. The message is assigned to edata->targetfield, or
701 * appended to it if appendval is true. The message is subject to translation
702 * if translateit is true.
704 * Note: we pstrdup the buffer rather than just transferring its storage
705 * to the edata field because the buffer might be considerably larger than
708 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
711 StringInfoData buf; \
712 /* Internationalize the error format string */ \
713 if ((translateit) && !in_error_recursion_trouble()) \
714 fmt = dgettext((domain), fmt); \
715 /* Expand %m in format string */ \
716 fmtbuf = expand_fmt_string(fmt, edata); \
717 initStringInfo(&buf); \
718 if ((appendval) && edata->targetfield) { \
719 appendStringInfoString(&buf, edata->targetfield); \
720 appendStringInfoChar(&buf, '\n'); \
722 /* Generate actual output --- have to use appendStringInfoVA */ \
727 va_start(args, fmt); \
728 needed = appendStringInfoVA(&buf, fmtbuf, args); \
732 enlargeStringInfo(&buf, needed); \
734 /* Done with expanded fmt */ \
736 /* Save the completed message into the stack item */ \
737 if (edata->targetfield) \
738 pfree(edata->targetfield); \
739 edata->targetfield = pstrdup(buf.data); \
744 * Same as above, except for pluralized error messages. The calling routine
745 * must be declared like "const char *fmt_singular, const char *fmt_plural,
746 * unsigned long n, ...". Translation is assumed always wanted.
748 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
752 StringInfoData buf; \
753 /* Internationalize the error format string */ \
754 if (!in_error_recursion_trouble()) \
755 fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
757 fmt = (n == 1 ? fmt_singular : fmt_plural); \
758 /* Expand %m in format string */ \
759 fmtbuf = expand_fmt_string(fmt, edata); \
760 initStringInfo(&buf); \
761 if ((appendval) && edata->targetfield) { \
762 appendStringInfoString(&buf, edata->targetfield); \
763 appendStringInfoChar(&buf, '\n'); \
765 /* Generate actual output --- have to use appendStringInfoVA */ \
771 needed = appendStringInfoVA(&buf, fmtbuf, args); \
775 enlargeStringInfo(&buf, needed); \
777 /* Done with expanded fmt */ \
779 /* Save the completed message into the stack item */ \
780 if (edata->targetfield) \
781 pfree(edata->targetfield); \
782 edata->targetfield = pstrdup(buf.data); \
788 * errmsg --- add a primary error message text to the current error
790 * In addition to the usual %-escapes recognized by printf, "%m" in
791 * fmt is replaced by the error message for the caller's value of errno.
793 * Note: no newline is needed at the end of the fmt string, since
794 * ereport will provide one for the output methods that need it.
797 errmsg(const char *fmt,...)
799 ErrorData *edata = &errordata[errordata_stack_depth];
800 MemoryContext oldcontext;
804 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
806 edata->message_id = fmt;
807 EVALUATE_MESSAGE(edata->domain, message, false, true);
809 MemoryContextSwitchTo(oldcontext);
811 return 0; /* return value does not matter */
816 * errmsg_internal --- add a primary error message text to the current error
818 * This is exactly like errmsg() except that strings passed to errmsg_internal
819 * are not translated, and are customarily left out of the
820 * internationalization message dictionary. This should be used for "can't
821 * happen" cases that are probably not worth spending translation effort on.
822 * We also use this for certain cases where we *must* not try to translate
823 * the message because the translation would fail and result in infinite
827 errmsg_internal(const char *fmt,...)
829 ErrorData *edata = &errordata[errordata_stack_depth];
830 MemoryContext oldcontext;
834 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
836 edata->message_id = fmt;
837 EVALUATE_MESSAGE(edata->domain, message, false, false);
839 MemoryContextSwitchTo(oldcontext);
841 return 0; /* return value does not matter */
846 * errmsg_plural --- add a primary error message text to the current error,
847 * with support for pluralization of the message text
850 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
853 ErrorData *edata = &errordata[errordata_stack_depth];
854 MemoryContext oldcontext;
858 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
860 edata->message_id = fmt_singular;
861 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
863 MemoryContextSwitchTo(oldcontext);
865 return 0; /* return value does not matter */
870 * errdetail --- add a detail error message text to the current error
873 errdetail(const char *fmt,...)
875 ErrorData *edata = &errordata[errordata_stack_depth];
876 MemoryContext oldcontext;
880 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
882 EVALUATE_MESSAGE(edata->domain, detail, false, true);
884 MemoryContextSwitchTo(oldcontext);
886 return 0; /* return value does not matter */
891 * errdetail_internal --- add a detail error message text to the current error
893 * This is exactly like errdetail() except that strings passed to
894 * errdetail_internal are not translated, and are customarily left out of the
895 * internationalization message dictionary. This should be used for detail
896 * messages that seem not worth translating for one reason or another
897 * (typically, that they don't seem to be useful to average users).
900 errdetail_internal(const char *fmt,...)
902 ErrorData *edata = &errordata[errordata_stack_depth];
903 MemoryContext oldcontext;
907 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
909 EVALUATE_MESSAGE(edata->domain, detail, false, false);
911 MemoryContextSwitchTo(oldcontext);
913 return 0; /* return value does not matter */
918 * errdetail_log --- add a detail_log error message text to the current error
921 errdetail_log(const char *fmt,...)
923 ErrorData *edata = &errordata[errordata_stack_depth];
924 MemoryContext oldcontext;
928 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
930 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
932 MemoryContextSwitchTo(oldcontext);
934 return 0; /* return value does not matter */
938 * errdetail_log_plural --- add a detail_log error message text to the current error
939 * with support for pluralization of the message text
942 errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
945 ErrorData *edata = &errordata[errordata_stack_depth];
946 MemoryContext oldcontext;
950 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
952 EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
954 MemoryContextSwitchTo(oldcontext);
956 return 0; /* return value does not matter */
961 * errdetail_plural --- add a detail error message text to the current error,
962 * with support for pluralization of the message text
965 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
968 ErrorData *edata = &errordata[errordata_stack_depth];
969 MemoryContext oldcontext;
973 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
975 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
977 MemoryContextSwitchTo(oldcontext);
979 return 0; /* return value does not matter */
984 * errhint --- add a hint error message text to the current error
987 errhint(const char *fmt,...)
989 ErrorData *edata = &errordata[errordata_stack_depth];
990 MemoryContext oldcontext;
994 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
996 EVALUATE_MESSAGE(edata->domain, hint, false, true);
998 MemoryContextSwitchTo(oldcontext);
1000 return 0; /* return value does not matter */
1005 * errcontext_msg --- add a context error message text to the current error
1007 * Unlike other cases, multiple calls are allowed to build up a stack of
1008 * context information. We assume earlier calls represent more-closely-nested
1012 errcontext_msg(const char *fmt,...)
1014 ErrorData *edata = &errordata[errordata_stack_depth];
1015 MemoryContext oldcontext;
1018 CHECK_STACK_DEPTH();
1019 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1021 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1023 MemoryContextSwitchTo(oldcontext);
1025 return 0; /* return value does not matter */
1029 * set_errcontext_domain --- set message domain to be used by errcontext()
1031 * errcontext_msg() can be called from a different module than the original
1032 * ereport(), so we cannot use the message domain passed in errstart() to
1033 * translate it. Instead, each errcontext_msg() call should be preceded by
1034 * a set_errcontext_domain() call to specify the domain. This is usually
1035 * done transparently by the errcontext() macro.
1037 * Although errcontext is primarily meant for use at call sites distant from
1038 * the original ereport call, there are a few places that invoke errcontext
1039 * within ereport. The expansion of errcontext as a comma expression calling
1040 * set_errcontext_domain then errcontext_msg is problematic in this case,
1041 * because the intended comma expression becomes two arguments to errfinish,
1042 * which the compiler is at liberty to evaluate in either order. But in
1043 * such a case, the set_errcontext_domain calls must be selecting the same
1044 * TEXTDOMAIN value that the errstart call did, so order does not matter
1045 * so long as errstart initializes context_domain along with domain.
1048 set_errcontext_domain(const char *domain)
1050 ErrorData *edata = &errordata[errordata_stack_depth];
1052 /* we don't bother incrementing recursion_depth */
1053 CHECK_STACK_DEPTH();
1055 /* the default text domain is the backend's */
1056 edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1058 return 0; /* return value does not matter */
1063 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1065 * This should be called if the message text already includes the statement.
1068 errhidestmt(bool hide_stmt)
1070 ErrorData *edata = &errordata[errordata_stack_depth];
1072 /* we don't bother incrementing recursion_depth */
1073 CHECK_STACK_DEPTH();
1075 edata->hide_stmt = hide_stmt;
1077 return 0; /* return value does not matter */
1081 * errhidecontext --- optionally suppress CONTEXT: field of log entry
1083 * This should only be used for verbose debugging messages where the repeated
1084 * inclusion of context would bloat the log volume too much.
1087 errhidecontext(bool hide_ctx)
1089 ErrorData *edata = &errordata[errordata_stack_depth];
1091 /* we don't bother incrementing recursion_depth */
1092 CHECK_STACK_DEPTH();
1094 edata->hide_ctx = hide_ctx;
1096 return 0; /* return value does not matter */
1101 * errfunction --- add reporting function name to the current error
1103 * This is used when backwards compatibility demands that the function
1104 * name appear in messages sent to old-protocol clients. Note that the
1105 * passed string is expected to be a non-freeable constant string.
1108 errfunction(const char *funcname)
1110 ErrorData *edata = &errordata[errordata_stack_depth];
1112 /* we don't bother incrementing recursion_depth */
1113 CHECK_STACK_DEPTH();
1115 edata->funcname = funcname;
1116 edata->show_funcname = true;
1118 return 0; /* return value does not matter */
1122 * errposition --- add cursor position to the current error
1125 errposition(int cursorpos)
1127 ErrorData *edata = &errordata[errordata_stack_depth];
1129 /* we don't bother incrementing recursion_depth */
1130 CHECK_STACK_DEPTH();
1132 edata->cursorpos = cursorpos;
1134 return 0; /* return value does not matter */
1138 * internalerrposition --- add internal cursor position to the current error
1141 internalerrposition(int cursorpos)
1143 ErrorData *edata = &errordata[errordata_stack_depth];
1145 /* we don't bother incrementing recursion_depth */
1146 CHECK_STACK_DEPTH();
1148 edata->internalpos = cursorpos;
1150 return 0; /* return value does not matter */
1154 * internalerrquery --- add internal query text to the current error
1156 * Can also pass NULL to drop the internal query text entry. This case
1157 * is intended for use in error callback subroutines that are editorializing
1158 * on the layout of the error report.
1161 internalerrquery(const char *query)
1163 ErrorData *edata = &errordata[errordata_stack_depth];
1165 /* we don't bother incrementing recursion_depth */
1166 CHECK_STACK_DEPTH();
1168 if (edata->internalquery)
1170 pfree(edata->internalquery);
1171 edata->internalquery = NULL;
1175 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1177 return 0; /* return value does not matter */
1181 * err_generic_string -- used to set individual ErrorData string fields
1182 * identified by PG_DIAG_xxx codes.
1184 * This intentionally only supports fields that don't use localized strings,
1185 * so that there are no translation considerations.
1187 * Most potential callers should not use this directly, but instead prefer
1188 * higher-level abstractions, such as errtablecol() (see relcache.c).
1191 err_generic_string(int field, const char *str)
1193 ErrorData *edata = &errordata[errordata_stack_depth];
1195 /* we don't bother incrementing recursion_depth */
1196 CHECK_STACK_DEPTH();
1200 case PG_DIAG_SCHEMA_NAME:
1201 set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1203 case PG_DIAG_TABLE_NAME:
1204 set_errdata_field(edata->assoc_context, &edata->table_name, str);
1206 case PG_DIAG_COLUMN_NAME:
1207 set_errdata_field(edata->assoc_context, &edata->column_name, str);
1209 case PG_DIAG_DATATYPE_NAME:
1210 set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1212 case PG_DIAG_CONSTRAINT_NAME:
1213 set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1216 elog(ERROR, "unsupported ErrorData field id: %d", field);
1220 return 0; /* return value does not matter */
1224 * set_errdata_field --- set an ErrorData string field
1227 set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1229 Assert(*ptr == NULL);
1230 *ptr = MemoryContextStrdup(cxt, str);
1234 * geterrcode --- return the currently set SQLSTATE error code
1236 * This is only intended for use in error callback subroutines, since there
1237 * is no other place outside elog.c where the concept is meaningful.
1242 ErrorData *edata = &errordata[errordata_stack_depth];
1244 /* we don't bother incrementing recursion_depth */
1245 CHECK_STACK_DEPTH();
1247 return edata->sqlerrcode;
1251 * geterrposition --- return the currently set error position (0 if none)
1253 * This is only intended for use in error callback subroutines, since there
1254 * is no other place outside elog.c where the concept is meaningful.
1257 geterrposition(void)
1259 ErrorData *edata = &errordata[errordata_stack_depth];
1261 /* we don't bother incrementing recursion_depth */
1262 CHECK_STACK_DEPTH();
1264 return edata->cursorpos;
1268 * getinternalerrposition --- same for internal error position
1270 * This is only intended for use in error callback subroutines, since there
1271 * is no other place outside elog.c where the concept is meaningful.
1274 getinternalerrposition(void)
1276 ErrorData *edata = &errordata[errordata_stack_depth];
1278 /* we don't bother incrementing recursion_depth */
1279 CHECK_STACK_DEPTH();
1281 return edata->internalpos;
1286 * elog_start --- startup for old-style API
1288 * All that we do here is stash the hidden filename/lineno/funcname
1289 * arguments into a stack entry, along with the current value of errno.
1291 * We need this to be separate from elog_finish because there's no other
1292 * C89-compliant way to deal with inserting extra arguments into the elog
1293 * call. (When using C99's __VA_ARGS__, we could possibly merge this with
1294 * elog_finish, but there doesn't seem to be a good way to save errno before
1295 * evaluating the format arguments if we do that.)
1298 elog_start(const char *filename, int lineno, const char *funcname)
1302 /* Make sure that memory context initialization has finished */
1303 if (ErrorContext == NULL)
1305 /* Ooops, hard crash time; very little we can do safely here */
1306 write_stderr("error occurred at %s:%d before error message processing is available\n",
1307 filename ? filename : "(unknown file)", lineno);
1311 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1314 * Wups, stack not big enough. We treat this as a PANIC condition
1315 * because it suggests an infinite loop of errors during error
1316 * recovery. Note that the message is intentionally not localized,
1317 * else failure to convert it to client encoding could cause further
1320 errordata_stack_depth = -1; /* make room on stack */
1321 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1324 edata = &errordata[errordata_stack_depth];
1329 /* keep only base name, useful especially for vpath builds */
1330 slash = strrchr(filename, '/');
1332 filename = slash + 1;
1334 edata->filename = filename;
1335 edata->lineno = lineno;
1336 edata->funcname = funcname;
1337 /* errno is saved now so that error parameter eval can't change it */
1338 edata->saved_errno = errno;
1340 /* Use ErrorContext for any allocations done at this level. */
1341 edata->assoc_context = ErrorContext;
1345 * elog_finish --- finish up for old-style API
1348 elog_finish(int elevel, const char *fmt,...)
1350 ErrorData *edata = &errordata[errordata_stack_depth];
1351 MemoryContext oldcontext;
1353 CHECK_STACK_DEPTH();
1356 * Do errstart() to see if we actually want to report the message.
1358 errordata_stack_depth--;
1359 errno = edata->saved_errno;
1360 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1361 return; /* nothing to do */
1364 * Format error message just like errmsg_internal().
1367 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1369 edata->message_id = fmt;
1370 EVALUATE_MESSAGE(edata->domain, message, false, false);
1372 MemoryContextSwitchTo(oldcontext);
1376 * And let errfinish() finish up.
1383 * Functions to allow construction of error message strings separately from
1384 * the ereport() call itself.
1386 * The expected calling convention is
1388 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1390 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1391 * assume that any functions called in the arguments of format_elog_string()
1392 * cannot result in re-entrant use of these functions --- otherwise the wrong
1393 * text domain might be used, or the wrong errno substituted for %m. This is
1394 * okay for the current usage with GUC check hooks, but might need further
1397 * The result of format_elog_string() is stored in ErrorContext, and will
1398 * therefore survive until FlushErrorState() is called.
1400 static int save_format_errnumber;
1401 static const char *save_format_domain;
1404 pre_format_elog_string(int errnumber, const char *domain)
1406 /* Save errno before evaluation of argument functions can change it */
1407 save_format_errnumber = errnumber;
1408 /* Save caller's text domain */
1409 save_format_domain = domain;
1413 format_elog_string(const char *fmt,...)
1417 MemoryContext oldcontext;
1419 /* Initialize a mostly-dummy error frame */
1421 MemSet(edata, 0, sizeof(ErrorData));
1422 /* the default text domain is the backend's */
1423 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1424 /* set the errno to be used to interpret %m */
1425 edata->saved_errno = save_format_errnumber;
1427 oldcontext = MemoryContextSwitchTo(ErrorContext);
1429 edata->message_id = fmt;
1430 EVALUATE_MESSAGE(edata->domain, message, false, true);
1432 MemoryContextSwitchTo(oldcontext);
1434 return edata->message;
1439 * Actual output of the top-of-stack error message
1441 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1442 * if the error is caught by somebody). For all other severity levels this
1443 * is called by errfinish.
1446 EmitErrorReport(void)
1448 ErrorData *edata = &errordata[errordata_stack_depth];
1449 MemoryContext oldcontext;
1452 CHECK_STACK_DEPTH();
1453 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1456 * Call hook before sending message to log. The hook function is allowed
1457 * to turn off edata->output_to_server, so we must recheck that afterward.
1458 * Making any other change in the content of edata is not considered
1461 * Note: the reason why the hook can only turn off output_to_server, and
1462 * not turn it on, is that it'd be unreliable: we will never get here at
1463 * all if errstart() deems the message uninteresting. A hook that could
1464 * make decisions in that direction would have to hook into errstart(),
1465 * where it would have much less information available. emit_log_hook is
1466 * intended for custom log filtering and custom log message transmission
1469 * The log hook has access to both the translated and original English
1470 * error message text, which is passed through to allow it to be used
1471 * as a message identifier. Note that the original text is not available
1472 * for detail, detail_log, hint and context text elements.
1474 if (edata->output_to_server && emit_log_hook)
1475 (*emit_log_hook) (edata);
1477 /* Send to server log, if enabled */
1478 if (edata->output_to_server)
1479 send_message_to_server_log(edata);
1481 /* Send to client, if enabled */
1482 if (edata->output_to_client)
1483 send_message_to_frontend(edata);
1485 MemoryContextSwitchTo(oldcontext);
1490 * CopyErrorData --- obtain a copy of the topmost error stack entry
1492 * This is only for use in error handler code. The data is copied into the
1493 * current memory context, so callers should always switch away from
1494 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1499 ErrorData *edata = &errordata[errordata_stack_depth];
1500 ErrorData *newedata;
1503 * we don't increment recursion_depth because out-of-memory here does not
1504 * indicate a problem within the error subsystem.
1506 CHECK_STACK_DEPTH();
1508 Assert(CurrentMemoryContext != ErrorContext);
1510 /* Copy the struct itself */
1511 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1512 memcpy(newedata, edata, sizeof(ErrorData));
1514 /* Make copies of separately-allocated fields */
1515 if (newedata->message)
1516 newedata->message = pstrdup(newedata->message);
1517 if (newedata->detail)
1518 newedata->detail = pstrdup(newedata->detail);
1519 if (newedata->detail_log)
1520 newedata->detail_log = pstrdup(newedata->detail_log);
1522 newedata->hint = pstrdup(newedata->hint);
1523 if (newedata->context)
1524 newedata->context = pstrdup(newedata->context);
1525 if (newedata->schema_name)
1526 newedata->schema_name = pstrdup(newedata->schema_name);
1527 if (newedata->table_name)
1528 newedata->table_name = pstrdup(newedata->table_name);
1529 if (newedata->column_name)
1530 newedata->column_name = pstrdup(newedata->column_name);
1531 if (newedata->datatype_name)
1532 newedata->datatype_name = pstrdup(newedata->datatype_name);
1533 if (newedata->constraint_name)
1534 newedata->constraint_name = pstrdup(newedata->constraint_name);
1535 if (newedata->internalquery)
1536 newedata->internalquery = pstrdup(newedata->internalquery);
1538 /* Use the calling context for string allocation */
1539 newedata->assoc_context = CurrentMemoryContext;
1545 * FreeErrorData --- free the structure returned by CopyErrorData.
1547 * Error handlers should use this in preference to assuming they know all
1548 * the separately-allocated fields.
1551 FreeErrorData(ErrorData *edata)
1554 pfree(edata->message);
1556 pfree(edata->detail);
1557 if (edata->detail_log)
1558 pfree(edata->detail_log);
1562 pfree(edata->context);
1563 if (edata->schema_name)
1564 pfree(edata->schema_name);
1565 if (edata->table_name)
1566 pfree(edata->table_name);
1567 if (edata->column_name)
1568 pfree(edata->column_name);
1569 if (edata->datatype_name)
1570 pfree(edata->datatype_name);
1571 if (edata->constraint_name)
1572 pfree(edata->constraint_name);
1573 if (edata->internalquery)
1574 pfree(edata->internalquery);
1579 * FlushErrorState --- flush the error state after error recovery
1581 * This should be called by an error handler after it's done processing
1582 * the error; or as soon as it's done CopyErrorData, if it intends to
1583 * do stuff that is likely to provoke another error. You are not "out" of
1584 * the error subsystem until you have done this.
1587 FlushErrorState(void)
1590 * Reset stack to empty. The only case where it would be more than one
1591 * deep is if we serviced an error that interrupted construction of
1592 * another message. We assume control escaped out of that message
1593 * construction and won't ever go back.
1595 errordata_stack_depth = -1;
1596 recursion_depth = 0;
1597 /* Delete all data in ErrorContext */
1598 MemoryContextResetAndDeleteChildren(ErrorContext);
1602 * ThrowErrorData --- report an error described by an ErrorData structure
1604 * This is intended to be used to re-report errors originally thrown by
1605 * background worker processes and then propagated (with or without
1606 * modification) to the backend responsible for them.
1609 ThrowErrorData(ErrorData *edata)
1611 ErrorData *newedata;
1612 MemoryContext oldcontext;
1614 if (!errstart(edata->elevel, edata->filename, edata->lineno,
1615 edata->funcname, NULL))
1618 newedata = &errordata[errordata_stack_depth];
1619 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1621 /* Copy the supplied fields to the error stack. */
1622 if (edata->sqlerrcode > 0)
1623 newedata->sqlerrcode = edata->sqlerrcode;
1625 newedata->message = pstrdup(edata->message);
1627 newedata->detail = pstrdup(edata->detail);
1628 if (edata->detail_log)
1629 newedata->detail_log = pstrdup(edata->detail_log);
1631 newedata->hint = pstrdup(edata->hint);
1633 newedata->context = pstrdup(edata->context);
1634 if (edata->schema_name)
1635 newedata->schema_name = pstrdup(edata->schema_name);
1636 if (edata->table_name)
1637 newedata->table_name = pstrdup(edata->table_name);
1638 if (edata->column_name)
1639 newedata->column_name = pstrdup(edata->column_name);
1640 if (edata->datatype_name)
1641 newedata->datatype_name = pstrdup(edata->datatype_name);
1642 if (edata->constraint_name)
1643 newedata->constraint_name = pstrdup(edata->constraint_name);
1644 if (edata->internalquery)
1645 newedata->internalquery = pstrdup(edata->internalquery);
1647 MemoryContextSwitchTo(oldcontext);
1653 * ReThrowError --- re-throw a previously copied error
1655 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1656 * subsystem, then do some processing, and finally ReThrowError to re-throw
1657 * the original error. This is slower than just PG_RE_THROW() but should
1658 * be used if the "some processing" is likely to incur another error.
1661 ReThrowError(ErrorData *edata)
1663 ErrorData *newedata;
1665 Assert(edata->elevel == ERROR);
1667 /* Push the data back into the error context */
1669 MemoryContextSwitchTo(ErrorContext);
1671 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1674 * Wups, stack not big enough. We treat this as a PANIC condition
1675 * because it suggests an infinite loop of errors during error
1678 errordata_stack_depth = -1; /* make room on stack */
1679 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1682 newedata = &errordata[errordata_stack_depth];
1683 memcpy(newedata, edata, sizeof(ErrorData));
1685 /* Make copies of separately-allocated fields */
1686 if (newedata->message)
1687 newedata->message = pstrdup(newedata->message);
1688 if (newedata->detail)
1689 newedata->detail = pstrdup(newedata->detail);
1690 if (newedata->detail_log)
1691 newedata->detail_log = pstrdup(newedata->detail_log);
1693 newedata->hint = pstrdup(newedata->hint);
1694 if (newedata->context)
1695 newedata->context = pstrdup(newedata->context);
1696 if (newedata->schema_name)
1697 newedata->schema_name = pstrdup(newedata->schema_name);
1698 if (newedata->table_name)
1699 newedata->table_name = pstrdup(newedata->table_name);
1700 if (newedata->column_name)
1701 newedata->column_name = pstrdup(newedata->column_name);
1702 if (newedata->datatype_name)
1703 newedata->datatype_name = pstrdup(newedata->datatype_name);
1704 if (newedata->constraint_name)
1705 newedata->constraint_name = pstrdup(newedata->constraint_name);
1706 if (newedata->internalquery)
1707 newedata->internalquery = pstrdup(newedata->internalquery);
1709 /* Reset the assoc_context to be ErrorContext */
1710 newedata->assoc_context = ErrorContext;
1717 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1722 /* If possible, throw the error to the next outer setjmp handler */
1723 if (PG_exception_stack != NULL)
1724 siglongjmp(*PG_exception_stack, 1);
1728 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1729 * we have now exited only to discover that there is no outer setjmp
1730 * handler to pass the error to. Had the error been thrown outside
1731 * the block to begin with, we'd have promoted the error to FATAL, so
1732 * the correct behavior is to make it FATAL now; that is, emit it and
1733 * then call proc_exit.
1735 ErrorData *edata = &errordata[errordata_stack_depth];
1737 Assert(errordata_stack_depth >= 0);
1738 Assert(edata->elevel == ERROR);
1739 edata->elevel = FATAL;
1742 * At least in principle, the increase in severity could have changed
1743 * where-to-output decisions, so recalculate. This should stay in
1744 * sync with errstart(), which see for comments.
1746 if (IsPostmasterEnvironment)
1747 edata->output_to_server = is_log_level_output(FATAL,
1750 edata->output_to_server = (FATAL >= log_min_messages);
1751 if (whereToSendOutput == DestRemote)
1753 if (ClientAuthInProgress)
1754 edata->output_to_client = true;
1756 edata->output_to_client = (FATAL >= client_min_messages);
1760 * We can use errfinish() for the rest, but we don't want it to call
1761 * any error context routines a second time. Since we know we are
1762 * about to exit, it should be OK to just clear the context stack.
1764 error_context_stack = NULL;
1769 /* Doesn't return ... */
1770 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1771 __FILE__, __LINE__);
1776 * GetErrorContextStack - Return the context stack, for display/diags
1778 * Returns a pstrdup'd string in the caller's context which includes the PG
1779 * error call stack. It is the caller's responsibility to ensure this string
1780 * is pfree'd (or its context cleaned up) when done.
1782 * This information is collected by traversing the error contexts and calling
1783 * each context's callback function, each of which is expected to call
1784 * errcontext() to return a string which can be presented to the user.
1787 GetErrorContextStack(void)
1790 ErrorContextCallback *econtext;
1793 * Okay, crank up a stack entry to store the info in.
1797 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1800 * Wups, stack not big enough. We treat this as a PANIC condition
1801 * because it suggests an infinite loop of errors during error
1804 errordata_stack_depth = -1; /* make room on stack */
1805 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1809 * Things look good so far, so initialize our error frame
1811 edata = &errordata[errordata_stack_depth];
1812 MemSet(edata, 0, sizeof(ErrorData));
1815 * Set up assoc_context to be the caller's context, so any allocations
1816 * done (which will include edata->context) will use their context.
1818 edata->assoc_context = CurrentMemoryContext;
1821 * Call any context callback functions to collect the context information
1822 * into edata->context.
1824 * Errors occurring in callback functions should go through the regular
1825 * error handling code which should handle any recursive errors, though we
1826 * double-check above, just in case.
1828 for (econtext = error_context_stack;
1830 econtext = econtext->previous)
1831 (*econtext->callback) (econtext->arg);
1834 * Clean ourselves off the stack, any allocations done should have been
1835 * using edata->assoc_context, which we set up earlier to be the caller's
1836 * context, so we're free to just remove our entry off the stack and
1837 * decrement recursion depth and exit.
1839 errordata_stack_depth--;
1843 * Return a pointer to the string the caller asked for, which should have
1844 * been allocated in their context.
1846 return edata->context;
1851 * Initialization of error output file
1859 if (OutputFileName[0])
1862 * A debug-output file name was given.
1864 * Make sure we can write the file, and find out if it's a tty.
1866 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1869 (errcode_for_file_access(),
1870 errmsg("could not open file \"%s\": %m", OutputFileName)));
1875 * Redirect our stderr to the debug output file.
1877 if (!freopen(OutputFileName, "a", stderr))
1879 (errcode_for_file_access(),
1880 errmsg("could not reopen file \"%s\" as stderr: %m",
1884 * If the file is a tty and we're running under the postmaster, try to
1885 * send stdout there as well (if it isn't a tty then stderr will block
1886 * out stdout, so we may as well let stdout go wherever it was going
1889 if (istty && IsUnderPostmaster)
1890 if (!freopen(OutputFileName, "a", stdout))
1892 (errcode_for_file_access(),
1893 errmsg("could not reopen file \"%s\" as stdout: %m",
1902 * Set or update the parameters for syslog logging
1905 set_syslog_parameters(const char *ident, int facility)
1908 * guc.c is likely to call us repeatedly with same parameters, so don't
1909 * thrash the syslog connection unnecessarily. Also, we do not re-open
1910 * the connection until needed, since this routine will get called whether
1911 * or not Log_destination actually mentions syslog.
1913 * Note that we make our own copy of the ident string rather than relying
1914 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1915 * accidentally free a string that syslog is still using.
1917 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1918 syslog_facility != facility)
1923 openlog_done = false;
1927 syslog_ident = strdup(ident);
1928 /* if the strdup fails, we will cope in write_syslog() */
1929 syslog_facility = facility;
1935 * Write a message line to syslog
1938 write_syslog(int level, const char *line)
1940 static unsigned long seq = 0;
1945 /* Open syslog connection if not done yet */
1948 openlog(syslog_ident ? syslog_ident : "postgres",
1949 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1951 openlog_done = true;
1955 * We add a sequence number to each log message to suppress "same"
1961 * Our problem here is that many syslog implementations don't handle long
1962 * messages in an acceptable manner. While this function doesn't help that
1963 * fact, it does work around by splitting up messages into smaller pieces.
1965 * We divide into multiple syslog() calls if message is too long or if the
1966 * message contains embedded newline(s).
1969 nlpos = strchr(line, '\n');
1970 if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
1976 char buf[PG_SYSLOG_LIMIT + 1];
1980 /* if we start at a newline, move ahead one char */
1981 if (line[0] == '\n')
1985 /* we need to recompute the next newline's position, too */
1986 nlpos = strchr(line, '\n');
1990 /* copy one line, or as much as will fit, to buf */
1992 buflen = nlpos - line;
1995 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1996 memcpy(buf, line, buflen);
1999 /* trim to multibyte letter boundary */
2000 buflen = pg_mbcliplen(buf, buflen, buflen);
2005 /* already word boundary? */
2006 if (line[buflen] != '\0' &&
2007 !isspace((unsigned char) line[buflen]))
2009 /* try to divide at word boundary */
2011 while (i > 0 && !isspace((unsigned char) buf[i]))
2014 if (i > 0) /* else couldn't divide word boundary */
2023 if (syslog_sequence_numbers)
2024 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2026 syslog(level, "[%d] %s", chunk_nr, buf);
2034 /* message short enough */
2035 if (syslog_sequence_numbers)
2036 syslog(level, "[%lu] %s", seq, line);
2038 syslog(level, "%s", line);
2041 #endif /* HAVE_SYSLOG */
2045 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
2046 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2047 * Every process in a given system will find the same value at all times.
2050 GetACPEncoding(void)
2052 static int encoding = -2;
2055 encoding = pg_codepage_to_encoding(GetACP());
2061 * Write a message line to the windows event log
2064 write_eventlog(int level, const char *line, int len)
2067 int eventlevel = EVENTLOG_ERROR_TYPE;
2068 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
2070 if (evtHandle == INVALID_HANDLE_VALUE)
2072 evtHandle = RegisterEventSource(NULL,
2073 event_source ? event_source : DEFAULT_EVENT_SOURCE);
2074 if (evtHandle == NULL)
2076 evtHandle = INVALID_HANDLE_VALUE;
2092 eventlevel = EVENTLOG_INFORMATION_TYPE;
2095 eventlevel = EVENTLOG_WARNING_TYPE;
2101 eventlevel = EVENTLOG_ERROR_TYPE;
2106 * If message character encoding matches the encoding expected by
2107 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2108 * try to convert the message to UTF16 and write it with ReportEventW().
2109 * Fall back on ReportEventA() if conversion failed.
2111 * Also verify that we are not on our way into error recursion trouble due
2112 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2114 if (!in_error_recursion_trouble() &&
2115 GetMessageEncoding() != GetACPEncoding())
2117 utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2120 ReportEventW(evtHandle,
2123 0, /* All events are Id 0 */
2129 /* XXX Try ReportEventA() when ReportEventW() fails? */
2135 ReportEventA(evtHandle,
2138 0, /* All events are Id 0 */
2148 write_console(const char *line, int len)
2155 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2156 * Fall back on write() if anything fails.
2158 * In contrast to write_eventlog(), don't skip straight to write() based
2159 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2160 * on the suitability of the console output code page. Since we put
2161 * stderr into binary mode in SubPostmasterMain(), write() skips the
2162 * necessary translation anyway.
2164 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2165 * to writing unconverted to the logfile in this case.
2167 * Since we palloc the structure required for conversion, also fall
2168 * through to writing unconverted if we have not yet set up
2169 * CurrentMemoryContext.
2171 if (!in_error_recursion_trouble() &&
2172 !redirection_done &&
2173 CurrentMemoryContext != NULL)
2178 utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2184 stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2185 if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2192 * In case WriteConsoleW() failed, fall back to writing the
2193 * message unconverted.
2201 * Conversion on non-win32 platforms is not implemented yet. It requires
2202 * non-throw version of pg_do_encoding_conversion(), that converts
2203 * unconvertable characters to '?' without errors.
2208 * We ignore any error from write() here. We have no useful way to report
2209 * it ... certainly whining on stderr isn't likely to be productive.
2211 rc = write(fileno(stderr), line, len);
2216 * setup formatted_log_time, for consistent times between CSV and regular logs
2219 setup_formatted_log_time(void)
2221 pg_time_t stamp_time;
2224 if (!saved_timeval_set)
2226 gettimeofday(&saved_timeval, NULL);
2227 saved_timeval_set = true;
2230 stamp_time = (pg_time_t) saved_timeval.tv_sec;
2233 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2234 * least with a minimal GMT value) before Log_line_prefix can become
2235 * nonempty or CSV mode can be selected.
2237 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
2238 /* leave room for milliseconds... */
2239 "%Y-%m-%d %H:%M:%S %Z",
2240 pg_localtime(&stamp_time, log_timezone));
2242 /* 'paste' milliseconds into place... */
2243 sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2244 memcpy(formatted_log_time + 19, msbuf, 4);
2248 * setup formatted_start_time
2251 setup_formatted_start_time(void)
2253 pg_time_t stamp_time = (pg_time_t) MyStartTime;
2256 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2257 * least with a minimal GMT value) before Log_line_prefix can become
2258 * nonempty or CSV mode can be selected.
2260 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
2261 "%Y-%m-%d %H:%M:%S %Z",
2262 pg_localtime(&stamp_time, log_timezone));
2266 * process_log_prefix_padding --- helper function for processing the format
2267 * string in log_line_prefix
2269 * Note: This function returns NULL if it finds something which
2270 * it deems invalid in the format string.
2273 process_log_prefix_padding(const char *p, int *ppadding)
2275 int paddingsign = 1;
2282 if (*p == '\0') /* Did the buf end in %- ? */
2287 /* generate an int version of the numerical string */
2288 while (*p >= '0' && *p <= '9')
2289 padding = padding * 10 + (*p++ - '0');
2291 /* format is invalid if it ends with the padding number */
2295 padding *= paddingsign;
2296 *ppadding = padding;
2301 * Format tag info for log lines; append to the provided buffer.
2304 log_line_prefix(StringInfo buf, ErrorData *edata)
2306 /* static counter for line numbers */
2307 static long log_line_number = 0;
2309 /* has counter been reset in current process? */
2310 static int log_my_pid = 0;
2315 * This is one of the few places where we'd rather not inherit a static
2316 * variable's value from the postmaster. But since we will, reset it when
2317 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2318 * reset the formatted start timestamp too.
2320 if (log_my_pid != MyProcPid)
2322 log_line_number = 0;
2323 log_my_pid = MyProcPid;
2324 formatted_start_time[0] = '\0';
2328 if (Log_line_prefix == NULL)
2329 return; /* in case guc hasn't run yet */
2331 for (p = Log_line_prefix; *p != '\0'; p++)
2335 /* literal char, just copy */
2336 appendStringInfoChar(buf, *p);
2340 /* must be a '%', so skip to the next char */
2343 break; /* format error - ignore it */
2346 /* string contains %% */
2347 appendStringInfoChar(buf, '%');
2353 * Process any formatting which may exist after the '%'. Note that
2354 * process_log_prefix_padding moves p past the padding number if it
2357 * Note: Since only '-', '0' to '9' are valid formatting characters we
2358 * can do a quick check here to pre-check for formatting. If the char
2359 * is not formatting then we can skip a useless function call.
2361 * Further note: At least on some platforms, passing %*s rather than
2362 * %s to appendStringInfo() is substantially slower, so many of the
2363 * cases below avoid doing that unless non-zero padding is in fact
2368 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2371 /* process the option */
2377 const char *appname = application_name;
2379 if (appname == NULL || *appname == '\0')
2380 appname = _("[unknown]");
2382 appendStringInfo(buf, "%*s", padding, appname);
2384 appendStringInfoString(buf, appname);
2386 else if (padding != 0)
2387 appendStringInfoSpaces(buf,
2388 padding > 0 ? padding : -padding);
2394 const char *username = MyProcPort->user_name;
2396 if (username == NULL || *username == '\0')
2397 username = _("[unknown]");
2399 appendStringInfo(buf, "%*s", padding, username);
2401 appendStringInfoString(buf, username);
2403 else if (padding != 0)
2404 appendStringInfoSpaces(buf,
2405 padding > 0 ? padding : -padding);
2410 const char *dbname = MyProcPort->database_name;
2412 if (dbname == NULL || *dbname == '\0')
2413 dbname = _("[unknown]");
2415 appendStringInfo(buf, "%*s", padding, dbname);
2417 appendStringInfoString(buf, dbname);
2419 else if (padding != 0)
2420 appendStringInfoSpaces(buf,
2421 padding > 0 ? padding : -padding);
2428 snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2429 (long) (MyStartTime), MyProcPid);
2430 appendStringInfo(buf, "%*s", padding, strfbuf);
2433 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2437 appendStringInfo(buf, "%*d", padding, MyProcPid);
2439 appendStringInfo(buf, "%d", MyProcPid);
2443 appendStringInfo(buf, "%*ld", padding, log_line_number);
2445 appendStringInfo(buf, "%ld", log_line_number);
2448 setup_formatted_log_time();
2450 appendStringInfo(buf, "%*s", padding, formatted_log_time);
2452 appendStringInfoString(buf, formatted_log_time);
2456 pg_time_t stamp_time = (pg_time_t) time(NULL);
2459 pg_strftime(strfbuf, sizeof(strfbuf),
2460 "%Y-%m-%d %H:%M:%S %Z",
2461 pg_localtime(&stamp_time, log_timezone));
2463 appendStringInfo(buf, "%*s", padding, strfbuf);
2465 appendStringInfoString(buf, strfbuf);
2472 if (!saved_timeval_set)
2474 gettimeofday(&saved_timeval, NULL);
2475 saved_timeval_set = true;
2478 sprintf(strfbuf, "%ld.%03d", saved_timeval.tv_sec,
2479 (int)(saved_timeval.tv_usec / 1000));
2482 appendStringInfo(buf, "%*s", padding, strfbuf);
2484 appendStringInfoString(buf, strfbuf);
2488 if (formatted_start_time[0] == '\0')
2489 setup_formatted_start_time();
2491 appendStringInfo(buf, "%*s", padding, formatted_start_time);
2493 appendStringInfoString(buf, formatted_start_time);
2501 psdisp = get_ps_display(&displen);
2503 appendStringInfo(buf, "%*s", padding, psdisp);
2505 appendBinaryStringInfo(buf, psdisp, displen);
2508 else if (padding != 0)
2509 appendStringInfoSpaces(buf,
2510 padding > 0 ? padding : -padding);
2513 if (MyProcPort && MyProcPort->remote_host)
2517 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2520 * This option is slightly special as the port
2521 * number may be appended onto the end. Here we
2522 * need to build 1 string which contains the
2523 * remote_host and optionally the remote_port (if
2524 * set) so we can properly align the string.
2529 hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2530 appendStringInfo(buf, "%*s", padding, hostport);
2534 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2538 /* padding is 0, so we don't need a temp buffer */
2539 appendStringInfoString(buf, MyProcPort->remote_host);
2540 if (MyProcPort->remote_port &&
2541 MyProcPort->remote_port[0] != '\0')
2542 appendStringInfo(buf, "(%s)",
2543 MyProcPort->remote_port);
2547 else if (padding != 0)
2548 appendStringInfoSpaces(buf,
2549 padding > 0 ? padding : -padding);
2552 if (MyProcPort && MyProcPort->remote_host)
2555 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2557 appendStringInfoString(buf, MyProcPort->remote_host);
2559 else if (padding != 0)
2560 appendStringInfoSpaces(buf,
2561 padding > 0 ? padding : -padding);
2564 /* in postmaster and friends, stop if %q is seen */
2565 /* in a backend, just ignore */
2566 if (MyProcPort == NULL)
2570 /* keep VXID format in sync with lockfuncs.c */
2571 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2577 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2578 MyProc->backendId, MyProc->lxid);
2579 appendStringInfo(buf, "%*s", padding, strfbuf);
2582 appendStringInfo(buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2584 else if (padding != 0)
2585 appendStringInfoSpaces(buf,
2586 padding > 0 ? padding : -padding);
2590 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2592 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2596 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2598 appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2601 /* format error - ignore it */
2608 * append a CSV'd version of a string to a StringInfo
2609 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2610 * If it's NULL, append nothing.
2613 appendCSVLiteral(StringInfo buf, const char *data)
2615 const char *p = data;
2618 /* avoid confusing an empty string with NULL */
2622 appendStringInfoCharMacro(buf, '"');
2623 while ((c = *p++) != '\0')
2626 appendStringInfoCharMacro(buf, '"');
2627 appendStringInfoCharMacro(buf, c);
2629 appendStringInfoCharMacro(buf, '"');
2633 * Constructs the error message, depending on the Errordata it gets, in a CSV
2634 * format which is described in doc/src/sgml/config.sgml.
2637 write_csvlog(ErrorData *edata)
2640 bool print_stmt = false;
2642 /* static counter for line numbers */
2643 static long log_line_number = 0;
2645 /* has counter been reset in current process? */
2646 static int log_my_pid = 0;
2649 * This is one of the few places where we'd rather not inherit a static
2650 * variable's value from the postmaster. But since we will, reset it when
2651 * MyProcPid changes.
2653 if (log_my_pid != MyProcPid)
2655 log_line_number = 0;
2656 log_my_pid = MyProcPid;
2657 formatted_start_time[0] = '\0';
2661 initStringInfo(&buf);
2664 * timestamp with milliseconds
2666 * Check if the timestamp is already calculated for the syslog message,
2667 * and use it if so. Otherwise, get the current timestamp. This is done
2668 * to put same timestamp in both syslog and csvlog messages.
2670 if (formatted_log_time[0] == '\0')
2671 setup_formatted_log_time();
2673 appendStringInfoString(&buf, formatted_log_time);
2674 appendStringInfoChar(&buf, ',');
2678 appendCSVLiteral(&buf, MyProcPort->user_name);
2679 appendStringInfoChar(&buf, ',');
2683 appendCSVLiteral(&buf, MyProcPort->database_name);
2684 appendStringInfoChar(&buf, ',');
2688 appendStringInfo(&buf, "%d", MyProcPid);
2689 appendStringInfoChar(&buf, ',');
2691 /* Remote host and port */
2692 if (MyProcPort && MyProcPort->remote_host)
2694 appendStringInfoChar(&buf, '"');
2695 appendStringInfoString(&buf, MyProcPort->remote_host);
2696 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2698 appendStringInfoChar(&buf, ':');
2699 appendStringInfoString(&buf, MyProcPort->remote_port);
2701 appendStringInfoChar(&buf, '"');
2703 appendStringInfoChar(&buf, ',');
2706 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2707 appendStringInfoChar(&buf, ',');
2710 appendStringInfo(&buf, "%ld", log_line_number);
2711 appendStringInfoChar(&buf, ',');
2716 StringInfoData msgbuf;
2720 initStringInfo(&msgbuf);
2722 psdisp = get_ps_display(&displen);
2723 appendBinaryStringInfo(&msgbuf, psdisp, displen);
2724 appendCSVLiteral(&buf, msgbuf.data);
2728 appendStringInfoChar(&buf, ',');
2730 /* session start timestamp */
2731 if (formatted_start_time[0] == '\0')
2732 setup_formatted_start_time();
2733 appendStringInfoString(&buf, formatted_start_time);
2734 appendStringInfoChar(&buf, ',');
2736 /* Virtual transaction id */
2737 /* keep VXID format in sync with lockfuncs.c */
2738 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2739 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2740 appendStringInfoChar(&buf, ',');
2742 /* Transaction id */
2743 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2744 appendStringInfoChar(&buf, ',');
2746 /* Error severity */
2747 appendStringInfoString(&buf, error_severity(edata->elevel));
2748 appendStringInfoChar(&buf, ',');
2750 /* SQL state code */
2751 appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2752 appendStringInfoChar(&buf, ',');
2755 appendCSVLiteral(&buf, edata->message);
2756 appendStringInfoChar(&buf, ',');
2758 /* errdetail or errdetail_log */
2759 if (edata->detail_log)
2760 appendCSVLiteral(&buf, edata->detail_log);
2762 appendCSVLiteral(&buf, edata->detail);
2763 appendStringInfoChar(&buf, ',');
2766 appendCSVLiteral(&buf, edata->hint);
2767 appendStringInfoChar(&buf, ',');
2769 /* internal query */
2770 appendCSVLiteral(&buf, edata->internalquery);
2771 appendStringInfoChar(&buf, ',');
2773 /* if printed internal query, print internal pos too */
2774 if (edata->internalpos > 0 && edata->internalquery != NULL)
2775 appendStringInfo(&buf, "%d", edata->internalpos);
2776 appendStringInfoChar(&buf, ',');
2779 if (!edata->hide_ctx)
2780 appendCSVLiteral(&buf, edata->context);
2781 appendStringInfoChar(&buf, ',');
2783 /* user query --- only reported if not disabled by the caller */
2784 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2785 debug_query_string != NULL &&
2789 appendCSVLiteral(&buf, debug_query_string);
2790 appendStringInfoChar(&buf, ',');
2791 if (print_stmt && edata->cursorpos > 0)
2792 appendStringInfo(&buf, "%d", edata->cursorpos);
2793 appendStringInfoChar(&buf, ',');
2795 /* file error location */
2796 if (Log_error_verbosity >= PGERROR_VERBOSE)
2798 StringInfoData msgbuf;
2800 initStringInfo(&msgbuf);
2802 if (edata->funcname && edata->filename)
2803 appendStringInfo(&msgbuf, "%s, %s:%d",
2804 edata->funcname, edata->filename,
2806 else if (edata->filename)
2807 appendStringInfo(&msgbuf, "%s:%d",
2808 edata->filename, edata->lineno);
2809 appendCSVLiteral(&buf, msgbuf.data);
2812 appendStringInfoChar(&buf, ',');
2814 /* application name */
2815 if (application_name)
2816 appendCSVLiteral(&buf, application_name);
2818 appendStringInfoChar(&buf, '\n');
2820 /* If in the syslogger process, try to write messages direct to file */
2822 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2824 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2830 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2834 unpack_sql_state(int sql_state)
2836 static char buf[12];
2839 for (i = 0; i < 5; i++)
2841 buf[i] = PGUNSIXBIT(sql_state);
2851 * Write error report to server's log
2854 send_message_to_server_log(ErrorData *edata)
2858 initStringInfo(&buf);
2860 saved_timeval_set = false;
2861 formatted_log_time[0] = '\0';
2863 log_line_prefix(&buf, edata);
2864 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2866 if (Log_error_verbosity >= PGERROR_VERBOSE)
2867 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2870 append_with_tabs(&buf, edata->message);
2872 append_with_tabs(&buf, _("missing error text"));
2874 if (edata->cursorpos > 0)
2875 appendStringInfo(&buf, _(" at character %d"),
2877 else if (edata->internalpos > 0)
2878 appendStringInfo(&buf, _(" at character %d"),
2879 edata->internalpos);
2881 appendStringInfoChar(&buf, '\n');
2883 if (Log_error_verbosity >= PGERROR_DEFAULT)
2885 if (edata->detail_log)
2887 log_line_prefix(&buf, edata);
2888 appendStringInfoString(&buf, _("DETAIL: "));
2889 append_with_tabs(&buf, edata->detail_log);
2890 appendStringInfoChar(&buf, '\n');
2892 else if (edata->detail)
2894 log_line_prefix(&buf, edata);
2895 appendStringInfoString(&buf, _("DETAIL: "));
2896 append_with_tabs(&buf, edata->detail);
2897 appendStringInfoChar(&buf, '\n');
2901 log_line_prefix(&buf, edata);
2902 appendStringInfoString(&buf, _("HINT: "));
2903 append_with_tabs(&buf, edata->hint);
2904 appendStringInfoChar(&buf, '\n');
2906 if (edata->internalquery)
2908 log_line_prefix(&buf, edata);
2909 appendStringInfoString(&buf, _("QUERY: "));
2910 append_with_tabs(&buf, edata->internalquery);
2911 appendStringInfoChar(&buf, '\n');
2913 if (edata->context && !edata->hide_ctx)
2915 log_line_prefix(&buf, edata);
2916 appendStringInfoString(&buf, _("CONTEXT: "));
2917 append_with_tabs(&buf, edata->context);
2918 appendStringInfoChar(&buf, '\n');
2920 if (Log_error_verbosity >= PGERROR_VERBOSE)
2922 /* assume no newlines in funcname or filename... */
2923 if (edata->funcname && edata->filename)
2925 log_line_prefix(&buf, edata);
2926 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2927 edata->funcname, edata->filename,
2930 else if (edata->filename)
2932 log_line_prefix(&buf, edata);
2933 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2934 edata->filename, edata->lineno);
2940 * If the user wants the query that generated this error logged, do it.
2942 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2943 debug_query_string != NULL &&
2946 log_line_prefix(&buf, edata);
2947 appendStringInfoString(&buf, _("STATEMENT: "));
2948 append_with_tabs(&buf, debug_query_string);
2949 appendStringInfoChar(&buf, '\n');
2953 /* Write to syslog, if enabled */
2954 if (Log_destination & LOG_DESTINATION_SYSLOG)
2958 switch (edata->elevel)
2965 syslog_level = LOG_DEBUG;
2970 syslog_level = LOG_INFO;
2974 syslog_level = LOG_NOTICE;
2977 syslog_level = LOG_WARNING;
2980 syslog_level = LOG_ERR;
2984 syslog_level = LOG_CRIT;
2988 write_syslog(syslog_level, buf.data);
2990 #endif /* HAVE_SYSLOG */
2993 /* Write to eventlog, if enabled */
2994 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2996 write_eventlog(edata->elevel, buf.data, buf.len);
3000 /* Write to stderr, if enabled */
3001 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
3004 * Use the chunking protocol if we know the syslogger should be
3005 * catching stderr output, and we are not ourselves the syslogger.
3006 * Otherwise, just do a vanilla write to stderr.
3008 if (redirection_done && !am_syslogger)
3009 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
3013 * In a win32 service environment, there is no usable stderr. Capture
3014 * anything going there and write it to the eventlog instead.
3016 * If stderr redirection is active, it was OK to write to stderr above
3017 * because that's really a pipe to the syslogger process.
3019 else if (pgwin32_is_service())
3020 write_eventlog(edata->elevel, buf.data, buf.len);
3023 write_console(buf.data, buf.len);
3026 /* If in the syslogger process, try to write messages direct to file */
3028 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
3030 /* Write to CSV log if enabled */
3031 if (Log_destination & LOG_DESTINATION_CSVLOG)
3033 if (redirection_done || am_syslogger)
3036 * send CSV data if it's safe to do so (syslogger doesn't need the
3037 * pipe). First get back the space in the message buffer.
3040 write_csvlog(edata);
3045 * syslogger not up (yet), so just dump the message to stderr,
3046 * unless we already did so above.
3048 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
3049 whereToSendOutput != DestDebug)
3050 write_console(buf.data, buf.len);
3061 * Send data to the syslogger using the chunked protocol
3063 * Note: when there are multiple backends writing into the syslogger pipe,
3064 * it's critical that each write go into the pipe indivisibly, and not
3065 * get interleaved with data from other processes. Fortunately, the POSIX
3066 * spec requires that writes to pipes be atomic so long as they are not
3067 * more than PIPE_BUF bytes long. So we divide long messages into chunks
3068 * that are no more than that length, and send one chunk per write() call.
3069 * The collector process knows how to reassemble the chunks.
3071 * Because of the atomic write requirement, there are only two possible
3072 * results from write() here: -1 for failure, or the requested number of
3073 * bytes. There is not really anything we can do about a failure; retry would
3074 * probably be an infinite loop, and we can't even report the error usefully.
3075 * (There is noplace else we could send it!) So we might as well just ignore
3076 * the result from write(). However, on some platforms you get a compiler
3077 * warning from ignoring write()'s result, so do a little dance with casting
3078 * rc to void to shut up the compiler.
3081 write_pipe_chunks(char *data, int len, int dest)
3084 int fd = fileno(stderr);
3089 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3090 p.proto.pid = MyProcPid;
3092 /* write all but the last chunk */
3093 while (len > PIPE_MAX_PAYLOAD)
3095 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
3096 p.proto.len = PIPE_MAX_PAYLOAD;
3097 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
3098 rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
3100 data += PIPE_MAX_PAYLOAD;
3101 len -= PIPE_MAX_PAYLOAD;
3104 /* write the last chunk */
3105 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
3107 memcpy(p.proto.data, data, len);
3108 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3114 * Append a text string to the error report being built for the client.
3116 * This is ordinarily identical to pq_sendstring(), but if we are in
3117 * error recursion trouble we skip encoding conversion, because of the
3118 * possibility that the problem is a failure in the encoding conversion
3119 * subsystem itself. Code elsewhere should ensure that the passed-in
3120 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3121 * in such cases. (In particular, we disable localization of error messages
3122 * to help ensure that's true.)
3125 err_sendstring(StringInfo buf, const char *str)
3127 if (in_error_recursion_trouble())
3128 pq_send_ascii_string(buf, str);
3130 pq_sendstring(buf, str);
3134 * Write error report to client
3137 send_message_to_frontend(ErrorData *edata)
3139 StringInfoData msgbuf;
3141 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3142 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
3144 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
3146 /* New style with separate fields */
3151 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3152 err_sendstring(&msgbuf, error_severity(edata->elevel));
3154 /* unpack MAKE_SQLSTATE code */
3155 ssval = edata->sqlerrcode;
3156 for (i = 0; i < 5; i++)
3158 tbuf[i] = PGUNSIXBIT(ssval);
3163 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3164 err_sendstring(&msgbuf, tbuf);
3166 /* M field is required per protocol, so always send something */
3167 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
3169 err_sendstring(&msgbuf, edata->message);
3171 err_sendstring(&msgbuf, _("missing error text"));
3175 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
3176 err_sendstring(&msgbuf, edata->detail);
3179 /* detail_log is intentionally not used here */
3183 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
3184 err_sendstring(&msgbuf, edata->hint);
3189 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3190 err_sendstring(&msgbuf, edata->context);
3193 if (edata->schema_name)
3195 pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3196 err_sendstring(&msgbuf, edata->schema_name);
3199 if (edata->table_name)
3201 pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3202 err_sendstring(&msgbuf, edata->table_name);
3205 if (edata->column_name)
3207 pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3208 err_sendstring(&msgbuf, edata->column_name);
3211 if (edata->datatype_name)
3213 pq_sendbyte(&msgbuf, PG_DIAG_DATATYPE_NAME);
3214 err_sendstring(&msgbuf, edata->datatype_name);
3217 if (edata->constraint_name)
3219 pq_sendbyte(&msgbuf, PG_DIAG_CONSTRAINT_NAME);
3220 err_sendstring(&msgbuf, edata->constraint_name);
3223 if (edata->cursorpos > 0)
3225 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3226 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
3227 err_sendstring(&msgbuf, tbuf);
3230 if (edata->internalpos > 0)
3232 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3233 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
3234 err_sendstring(&msgbuf, tbuf);
3237 if (edata->internalquery)
3239 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
3240 err_sendstring(&msgbuf, edata->internalquery);
3243 if (edata->filename)
3245 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3246 err_sendstring(&msgbuf, edata->filename);
3249 if (edata->lineno > 0)
3251 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3252 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3253 err_sendstring(&msgbuf, tbuf);
3256 if (edata->funcname)
3258 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
3259 err_sendstring(&msgbuf, edata->funcname);
3262 pq_sendbyte(&msgbuf, '\0'); /* terminator */
3266 /* Old style --- gin up a backwards-compatible message */
3269 initStringInfo(&buf);
3271 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
3273 if (edata->show_funcname && edata->funcname)
3274 appendStringInfo(&buf, "%s: ", edata->funcname);
3277 appendStringInfoString(&buf, edata->message);
3279 appendStringInfoString(&buf, _("missing error text"));
3281 if (edata->cursorpos > 0)
3282 appendStringInfo(&buf, _(" at character %d"),
3284 else if (edata->internalpos > 0)
3285 appendStringInfo(&buf, _(" at character %d"),
3286 edata->internalpos);
3288 appendStringInfoChar(&buf, '\n');
3290 err_sendstring(&msgbuf, buf.data);
3295 pq_endmessage(&msgbuf);
3298 * This flush is normally not necessary, since postgres.c will flush out
3299 * waiting data when control returns to the main loop. But it seems best
3300 * to leave it here, so that the client has some clue what happened if the
3301 * backend dies before getting back to the main loop ... error/notice
3302 * messages should not be a performance-critical path anyway, so an extra
3303 * flush won't hurt much ...
3310 * Support routines for formatting error messages.
3315 * expand_fmt_string --- process special format codes in a format string
3317 * We must replace %m with the appropriate strerror string, since vsnprintf
3318 * won't know what to do with it.
3320 * The result is a palloc'd string.
3323 expand_fmt_string(const char *fmt, ErrorData *edata)
3328 initStringInfo(&buf);
3330 for (cp = fmt; *cp; cp++)
3332 if (cp[0] == '%' && cp[1] != '\0')
3338 * Replace %m by system error string. If there are any %'s in
3339 * the string, we'd better double them so that vsnprintf won't
3344 cp2 = useful_strerror(edata->saved_errno);
3348 appendStringInfoCharMacro(&buf, '%');
3349 appendStringInfoCharMacro(&buf, *cp2);
3354 /* copy % and next char --- this avoids trouble with %%m */
3355 appendStringInfoCharMacro(&buf, '%');
3356 appendStringInfoCharMacro(&buf, *cp);
3360 appendStringInfoCharMacro(&buf, *cp);
3368 * A slightly cleaned-up version of strerror()
3371 useful_strerror(int errnum)
3373 /* this buffer is only used if strerror() and get_errno_symbol() fail */
3374 static char errorstr_buf[48];
3378 /* Winsock error code range, per WinError.h */
3379 if (errnum >= 10000 && errnum <= 11999)
3380 return pgwin32_socket_strerror(errnum);
3382 str = strerror(errnum);
3385 * Some strerror()s return an empty string for out-of-range errno. This
3386 * is ANSI C spec compliant, but not exactly useful. Also, we may get
3387 * back strings of question marks if libc cannot transcode the message to
3388 * the codeset specified by LC_CTYPE. If we get nothing useful, first try
3389 * get_errno_symbol(), and if that fails, print the numeric errno.
3391 if (str == NULL || *str == '\0' || *str == '?')
3392 str = get_errno_symbol(errnum);
3396 snprintf(errorstr_buf, sizeof(errorstr_buf),
3398 translator: This string will be truncated at 47
3399 characters expanded. */
3400 _("operating system error %d"), errnum);
3408 * Returns a symbol (e.g. "ENOENT") for an errno code.
3409 * Returns NULL if the code is unrecognized.
3412 get_errno_symbol(int errnum)
3422 return "EADDRINUSE";
3424 #ifdef EADDRNOTAVAIL
3426 return "EADDRNOTAVAIL";
3429 return "EAFNOSUPPORT";
3450 return "ECONNABORTED";
3453 return "ECONNREFUSED";
3456 return "ECONNRESET";
3470 return "EHOSTUNREACH";
3475 return "EINPROGRESS";
3499 return "ENAMETOOLONG";
3522 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
3538 #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP))
3540 return "EOPNOTSUPP";
3550 case EPROTONOSUPPORT:
3551 return "EPROTONOSUPPORT";
3568 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
3570 return "EWOULDBLOCK";
3581 * error_severity --- get localized string representing elevel
3584 error_severity(int elevel)
3595 prefix = _("DEBUG");
3605 prefix = _("NOTICE");
3608 prefix = _("WARNING");
3611 prefix = _("ERROR");
3614 prefix = _("FATAL");
3617 prefix = _("PANIC");
3631 * Append the string to the StringInfo buffer, inserting a tab after any
3635 append_with_tabs(StringInfo buf, const char *str)
3639 while ((ch = *str++) != '\0')
3641 appendStringInfoCharMacro(buf, ch);
3643 appendStringInfoCharMacro(buf, '\t');
3649 * Write errors to stderr (or by equal means when stderr is
3650 * not available). Used before ereport/elog can be used
3651 * safely (memory context, GUC load etc)
3654 write_stderr(const char *fmt,...)
3659 char errbuf[2048]; /* Arbitrary size? */
3666 /* On Unix, we just fprintf to stderr */
3667 vfprintf(stderr, fmt, ap);
3670 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3673 * On Win32, we print to stderr if running on a console, or write to
3674 * eventlog if running as a service
3676 if (pgwin32_is_service()) /* Running as a service */
3678 write_eventlog(ERROR, errbuf, strlen(errbuf));
3682 /* Not running as service, write to stderr */
3683 write_console(errbuf, strlen(errbuf));
3692 * is_log_level_output -- is elevel logically >= log_min_level?
3694 * We use this for tests that should consider LOG to sort out-of-order,
3695 * between ERROR and FATAL. Generally this is the right thing for testing
3696 * whether a message should go to the postmaster log, whereas a simple >=
3697 * test is correct for testing whether the message should go to the client.
3700 is_log_level_output(int elevel, int log_min_level)
3702 if (elevel == LOG || elevel == COMMERROR)
3704 if (log_min_level == LOG || log_min_level <= ERROR)
3707 else if (log_min_level == LOG)
3710 if (elevel >= FATAL)
3713 /* Neither is LOG */
3714 else if (elevel >= log_min_level)
3721 * Adjust the level of a recovery-related message per trace_recovery_messages.
3723 * The argument is the default log level of the message, eg, DEBUG2. (This
3724 * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3725 * If the level is >= trace_recovery_messages, we return LOG, causing the
3726 * message to be logged unconditionally (for most settings of
3727 * log_min_messages). Otherwise, we return the argument unchanged.
3728 * The message will then be shown based on the setting of log_min_messages.
3730 * Intention is to keep this for at least the whole of the 9.0 production
3731 * release, so we can more easily diagnose production problems in the field.
3732 * It should go away eventually, though, because it's an ugly and
3733 * hard-to-explain kluge.
3736 trace_recovery(int trace_level)
3738 if (trace_level < LOG &&
3739 trace_level >= trace_recovery_messages)