1 /*-------------------------------------------------------------------------
4 * error logging and reporting
6 * Some notes about recursion and errors during error processing:
8 * We need to be robust about recursive-error scenarios --- for example,
9 * if we run out of memory, it's important to be able to report that fact.
10 * There are a number of considerations that go into this.
12 * First, distinguish between re-entrant use and actual recursion. It
13 * is possible for an error or warning message to be emitted while the
14 * parameters for an error message are being computed. In this case
15 * errstart has been called for the outer message, and some field values
16 * may have already been saved, but we are not actually recursing. We handle
17 * this by providing a (small) stack of ErrorData records. The inner message
18 * can be computed and sent without disturbing the state of the outer message.
19 * (If the inner message is actually an error, this isn't very interesting
20 * because control won't come back to the outer message generator ... but
21 * if the inner message is only debug or log data, this is critical.)
23 * Second, actual recursion will occur if an error is reported by one of
24 * the elog.c routines or something they call. By far the most probable
25 * scenario of this sort is "out of memory"; and it's also the nastiest
26 * to handle because we'd likely also run out of memory while trying to
27 * report this error! Our escape hatch for this case is to reset the
28 * ErrorContext to empty before trying to process the inner error. Since
29 * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
30 * we should be able to process an "out of memory" message successfully.
31 * Since we lose the prior error state due to the reset, we won't be able
32 * to return to processing the original error, but we wouldn't have anyway.
33 * (NOTE: the escape hatch is not used for recursive situations where the
34 * inner message is of less than ERROR severity; in that case we just
35 * try to process it and return normally. Usually this will work, but if
36 * it ends up in infinite recursion, we will PANIC due to error stack
40 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
41 * Portions Copyright (c) 1994, Regents of the University of California
45 * $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.214 2009/06/04 18:33:07 tgl Exp $
47 *-------------------------------------------------------------------------
60 #include "access/transam.h"
61 #include "access/xact.h"
62 #include "libpq/libpq.h"
63 #include "libpq/pqformat.h"
64 #include "mb/pg_wchar.h"
65 #include "miscadmin.h"
66 #include "postmaster/postmaster.h"
67 #include "postmaster/syslogger.h"
68 #include "storage/ipc.h"
69 #include "storage/proc.h"
70 #include "tcop/tcopprot.h"
71 #include "utils/memutils.h"
72 #include "utils/ps_status.h"
76 #define _(x) err_gettext(x)
78 /* Global variables */
79 ErrorContextCallback *error_context_stack = NULL;
81 sigjmp_buf *PG_exception_stack = NULL;
83 extern bool redirection_done;
86 int Log_error_verbosity = PGERROR_VERBOSE;
87 char *Log_line_prefix = NULL; /* format for extra log line info */
88 int Log_destination = LOG_DESTINATION_STDERR;
93 * Max string length to send to syslog(). Note that this doesn't count the
94 * sequence-number prefix we add, and of course it doesn't count the prefix
95 * added by syslog itself. On many implementations it seems that the hard
96 * limit is approximately 2K bytes including both those prefixes.
98 #ifndef PG_SYSLOG_LIMIT
99 #define PG_SYSLOG_LIMIT 1024
102 static bool openlog_done = false;
103 static char *syslog_ident = NULL;
104 static int syslog_facility = LOG_LOCAL0;
106 static void write_syslog(int level, const char *line);
110 static void write_eventlog(int level, const char *line);
113 /* We provide a small stack of ErrorData records for re-entrant cases */
114 #define ERRORDATA_STACK_SIZE 5
116 static ErrorData errordata[ERRORDATA_STACK_SIZE];
118 static int errordata_stack_depth = -1; /* index of topmost active frame */
120 static int recursion_depth = 0; /* to detect actual recursion */
122 /* buffers for formatted timestamps that might be used by both
123 * log_line_prefix and csv logs.
126 #define FORMATTED_TS_LEN 128
127 static char formatted_start_time[FORMATTED_TS_LEN];
128 static char formatted_log_time[FORMATTED_TS_LEN];
131 /* Macro for checking errordata_stack_depth is reasonable */
132 #define CHECK_STACK_DEPTH() \
134 if (errordata_stack_depth < 0) \
136 errordata_stack_depth = -1; \
137 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
142 static void log_line_prefix(StringInfo buf);
143 static void send_message_to_server_log(ErrorData *edata);
144 static void send_message_to_frontend(ErrorData *edata);
145 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
146 static const char *useful_strerror(int errnum);
147 static const char *error_severity(int elevel);
148 static void append_with_tabs(StringInfo buf, const char *str);
149 static bool is_log_level_output(int elevel, int log_min_level);
150 static void write_pipe_chunks(char *data, int len, int dest);
151 static void write_csvlog(ErrorData *edata);
152 static void setup_formatted_log_time(void);
153 static void setup_formatted_start_time(void);
157 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
159 * This function exists to provide common control of various fallback steps
160 * that we take if we think we are facing infinite error recursion. See the
161 * callers for details.
164 in_error_recursion_trouble(void)
166 /* Pull the plug if recurse more than once */
167 return (recursion_depth > 2);
171 * One of those fallback steps is to stop trying to localize the error
172 * message, since there's a significant probability that that's exactly
173 * what's causing the recursion.
175 static inline const char *
176 err_gettext(const char *str)
179 if (in_error_recursion_trouble())
190 * errstart --- begin an error-reporting cycle
192 * Create a stack entry and store the given parameters in it. Subsequently,
193 * errmsg() and perhaps other routines will be called to further populate
194 * the stack entry. Finally, errfinish() will be called to actually process
197 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
198 * report (if it's a warning or lower and not to be reported anywhere).
201 errstart(int elevel, const char *filename, int lineno,
202 const char *funcname, const char *domain)
205 bool output_to_server;
206 bool output_to_client = false;
210 * Check some cases in which we want to promote an error into a more
211 * severe error. None of this logic applies for non-error messages.
216 * If we are inside a critical section, all errors become PANIC
217 * errors. See miscadmin.h.
219 if (CritSectionCount > 0)
223 * Check reasons for treating ERROR as FATAL:
225 * 1. we have no handler to pass the error to (implies we are in the
226 * postmaster or in backend startup).
228 * 2. ExitOnAnyError mode switch is set (initdb uses this).
230 * 3. the error occurred after proc_exit has begun to run. (It's
231 * proc_exit's responsibility to see that this doesn't turn into
232 * infinite recursion!)
236 if (PG_exception_stack == NULL ||
238 proc_exit_inprogress)
243 * If the error level is ERROR or more, errfinish is not going to
244 * return to caller; therefore, if there is any stacked error already
245 * in progress it will be lost. This is more or less okay, except we
246 * do not want to have a FATAL or PANIC error downgraded because the
247 * reporting process was interrupted by a lower-grade error. So check
248 * the stack and make sure we panic if panic is warranted.
250 for (i = 0; i <= errordata_stack_depth; i++)
251 elevel = Max(elevel, errordata[i].elevel);
255 * Now decide whether we need to process this report at all; if it's
256 * warning or less and not enabled for logging, just return FALSE without
257 * starting up any error logging machinery.
260 /* Determine whether message is enabled for server log output */
261 if (IsPostmasterEnvironment)
262 output_to_server = is_log_level_output(elevel, log_min_messages);
264 /* In bootstrap/standalone case, do not sort LOG out-of-order */
265 output_to_server = (elevel >= log_min_messages);
267 /* Determine whether message is enabled for client output */
268 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
271 * client_min_messages is honored only after we complete the
272 * authentication handshake. This is required both for security
273 * reasons and because many clients can't handle NOTICE messages
274 * during authentication.
276 if (ClientAuthInProgress)
277 output_to_client = (elevel >= ERROR);
279 output_to_client = (elevel >= client_min_messages ||
283 /* Skip processing effort if non-error message will not be output */
284 if (elevel < ERROR && !output_to_server && !output_to_client)
288 * Okay, crank up a stack entry to store the info in.
291 if (recursion_depth++ > 0 && elevel >= ERROR)
294 * Ooops, error during error processing. Clear ErrorContext as
295 * discussed at top of file. We will not return to the original
296 * error's reporter or handler, so we don't need it.
298 MemoryContextReset(ErrorContext);
301 * Infinite error recursion might be due to something broken
302 * in a context traceback routine. Abandon them too. We also abandon
303 * attempting to print the error statement (which, if long, could
304 * itself be the source of the recursive failure).
306 if (in_error_recursion_trouble())
308 error_context_stack = NULL;
309 debug_query_string = NULL;
312 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
315 * Wups, stack not big enough. We treat this as a PANIC condition
316 * because it suggests an infinite loop of errors during error
319 errordata_stack_depth = -1; /* make room on stack */
320 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
323 /* Initialize data for this error frame */
324 edata = &errordata[errordata_stack_depth];
325 MemSet(edata, 0, sizeof(ErrorData));
326 edata->elevel = elevel;
327 edata->output_to_server = output_to_server;
328 edata->output_to_client = output_to_client;
329 edata->filename = filename;
330 edata->lineno = lineno;
331 edata->funcname = funcname;
332 /* the default text domain is the backend's */
333 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
334 /* Select default errcode based on elevel */
336 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
337 else if (elevel == WARNING)
338 edata->sqlerrcode = ERRCODE_WARNING;
340 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
341 /* errno is saved here so that error parameter eval can't change it */
342 edata->saved_errno = errno;
349 * errfinish --- end an error-reporting cycle
351 * Produce the appropriate error report(s) and pop the error stack.
353 * If elevel is ERROR or worse, control does not return to the caller.
354 * See elog.h for the error level definitions.
357 errfinish(int dummy,...)
359 ErrorData *edata = &errordata[errordata_stack_depth];
360 int elevel = edata->elevel;
361 MemoryContext oldcontext;
362 ErrorContextCallback *econtext;
368 * Do processing in ErrorContext, which we hope has enough reserved space
369 * to report an error.
371 oldcontext = MemoryContextSwitchTo(ErrorContext);
374 * Call any context callback functions. Errors occurring in callback
375 * functions will be treated as recursive errors --- this ensures we will
376 * avoid infinite recursion (see errstart).
378 for (econtext = error_context_stack;
380 econtext = econtext->previous)
381 (*econtext->callback) (econtext->arg);
384 * If ERROR (not more nor less) we pass it off to the current handler.
385 * Printing it and popping the stack is the responsibility of the handler.
390 * We do some minimal cleanup before longjmp'ing so that handlers can
391 * execute in a reasonably sane state.
394 /* This is just in case the error came while waiting for input */
395 ImmediateInterruptOK = false;
398 * Reset InterruptHoldoffCount in case we ereport'd from inside an
399 * interrupt holdoff section. (We assume here that no handler will
400 * itself be inside a holdoff section. If necessary, such a handler
401 * could save and restore InterruptHoldoffCount for itself, but this
402 * should make life easier for most.)
404 InterruptHoldoffCount = 0;
406 CritSectionCount = 0; /* should be unnecessary, but... */
409 * Note that we leave CurrentMemoryContext set to ErrorContext. The
410 * handler should reset it to something else soon.
418 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
419 * progress, so that we can report the message before dying. (Without
420 * this, pq_putmessage will refuse to send the message at all, which is
421 * what we want for NOTICE messages, but not for fatal exits.) This hack
422 * is necessary because of poor design of old-style copy protocol. Note
423 * we must do this even if client is fool enough to have set
424 * client_min_messages above FATAL, so don't look at output_to_client.
426 if (elevel >= FATAL && whereToSendOutput == DestRemote)
429 /* Emit the message to the right places */
432 /* Now free up subsidiary data attached to stack entry, and release it */
434 pfree(edata->message);
436 pfree(edata->detail);
437 if (edata->detail_log)
438 pfree(edata->detail_log);
442 pfree(edata->context);
443 if (edata->internalquery)
444 pfree(edata->internalquery);
446 errordata_stack_depth--;
448 /* Exit error-handling context */
449 MemoryContextSwitchTo(oldcontext);
453 * Perform error recovery action as specified by elevel.
458 * For a FATAL error, we let proc_exit clean up and exit.
460 ImmediateInterruptOK = false;
463 * If we just reported a startup failure, the client will disconnect
464 * on receiving it, so don't send any more to the client.
466 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
467 whereToSendOutput = DestNone;
470 * fflush here is just to improve the odds that we get to see the
471 * error message, in case things are so hosed that proc_exit crashes.
472 * Any other code you might be tempted to add here should probably be
473 * in an on_proc_exit or on_shmem_exit callback instead.
479 * Do normal process-exit cleanup, then return exit code 1 to indicate
480 * FATAL termination. The postmaster may or may not consider this
481 * worthy of panic, depending on which subprocess returns it.
489 * Serious crash time. Postmaster will observe SIGABRT process exit
490 * status and kill the other backends too.
492 * XXX: what if we are *in* the postmaster? abort() won't kill our
495 ImmediateInterruptOK = false;
502 * We reach here if elevel <= WARNING. OK to return to caller.
504 * But check for cancel/die interrupt first --- this is so that the user
505 * can stop a query emitting tons of notice or warning messages, even if
506 * it's in a loop that otherwise fails to check for interrupts.
508 CHECK_FOR_INTERRUPTS();
513 * errcode --- add SQLSTATE error code to the current error
515 * The code is expected to be represented as per MAKE_SQLSTATE().
518 errcode(int sqlerrcode)
520 ErrorData *edata = &errordata[errordata_stack_depth];
522 /* we don't bother incrementing recursion_depth */
525 edata->sqlerrcode = sqlerrcode;
527 return 0; /* return value does not matter */
532 * errcode_for_file_access --- add SQLSTATE error code to the current error
534 * The SQLSTATE code is chosen based on the saved errno value. We assume
535 * that the failing operation was some type of disk file access.
537 * NOTE: the primary error message string should generally include %m
541 errcode_for_file_access(void)
543 ErrorData *edata = &errordata[errordata_stack_depth];
545 /* we don't bother incrementing recursion_depth */
548 switch (edata->saved_errno)
550 /* Permission-denied failures */
551 case EPERM: /* Not super-user */
552 case EACCES: /* Permission denied */
554 case EROFS: /* Read only file system */
556 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
560 case ENOENT: /* No such file or directory */
561 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
565 case EEXIST: /* File exists */
566 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
569 /* Wrong object type or state */
570 case ENOTDIR: /* Not a directory */
571 case EISDIR: /* Is a directory */
572 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
573 case ENOTEMPTY: /* Directory not empty */
575 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
578 /* Insufficient resources */
579 case ENOSPC: /* No space left on device */
580 edata->sqlerrcode = ERRCODE_DISK_FULL;
583 case ENFILE: /* File table overflow */
584 case EMFILE: /* Too many open files */
585 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
588 /* Hardware failure */
589 case EIO: /* I/O error */
590 edata->sqlerrcode = ERRCODE_IO_ERROR;
593 /* All else is classified as internal errors */
595 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
599 return 0; /* return value does not matter */
603 * errcode_for_socket_access --- add SQLSTATE error code to the current error
605 * The SQLSTATE code is chosen based on the saved errno value. We assume
606 * that the failing operation was some type of socket access.
608 * NOTE: the primary error message string should generally include %m
612 errcode_for_socket_access(void)
614 ErrorData *edata = &errordata[errordata_stack_depth];
616 /* we don't bother incrementing recursion_depth */
619 switch (edata->saved_errno)
621 /* Loss of connection */
626 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
629 /* All else is classified as internal errors */
631 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
635 return 0; /* return value does not matter */
640 * This macro handles expansion of a format string and associated parameters;
641 * it's common code for errmsg(), errdetail(), etc. Must be called inside
642 * a routine that is declared like "const char *fmt, ..." and has an edata
643 * pointer set up. The message is assigned to edata->targetfield, or
644 * appended to it if appendval is true. The message is subject to translation
645 * if translateit is true.
647 * Note: we pstrdup the buffer rather than just transferring its storage
648 * to the edata field because the buffer might be considerably larger than
651 #define EVALUATE_MESSAGE(targetfield, appendval, translateit) \
654 StringInfoData buf; \
655 /* Internationalize the error format string */ \
656 if (translateit && !in_error_recursion_trouble()) \
657 fmt = dgettext(edata->domain, fmt); \
658 /* Expand %m in format string */ \
659 fmtbuf = expand_fmt_string(fmt, edata); \
660 initStringInfo(&buf); \
661 if ((appendval) && edata->targetfield) \
662 appendStringInfo(&buf, "%s\n", edata->targetfield); \
663 /* Generate actual output --- have to use appendStringInfoVA */ \
668 va_start(args, fmt); \
669 success = appendStringInfoVA(&buf, fmtbuf, args); \
673 enlargeStringInfo(&buf, buf.maxlen); \
675 /* Done with expanded fmt */ \
677 /* Save the completed message into the stack item */ \
678 if (edata->targetfield) \
679 pfree(edata->targetfield); \
680 edata->targetfield = pstrdup(buf.data); \
685 * Same as above, except for pluralized error messages. The calling routine
686 * must be declared like "const char *fmt_singular, const char *fmt_plural,
687 * unsigned long n, ...". Translation is assumed always wanted.
689 #define EVALUATE_MESSAGE_PLURAL(targetfield, appendval) \
693 StringInfoData buf; \
694 /* Internationalize the error format string */ \
695 if (!in_error_recursion_trouble()) \
696 fmt = dngettext(edata->domain, fmt_singular, fmt_plural, n); \
698 fmt = (n == 1 ? fmt_singular : fmt_plural); \
699 /* Expand %m in format string */ \
700 fmtbuf = expand_fmt_string(fmt, edata); \
701 initStringInfo(&buf); \
702 if ((appendval) && edata->targetfield) \
703 appendStringInfo(&buf, "%s\n", edata->targetfield); \
704 /* Generate actual output --- have to use appendStringInfoVA */ \
710 success = appendStringInfoVA(&buf, fmtbuf, args); \
714 enlargeStringInfo(&buf, buf.maxlen); \
716 /* Done with expanded fmt */ \
718 /* Save the completed message into the stack item */ \
719 if (edata->targetfield) \
720 pfree(edata->targetfield); \
721 edata->targetfield = pstrdup(buf.data); \
727 * errmsg --- add a primary error message text to the current error
729 * In addition to the usual %-escapes recognized by printf, "%m" in
730 * fmt is replaced by the error message for the caller's value of errno.
732 * Note: no newline is needed at the end of the fmt string, since
733 * ereport will provide one for the output methods that need it.
736 errmsg(const char *fmt,...)
738 ErrorData *edata = &errordata[errordata_stack_depth];
739 MemoryContext oldcontext;
743 oldcontext = MemoryContextSwitchTo(ErrorContext);
745 EVALUATE_MESSAGE(message, false, true);
747 MemoryContextSwitchTo(oldcontext);
749 return 0; /* return value does not matter */
754 * errmsg_internal --- add a primary error message text to the current error
756 * This is exactly like errmsg() except that strings passed to errmsg_internal
757 * are not translated, and are customarily left out of the
758 * internationalization message dictionary. This should be used for "can't
759 * happen" cases that are probably not worth spending translation effort on.
760 * We also use this for certain cases where we *must* not try to translate
761 * the message because the translation would fail and result in infinite
765 errmsg_internal(const char *fmt,...)
767 ErrorData *edata = &errordata[errordata_stack_depth];
768 MemoryContext oldcontext;
772 oldcontext = MemoryContextSwitchTo(ErrorContext);
774 EVALUATE_MESSAGE(message, false, false);
776 MemoryContextSwitchTo(oldcontext);
778 return 0; /* return value does not matter */
783 * errmsg_plural --- add a primary error message text to the current error,
784 * with support for pluralization of the message text
787 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
788 unsigned long n, ...)
790 ErrorData *edata = &errordata[errordata_stack_depth];
791 MemoryContext oldcontext;
795 oldcontext = MemoryContextSwitchTo(ErrorContext);
797 EVALUATE_MESSAGE_PLURAL(message, false);
799 MemoryContextSwitchTo(oldcontext);
801 return 0; /* return value does not matter */
806 * errdetail --- add a detail error message text to the current error
809 errdetail(const char *fmt,...)
811 ErrorData *edata = &errordata[errordata_stack_depth];
812 MemoryContext oldcontext;
816 oldcontext = MemoryContextSwitchTo(ErrorContext);
818 EVALUATE_MESSAGE(detail, false, true);
820 MemoryContextSwitchTo(oldcontext);
822 return 0; /* return value does not matter */
827 * errdetail_log --- add a detail_log error message text to the current error
830 errdetail_log(const char *fmt,...)
832 ErrorData *edata = &errordata[errordata_stack_depth];
833 MemoryContext oldcontext;
837 oldcontext = MemoryContextSwitchTo(ErrorContext);
839 EVALUATE_MESSAGE(detail_log, false, true);
841 MemoryContextSwitchTo(oldcontext);
843 return 0; /* return value does not matter */
848 * errdetail_plural --- add a detail error message text to the current error,
849 * with support for pluralization of the message text
852 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
853 unsigned long n, ...)
855 ErrorData *edata = &errordata[errordata_stack_depth];
856 MemoryContext oldcontext;
860 oldcontext = MemoryContextSwitchTo(ErrorContext);
862 EVALUATE_MESSAGE_PLURAL(detail, false);
864 MemoryContextSwitchTo(oldcontext);
866 return 0; /* return value does not matter */
871 * errhint --- add a hint error message text to the current error
874 errhint(const char *fmt,...)
876 ErrorData *edata = &errordata[errordata_stack_depth];
877 MemoryContext oldcontext;
881 oldcontext = MemoryContextSwitchTo(ErrorContext);
883 EVALUATE_MESSAGE(hint, false, true);
885 MemoryContextSwitchTo(oldcontext);
887 return 0; /* return value does not matter */
892 * errcontext --- add a context error message text to the current error
894 * Unlike other cases, multiple calls are allowed to build up a stack of
895 * context information. We assume earlier calls represent more-closely-nested
899 errcontext(const char *fmt,...)
901 ErrorData *edata = &errordata[errordata_stack_depth];
902 MemoryContext oldcontext;
906 oldcontext = MemoryContextSwitchTo(ErrorContext);
908 EVALUATE_MESSAGE(context, true, true);
910 MemoryContextSwitchTo(oldcontext);
912 return 0; /* return value does not matter */
917 * errhidestmt --- optionally suppress STATEMENT: field of log entry
919 * This should be called if the message text already includes the statement.
922 errhidestmt(bool hide_stmt)
924 ErrorData *edata = &errordata[errordata_stack_depth];
926 /* we don't bother incrementing recursion_depth */
929 edata->hide_stmt = hide_stmt;
931 return 0; /* return value does not matter */
936 * errfunction --- add reporting function name to the current error
938 * This is used when backwards compatibility demands that the function
939 * name appear in messages sent to old-protocol clients. Note that the
940 * passed string is expected to be a non-freeable constant string.
943 errfunction(const char *funcname)
945 ErrorData *edata = &errordata[errordata_stack_depth];
947 /* we don't bother incrementing recursion_depth */
950 edata->funcname = funcname;
951 edata->show_funcname = true;
953 return 0; /* return value does not matter */
957 * errposition --- add cursor position to the current error
960 errposition(int cursorpos)
962 ErrorData *edata = &errordata[errordata_stack_depth];
964 /* we don't bother incrementing recursion_depth */
967 edata->cursorpos = cursorpos;
969 return 0; /* return value does not matter */
973 * internalerrposition --- add internal cursor position to the current error
976 internalerrposition(int cursorpos)
978 ErrorData *edata = &errordata[errordata_stack_depth];
980 /* we don't bother incrementing recursion_depth */
983 edata->internalpos = cursorpos;
985 return 0; /* return value does not matter */
989 * internalerrquery --- add internal query text to the current error
991 * Can also pass NULL to drop the internal query text entry. This case
992 * is intended for use in error callback subroutines that are editorializing
993 * on the layout of the error report.
996 internalerrquery(const char *query)
998 ErrorData *edata = &errordata[errordata_stack_depth];
1000 /* we don't bother incrementing recursion_depth */
1001 CHECK_STACK_DEPTH();
1003 if (edata->internalquery)
1005 pfree(edata->internalquery);
1006 edata->internalquery = NULL;
1010 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1012 return 0; /* return value does not matter */
1016 * geterrcode --- return the currently set SQLSTATE error code
1018 * This is only intended for use in error callback subroutines, since there
1019 * is no other place outside elog.c where the concept is meaningful.
1024 ErrorData *edata = &errordata[errordata_stack_depth];
1026 /* we don't bother incrementing recursion_depth */
1027 CHECK_STACK_DEPTH();
1029 return edata->sqlerrcode;
1033 * geterrposition --- return the currently set error position (0 if none)
1035 * This is only intended for use in error callback subroutines, since there
1036 * is no other place outside elog.c where the concept is meaningful.
1039 geterrposition(void)
1041 ErrorData *edata = &errordata[errordata_stack_depth];
1043 /* we don't bother incrementing recursion_depth */
1044 CHECK_STACK_DEPTH();
1046 return edata->cursorpos;
1050 * getinternalerrposition --- same for internal error position
1052 * This is only intended for use in error callback subroutines, since there
1053 * is no other place outside elog.c where the concept is meaningful.
1056 getinternalerrposition(void)
1058 ErrorData *edata = &errordata[errordata_stack_depth];
1060 /* we don't bother incrementing recursion_depth */
1061 CHECK_STACK_DEPTH();
1063 return edata->internalpos;
1068 * elog_start --- startup for old-style API
1070 * All that we do here is stash the hidden filename/lineno/funcname
1071 * arguments into a stack entry.
1073 * We need this to be separate from elog_finish because there's no other
1074 * portable way to deal with inserting extra arguments into the elog call.
1075 * (If macros with variable numbers of arguments were portable, it'd be
1076 * easy, but they aren't.)
1079 elog_start(const char *filename, int lineno, const char *funcname)
1083 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1086 * Wups, stack not big enough. We treat this as a PANIC condition
1087 * because it suggests an infinite loop of errors during error
1088 * recovery. Note that the message is intentionally not localized,
1089 * else failure to convert it to client encoding could cause further
1092 errordata_stack_depth = -1; /* make room on stack */
1093 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1096 edata = &errordata[errordata_stack_depth];
1097 edata->filename = filename;
1098 edata->lineno = lineno;
1099 edata->funcname = funcname;
1100 /* errno is saved now so that error parameter eval can't change it */
1101 edata->saved_errno = errno;
1105 * elog_finish --- finish up for old-style API
1108 elog_finish(int elevel, const char *fmt,...)
1110 ErrorData *edata = &errordata[errordata_stack_depth];
1111 MemoryContext oldcontext;
1113 CHECK_STACK_DEPTH();
1116 * Do errstart() to see if we actually want to report the message.
1118 errordata_stack_depth--;
1119 errno = edata->saved_errno;
1120 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1121 return; /* nothing to do */
1124 * Format error message just like errmsg_internal().
1127 oldcontext = MemoryContextSwitchTo(ErrorContext);
1129 EVALUATE_MESSAGE(message, false, false);
1131 MemoryContextSwitchTo(oldcontext);
1135 * And let errfinish() finish up.
1141 * Actual output of the top-of-stack error message
1143 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1144 * if the error is caught by somebody). For all other severity levels this
1145 * is called by errfinish.
1148 EmitErrorReport(void)
1150 ErrorData *edata = &errordata[errordata_stack_depth];
1151 MemoryContext oldcontext;
1154 CHECK_STACK_DEPTH();
1155 oldcontext = MemoryContextSwitchTo(ErrorContext);
1157 /* Send to server log, if enabled */
1158 if (edata->output_to_server)
1159 send_message_to_server_log(edata);
1161 /* Send to client, if enabled */
1162 if (edata->output_to_client)
1163 send_message_to_frontend(edata);
1165 MemoryContextSwitchTo(oldcontext);
1170 * CopyErrorData --- obtain a copy of the topmost error stack entry
1172 * This is only for use in error handler code. The data is copied into the
1173 * current memory context, so callers should always switch away from
1174 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1179 ErrorData *edata = &errordata[errordata_stack_depth];
1180 ErrorData *newedata;
1183 * we don't increment recursion_depth because out-of-memory here does not
1184 * indicate a problem within the error subsystem.
1186 CHECK_STACK_DEPTH();
1188 Assert(CurrentMemoryContext != ErrorContext);
1190 /* Copy the struct itself */
1191 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1192 memcpy(newedata, edata, sizeof(ErrorData));
1194 /* Make copies of separately-allocated fields */
1195 if (newedata->message)
1196 newedata->message = pstrdup(newedata->message);
1197 if (newedata->detail)
1198 newedata->detail = pstrdup(newedata->detail);
1199 if (newedata->detail_log)
1200 newedata->detail_log = pstrdup(newedata->detail_log);
1202 newedata->hint = pstrdup(newedata->hint);
1203 if (newedata->context)
1204 newedata->context = pstrdup(newedata->context);
1205 if (newedata->internalquery)
1206 newedata->internalquery = pstrdup(newedata->internalquery);
1212 * FreeErrorData --- free the structure returned by CopyErrorData.
1214 * Error handlers should use this in preference to assuming they know all
1215 * the separately-allocated fields.
1218 FreeErrorData(ErrorData *edata)
1221 pfree(edata->message);
1223 pfree(edata->detail);
1224 if (edata->detail_log)
1225 pfree(edata->detail_log);
1229 pfree(edata->context);
1230 if (edata->internalquery)
1231 pfree(edata->internalquery);
1236 * FlushErrorState --- flush the error state after error recovery
1238 * This should be called by an error handler after it's done processing
1239 * the error; or as soon as it's done CopyErrorData, if it intends to
1240 * do stuff that is likely to provoke another error. You are not "out" of
1241 * the error subsystem until you have done this.
1244 FlushErrorState(void)
1247 * Reset stack to empty. The only case where it would be more than one
1248 * deep is if we serviced an error that interrupted construction of
1249 * another message. We assume control escaped out of that message
1250 * construction and won't ever go back.
1252 errordata_stack_depth = -1;
1253 recursion_depth = 0;
1254 /* Delete all data in ErrorContext */
1255 MemoryContextResetAndDeleteChildren(ErrorContext);
1259 * ReThrowError --- re-throw a previously copied error
1261 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1262 * subsystem, then do some processing, and finally ReThrowError to re-throw
1263 * the original error. This is slower than just PG_RE_THROW() but should
1264 * be used if the "some processing" is likely to incur another error.
1267 ReThrowError(ErrorData *edata)
1269 ErrorData *newedata;
1271 Assert(edata->elevel == ERROR);
1273 /* Push the data back into the error context */
1275 MemoryContextSwitchTo(ErrorContext);
1277 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1280 * Wups, stack not big enough. We treat this as a PANIC condition
1281 * because it suggests an infinite loop of errors during error
1284 errordata_stack_depth = -1; /* make room on stack */
1285 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1288 newedata = &errordata[errordata_stack_depth];
1289 memcpy(newedata, edata, sizeof(ErrorData));
1291 /* Make copies of separately-allocated fields */
1292 if (newedata->message)
1293 newedata->message = pstrdup(newedata->message);
1294 if (newedata->detail)
1295 newedata->detail = pstrdup(newedata->detail);
1296 if (newedata->detail_log)
1297 newedata->detail_log = pstrdup(newedata->detail_log);
1299 newedata->hint = pstrdup(newedata->hint);
1300 if (newedata->context)
1301 newedata->context = pstrdup(newedata->context);
1302 if (newedata->internalquery)
1303 newedata->internalquery = pstrdup(newedata->internalquery);
1310 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1315 /* If possible, throw the error to the next outer setjmp handler */
1316 if (PG_exception_stack != NULL)
1317 siglongjmp(*PG_exception_stack, 1);
1321 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1322 * we have now exited only to discover that there is no outer setjmp
1323 * handler to pass the error to. Had the error been thrown outside
1324 * the block to begin with, we'd have promoted the error to FATAL, so
1325 * the correct behavior is to make it FATAL now; that is, emit it and
1326 * then call proc_exit.
1328 ErrorData *edata = &errordata[errordata_stack_depth];
1330 Assert(errordata_stack_depth >= 0);
1331 Assert(edata->elevel == ERROR);
1332 edata->elevel = FATAL;
1335 * At least in principle, the increase in severity could have changed
1336 * where-to-output decisions, so recalculate. This should stay in
1337 * sync with errstart(), which see for comments.
1339 if (IsPostmasterEnvironment)
1340 edata->output_to_server = is_log_level_output(FATAL,
1343 edata->output_to_server = (FATAL >= log_min_messages);
1344 if (whereToSendOutput == DestRemote)
1346 if (ClientAuthInProgress)
1347 edata->output_to_client = true;
1349 edata->output_to_client = (FATAL >= client_min_messages);
1353 * We can use errfinish() for the rest, but we don't want it to call
1354 * any error context routines a second time. Since we know we are
1355 * about to exit, it should be OK to just clear the context stack.
1357 error_context_stack = NULL;
1362 /* We mustn't return... */
1363 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1364 __FILE__, __LINE__);
1367 * Since ExceptionalCondition isn't declared noreturn because of
1368 * TrapMacro(), we need this to keep gcc from complaining.
1375 * Initialization of error output file
1383 if (OutputFileName[0])
1386 * A debug-output file name was given.
1388 * Make sure we can write the file, and find out if it's a tty.
1390 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1393 (errcode_for_file_access(),
1394 errmsg("could not open file \"%s\": %m", OutputFileName)));
1399 * Redirect our stderr to the debug output file.
1401 if (!freopen(OutputFileName, "a", stderr))
1403 (errcode_for_file_access(),
1404 errmsg("could not reopen file \"%s\" as stderr: %m",
1408 * If the file is a tty and we're running under the postmaster, try to
1409 * send stdout there as well (if it isn't a tty then stderr will block
1410 * out stdout, so we may as well let stdout go wherever it was going
1413 if (istty && IsUnderPostmaster)
1414 if (!freopen(OutputFileName, "a", stdout))
1416 (errcode_for_file_access(),
1417 errmsg("could not reopen file \"%s\" as stdout: %m",
1426 * Set or update the parameters for syslog logging
1429 set_syslog_parameters(const char *ident, int facility)
1432 * guc.c is likely to call us repeatedly with same parameters, so don't
1433 * thrash the syslog connection unnecessarily. Also, we do not re-open
1434 * the connection until needed, since this routine will get called whether
1435 * or not Log_destination actually mentions syslog.
1437 * Note that we make our own copy of the ident string rather than relying
1438 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1439 * accidentally free a string that syslog is still using.
1441 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1442 syslog_facility != facility)
1447 openlog_done = false;
1451 syslog_ident = strdup(ident);
1452 /* if the strdup fails, we will cope in write_syslog() */
1453 syslog_facility = facility;
1459 * Write a message line to syslog
1462 write_syslog(int level, const char *line)
1464 static unsigned long seq = 0;
1469 /* Open syslog connection if not done yet */
1472 openlog(syslog_ident ? syslog_ident : "postgres",
1473 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1475 openlog_done = true;
1479 * We add a sequence number to each log message to suppress "same"
1485 * Our problem here is that many syslog implementations don't handle long
1486 * messages in an acceptable manner. While this function doesn't help that
1487 * fact, it does work around by splitting up messages into smaller pieces.
1489 * We divide into multiple syslog() calls if message is too long or if the
1490 * message contains embedded newline(s).
1493 nlpos = strchr(line, '\n');
1494 if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1500 char buf[PG_SYSLOG_LIMIT + 1];
1504 /* if we start at a newline, move ahead one char */
1505 if (line[0] == '\n')
1509 /* we need to recompute the next newline's position, too */
1510 nlpos = strchr(line, '\n');
1514 /* copy one line, or as much as will fit, to buf */
1516 buflen = nlpos - line;
1519 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1520 memcpy(buf, line, buflen);
1523 /* trim to multibyte letter boundary */
1524 buflen = pg_mbcliplen(buf, buflen, buflen);
1529 /* already word boundary? */
1530 if (line[buflen] != '\0' &&
1531 !isspace((unsigned char) line[buflen]))
1533 /* try to divide at word boundary */
1535 while (i > 0 && !isspace((unsigned char) buf[i]))
1538 if (i > 0) /* else couldn't divide word boundary */
1547 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1554 /* message short enough */
1555 syslog(level, "[%lu] %s", seq, line);
1558 #endif /* HAVE_SYSLOG */
1562 * Write a message line to the windows event log
1565 write_eventlog(int level, const char *line)
1567 int eventlevel = EVENTLOG_ERROR_TYPE;
1568 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1570 if (evtHandle == INVALID_HANDLE_VALUE)
1572 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1573 if (evtHandle == NULL)
1575 evtHandle = INVALID_HANDLE_VALUE;
1591 eventlevel = EVENTLOG_INFORMATION_TYPE;
1594 eventlevel = EVENTLOG_WARNING_TYPE;
1600 eventlevel = EVENTLOG_ERROR_TYPE;
1605 ReportEvent(evtHandle,
1608 0, /* All events are Id 0 */
1618 * setup formatted_log_time, for consistent times between CSV and regular logs
1621 setup_formatted_log_time(void)
1624 pg_time_t stamp_time;
1628 gettimeofday(&tv, NULL);
1629 stamp_time = (pg_time_t) tv.tv_sec;
1632 * Normally we print log timestamps in log_timezone, but during startup we
1633 * could get here before that's set. If so, fall back to gmt_timezone
1634 * (which guc.c ensures is set up before Log_line_prefix can become
1637 tz = log_timezone ? log_timezone : gmt_timezone;
1639 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1640 /* leave room for milliseconds... */
1641 "%Y-%m-%d %H:%M:%S %Z",
1642 pg_localtime(&stamp_time, tz));
1644 /* 'paste' milliseconds into place... */
1645 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1646 strncpy(formatted_log_time + 19, msbuf, 4);
1650 * setup formatted_start_time
1653 setup_formatted_start_time(void)
1655 pg_time_t stamp_time = (pg_time_t) MyStartTime;
1659 * Normally we print log timestamps in log_timezone, but during startup we
1660 * could get here before that's set. If so, fall back to gmt_timezone
1661 * (which guc.c ensures is set up before Log_line_prefix can become
1664 tz = log_timezone ? log_timezone : gmt_timezone;
1666 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1667 "%Y-%m-%d %H:%M:%S %Z",
1668 pg_localtime(&stamp_time, tz));
1672 * Format tag info for log lines; append to the provided buffer.
1675 log_line_prefix(StringInfo buf)
1677 /* static counter for line numbers */
1678 static long log_line_number = 0;
1680 /* has counter been reset in current process? */
1681 static int log_my_pid = 0;
1687 * This is one of the few places where we'd rather not inherit a static
1688 * variable's value from the postmaster. But since we will, reset it when
1689 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1690 * reset the formatted start timestamp too.
1692 if (log_my_pid != MyProcPid)
1694 log_line_number = 0;
1695 log_my_pid = MyProcPid;
1696 formatted_start_time[0] = '\0';
1700 if (Log_line_prefix == NULL)
1701 return; /* in case guc hasn't run yet */
1703 format_len = strlen(Log_line_prefix);
1705 for (i = 0; i < format_len; i++)
1707 if (Log_line_prefix[i] != '%')
1709 /* literal char, just copy */
1710 appendStringInfoChar(buf, Log_line_prefix[i]);
1713 /* go to char after '%' */
1715 if (i >= format_len)
1716 break; /* format error - ignore it */
1718 /* process the option */
1719 switch (Log_line_prefix[i])
1724 const char *username = MyProcPort->user_name;
1726 if (username == NULL || *username == '\0')
1727 username = _("[unknown]");
1728 appendStringInfo(buf, "%s", username);
1734 const char *dbname = MyProcPort->database_name;
1736 if (dbname == NULL || *dbname == '\0')
1737 dbname = _("[unknown]");
1738 appendStringInfo(buf, "%s", dbname);
1742 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1745 appendStringInfo(buf, "%d", MyProcPid);
1748 appendStringInfo(buf, "%ld", log_line_number);
1751 setup_formatted_log_time();
1752 appendStringInfoString(buf, formatted_log_time);
1756 pg_time_t stamp_time = (pg_time_t) time(NULL);
1760 tz = log_timezone ? log_timezone : gmt_timezone;
1762 pg_strftime(strfbuf, sizeof(strfbuf),
1763 "%Y-%m-%d %H:%M:%S %Z",
1764 pg_localtime(&stamp_time, tz));
1765 appendStringInfoString(buf, strfbuf);
1769 if (formatted_start_time[0] == '\0')
1770 setup_formatted_start_time();
1771 appendStringInfoString(buf, formatted_start_time);
1779 psdisp = get_ps_display(&displen);
1780 appendStringInfo(buf, "%.*s", displen, psdisp);
1784 if (MyProcPort && MyProcPort->remote_host)
1786 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1787 if (MyProcPort->remote_port &&
1788 MyProcPort->remote_port[0] != '\0')
1789 appendStringInfo(buf, "(%s)",
1790 MyProcPort->remote_port);
1794 if (MyProcPort && MyProcPort->remote_host)
1795 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1798 /* in postmaster and friends, stop if %q is seen */
1799 /* in a backend, just ignore */
1800 if (MyProcPort == NULL)
1804 /* keep VXID format in sync with lockfuncs.c */
1805 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1806 appendStringInfo(buf, "%d/%u",
1807 MyProc->backendId, MyProc->lxid);
1810 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1813 appendStringInfoChar(buf, '%');
1816 /* format error - ignore it */
1823 * append a CSV'd version of a string to a StringInfo
1824 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1825 * If it's NULL, append nothing.
1828 appendCSVLiteral(StringInfo buf, const char *data)
1830 const char *p = data;
1833 /* avoid confusing an empty string with NULL */
1837 appendStringInfoCharMacro(buf, '"');
1838 while ((c = *p++) != '\0')
1841 appendStringInfoCharMacro(buf, '"');
1842 appendStringInfoCharMacro(buf, c);
1844 appendStringInfoCharMacro(buf, '"');
1848 * Constructs the error message, depending on the Errordata it gets, in a CSV
1849 * format which is described in doc/src/sgml/config.sgml.
1852 write_csvlog(ErrorData *edata)
1855 bool print_stmt = false;
1857 /* static counter for line numbers */
1858 static long log_line_number = 0;
1860 /* has counter been reset in current process? */
1861 static int log_my_pid = 0;
1864 * This is one of the few places where we'd rather not inherit a static
1865 * variable's value from the postmaster. But since we will, reset it when
1866 * MyProcPid changes.
1868 if (log_my_pid != MyProcPid)
1870 log_line_number = 0;
1871 log_my_pid = MyProcPid;
1872 formatted_start_time[0] = '\0';
1876 initStringInfo(&buf);
1879 * timestamp with milliseconds
1881 * Check if the timestamp is already calculated for the syslog message,
1882 * and use it if so. Otherwise, get the current timestamp. This is done
1883 * to put same timestamp in both syslog and csvlog messages.
1885 if (formatted_log_time[0] == '\0')
1886 setup_formatted_log_time();
1888 appendStringInfoString(&buf, formatted_log_time);
1889 appendStringInfoChar(&buf, ',');
1893 appendCSVLiteral(&buf, MyProcPort->user_name);
1894 appendStringInfoChar(&buf, ',');
1898 appendCSVLiteral(&buf, MyProcPort->database_name);
1899 appendStringInfoChar(&buf, ',');
1903 appendStringInfo(&buf, "%d", MyProcPid);
1904 appendStringInfoChar(&buf, ',');
1906 /* Remote host and port */
1907 if (MyProcPort && MyProcPort->remote_host)
1909 appendStringInfoChar(&buf, '"');
1910 appendStringInfo(&buf, "%s", MyProcPort->remote_host);
1911 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
1912 appendStringInfo(&buf, ":%s", MyProcPort->remote_port);
1913 appendStringInfoChar(&buf, '"');
1915 appendStringInfoChar(&buf, ',');
1918 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
1919 appendStringInfoChar(&buf, ',');
1922 appendStringInfo(&buf, "%ld", log_line_number);
1923 appendStringInfoChar(&buf, ',');
1928 StringInfoData msgbuf;
1932 initStringInfo(&msgbuf);
1934 psdisp = get_ps_display(&displen);
1935 appendStringInfo(&msgbuf, "%.*s", displen, psdisp);
1936 appendCSVLiteral(&buf, msgbuf.data);
1940 appendStringInfoChar(&buf, ',');
1942 /* session start timestamp */
1943 if (formatted_start_time[0] == '\0')
1944 setup_formatted_start_time();
1945 appendStringInfoString(&buf, formatted_start_time);
1946 appendStringInfoChar(&buf, ',');
1948 /* Virtual transaction id */
1949 /* keep VXID format in sync with lockfuncs.c */
1950 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1951 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
1952 appendStringInfoChar(&buf, ',');
1954 /* Transaction id */
1955 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
1956 appendStringInfoChar(&buf, ',');
1958 /* Error severity */
1959 appendStringInfo(&buf, "%s", error_severity(edata->elevel));
1960 appendStringInfoChar(&buf, ',');
1962 /* SQL state code */
1963 appendStringInfo(&buf, "%s", unpack_sql_state(edata->sqlerrcode));
1964 appendStringInfoChar(&buf, ',');
1967 appendCSVLiteral(&buf, edata->message);
1968 appendStringInfoCharMacro(&buf, ',');
1970 /* errdetail or errdetail_log */
1971 if (edata->detail_log)
1972 appendCSVLiteral(&buf, edata->detail_log);
1974 appendCSVLiteral(&buf, edata->detail);
1975 appendStringInfoCharMacro(&buf, ',');
1978 appendCSVLiteral(&buf, edata->hint);
1979 appendStringInfoCharMacro(&buf, ',');
1981 /* internal query */
1982 appendCSVLiteral(&buf, edata->internalquery);
1983 appendStringInfoCharMacro(&buf, ',');
1985 /* if printed internal query, print internal pos too */
1986 if (edata->internalpos > 0 && edata->internalquery != NULL)
1987 appendStringInfo(&buf, "%d", edata->internalpos);
1988 appendStringInfoCharMacro(&buf, ',');
1991 appendCSVLiteral(&buf, edata->context);
1992 appendStringInfoCharMacro(&buf, ',');
1994 /* user query --- only reported if not disabled by the caller */
1995 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1996 debug_query_string != NULL &&
2000 appendCSVLiteral(&buf, debug_query_string);
2001 appendStringInfoCharMacro(&buf, ',');
2002 if (print_stmt && edata->cursorpos > 0)
2003 appendStringInfo(&buf, "%d", edata->cursorpos);
2004 appendStringInfoCharMacro(&buf, ',');
2006 /* file error location */
2007 if (Log_error_verbosity >= PGERROR_VERBOSE)
2009 StringInfoData msgbuf;
2011 initStringInfo(&msgbuf);
2013 if (edata->funcname && edata->filename)
2014 appendStringInfo(&msgbuf, "%s, %s:%d",
2015 edata->funcname, edata->filename,
2017 else if (edata->filename)
2018 appendStringInfo(&msgbuf, "%s:%d",
2019 edata->filename, edata->lineno);
2020 appendCSVLiteral(&buf, msgbuf.data);
2024 appendStringInfoChar(&buf, '\n');
2026 /* If in the syslogger process, try to write messages direct to file */
2028 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2030 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2036 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2040 unpack_sql_state(int sql_state)
2042 static char buf[12];
2045 for (i = 0; i < 5; i++)
2047 buf[i] = PGUNSIXBIT(sql_state);
2057 * Write error report to server's log
2060 send_message_to_server_log(ErrorData *edata)
2064 initStringInfo(&buf);
2066 formatted_log_time[0] = '\0';
2068 log_line_prefix(&buf);
2069 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2071 if (Log_error_verbosity >= PGERROR_VERBOSE)
2072 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2075 append_with_tabs(&buf, edata->message);
2077 append_with_tabs(&buf, _("missing error text"));
2079 if (edata->cursorpos > 0)
2080 appendStringInfo(&buf, _(" at character %d"),
2082 else if (edata->internalpos > 0)
2083 appendStringInfo(&buf, _(" at character %d"),
2084 edata->internalpos);
2086 appendStringInfoChar(&buf, '\n');
2088 if (Log_error_verbosity >= PGERROR_DEFAULT)
2090 if (edata->detail_log)
2092 log_line_prefix(&buf);
2093 appendStringInfoString(&buf, _("DETAIL: "));
2094 append_with_tabs(&buf, edata->detail_log);
2095 appendStringInfoChar(&buf, '\n');
2097 else if (edata->detail)
2099 log_line_prefix(&buf);
2100 appendStringInfoString(&buf, _("DETAIL: "));
2101 append_with_tabs(&buf, edata->detail);
2102 appendStringInfoChar(&buf, '\n');
2106 log_line_prefix(&buf);
2107 appendStringInfoString(&buf, _("HINT: "));
2108 append_with_tabs(&buf, edata->hint);
2109 appendStringInfoChar(&buf, '\n');
2111 if (edata->internalquery)
2113 log_line_prefix(&buf);
2114 appendStringInfoString(&buf, _("QUERY: "));
2115 append_with_tabs(&buf, edata->internalquery);
2116 appendStringInfoChar(&buf, '\n');
2120 log_line_prefix(&buf);
2121 appendStringInfoString(&buf, _("CONTEXT: "));
2122 append_with_tabs(&buf, edata->context);
2123 appendStringInfoChar(&buf, '\n');
2125 if (Log_error_verbosity >= PGERROR_VERBOSE)
2127 /* assume no newlines in funcname or filename... */
2128 if (edata->funcname && edata->filename)
2130 log_line_prefix(&buf);
2131 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2132 edata->funcname, edata->filename,
2135 else if (edata->filename)
2137 log_line_prefix(&buf);
2138 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2139 edata->filename, edata->lineno);
2145 * If the user wants the query that generated this error logged, do it.
2147 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2148 debug_query_string != NULL &&
2151 log_line_prefix(&buf);
2152 appendStringInfoString(&buf, _("STATEMENT: "));
2153 append_with_tabs(&buf, debug_query_string);
2154 appendStringInfoChar(&buf, '\n');
2158 /* Write to syslog, if enabled */
2159 if (Log_destination & LOG_DESTINATION_SYSLOG)
2163 switch (edata->elevel)
2170 syslog_level = LOG_DEBUG;
2175 syslog_level = LOG_INFO;
2179 syslog_level = LOG_NOTICE;
2182 syslog_level = LOG_WARNING;
2185 syslog_level = LOG_ERR;
2189 syslog_level = LOG_CRIT;
2193 write_syslog(syslog_level, buf.data);
2195 #endif /* HAVE_SYSLOG */
2198 /* Write to eventlog, if enabled */
2199 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2201 write_eventlog(edata->elevel, buf.data);
2205 /* Write to stderr, if enabled */
2206 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2209 * Use the chunking protocol if we know the syslogger should be
2210 * catching stderr output, and we are not ourselves the syslogger.
2211 * Otherwise, just do a vanilla write to stderr.
2213 if (redirection_done && !am_syslogger)
2214 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2218 * In a win32 service environment, there is no usable stderr. Capture
2219 * anything going there and write it to the eventlog instead.
2221 * If stderr redirection is active, it was OK to write to stderr above
2222 * because that's really a pipe to the syslogger process.
2224 else if (pgwin32_is_service())
2225 write_eventlog(edata->elevel, buf.data);
2228 write(fileno(stderr), buf.data, buf.len);
2231 /* If in the syslogger process, try to write messages direct to file */
2233 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2235 /* Write to CSV log if enabled */
2236 if (Log_destination & LOG_DESTINATION_CSVLOG)
2238 if (redirection_done || am_syslogger)
2241 * send CSV data if it's safe to do so (syslogger doesn't need the
2242 * pipe). First get back the space in the message buffer.
2245 write_csvlog(edata);
2249 const char *msg = _("Not safe to send CSV data\n");
2251 write(fileno(stderr), msg, strlen(msg));
2252 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2253 whereToSendOutput != DestDebug)
2255 /* write message to stderr unless we just sent it above */
2256 write(fileno(stderr), buf.data, buf.len);
2268 * Send data to the syslogger using the chunked protocol
2271 write_pipe_chunks(char *data, int len, int dest)
2275 int fd = fileno(stderr);
2279 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2280 p.proto.pid = MyProcPid;
2282 /* write all but the last chunk */
2283 while (len > PIPE_MAX_PAYLOAD)
2285 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2286 p.proto.len = PIPE_MAX_PAYLOAD;
2287 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2288 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2289 data += PIPE_MAX_PAYLOAD;
2290 len -= PIPE_MAX_PAYLOAD;
2293 /* write the last chunk */
2294 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2296 memcpy(p.proto.data, data, len);
2297 write(fd, &p, PIPE_HEADER_SIZE + len);
2302 * Append a text string to the error report being built for the client.
2304 * This is ordinarily identical to pq_sendstring(), but if we are in
2305 * error recursion trouble we skip encoding conversion, because of the
2306 * possibility that the problem is a failure in the encoding conversion
2307 * subsystem itself. Code elsewhere should ensure that the passed-in
2308 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2309 * in such cases. (In particular, we disable localization of error messages
2310 * to help ensure that's true.)
2313 err_sendstring(StringInfo buf, const char *str)
2315 if (in_error_recursion_trouble())
2316 pq_send_ascii_string(buf, str);
2318 pq_sendstring(buf, str);
2322 * Write error report to client
2325 send_message_to_frontend(ErrorData *edata)
2327 StringInfoData msgbuf;
2329 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2330 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2332 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2334 /* New style with separate fields */
2339 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2340 err_sendstring(&msgbuf, error_severity(edata->elevel));
2342 /* unpack MAKE_SQLSTATE code */
2343 ssval = edata->sqlerrcode;
2344 for (i = 0; i < 5; i++)
2346 tbuf[i] = PGUNSIXBIT(ssval);
2351 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2352 err_sendstring(&msgbuf, tbuf);
2354 /* M field is required per protocol, so always send something */
2355 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2357 err_sendstring(&msgbuf, edata->message);
2359 err_sendstring(&msgbuf, _("missing error text"));
2363 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2364 err_sendstring(&msgbuf, edata->detail);
2367 /* detail_log is intentionally not used here */
2371 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2372 err_sendstring(&msgbuf, edata->hint);
2377 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2378 err_sendstring(&msgbuf, edata->context);
2381 if (edata->cursorpos > 0)
2383 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2384 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2385 err_sendstring(&msgbuf, tbuf);
2388 if (edata->internalpos > 0)
2390 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2391 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2392 err_sendstring(&msgbuf, tbuf);
2395 if (edata->internalquery)
2397 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2398 err_sendstring(&msgbuf, edata->internalquery);
2401 if (edata->filename)
2403 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2404 err_sendstring(&msgbuf, edata->filename);
2407 if (edata->lineno > 0)
2409 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2410 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2411 err_sendstring(&msgbuf, tbuf);
2414 if (edata->funcname)
2416 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2417 err_sendstring(&msgbuf, edata->funcname);
2420 pq_sendbyte(&msgbuf, '\0'); /* terminator */
2424 /* Old style --- gin up a backwards-compatible message */
2427 initStringInfo(&buf);
2429 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2431 if (edata->show_funcname && edata->funcname)
2432 appendStringInfo(&buf, "%s: ", edata->funcname);
2435 appendStringInfoString(&buf, edata->message);
2437 appendStringInfoString(&buf, _("missing error text"));
2439 if (edata->cursorpos > 0)
2440 appendStringInfo(&buf, _(" at character %d"),
2442 else if (edata->internalpos > 0)
2443 appendStringInfo(&buf, _(" at character %d"),
2444 edata->internalpos);
2446 appendStringInfoChar(&buf, '\n');
2448 err_sendstring(&msgbuf, buf.data);
2453 pq_endmessage(&msgbuf);
2456 * This flush is normally not necessary, since postgres.c will flush out
2457 * waiting data when control returns to the main loop. But it seems best
2458 * to leave it here, so that the client has some clue what happened if the
2459 * backend dies before getting back to the main loop ... error/notice
2460 * messages should not be a performance-critical path anyway, so an extra
2461 * flush won't hurt much ...
2468 * Support routines for formatting error messages.
2473 * expand_fmt_string --- process special format codes in a format string
2475 * We must replace %m with the appropriate strerror string, since vsnprintf
2476 * won't know what to do with it.
2478 * The result is a palloc'd string.
2481 expand_fmt_string(const char *fmt, ErrorData *edata)
2486 initStringInfo(&buf);
2488 for (cp = fmt; *cp; cp++)
2490 if (cp[0] == '%' && cp[1] != '\0')
2496 * Replace %m by system error string. If there are any %'s in
2497 * the string, we'd better double them so that vsnprintf won't
2502 cp2 = useful_strerror(edata->saved_errno);
2506 appendStringInfoCharMacro(&buf, '%');
2507 appendStringInfoCharMacro(&buf, *cp2);
2512 /* copy % and next char --- this avoids trouble with %%m */
2513 appendStringInfoCharMacro(&buf, '%');
2514 appendStringInfoCharMacro(&buf, *cp);
2518 appendStringInfoCharMacro(&buf, *cp);
2526 * A slightly cleaned-up version of strerror()
2529 useful_strerror(int errnum)
2531 /* this buffer is only used if errno has a bogus value */
2532 static char errorstr_buf[48];
2536 /* Winsock error code range, per WinError.h */
2537 if (errnum >= 10000 && errnum <= 11999)
2538 return pgwin32_socket_strerror(errnum);
2540 str = strerror(errnum);
2543 * Some strerror()s return an empty string for out-of-range errno. This is
2544 * ANSI C spec compliant, but not exactly useful.
2546 if (str == NULL || *str == '\0')
2548 snprintf(errorstr_buf, sizeof(errorstr_buf),
2550 translator: This string will be truncated at 47
2551 characters expanded. */
2552 _("operating system error %d"), errnum);
2561 * error_severity --- get localized string representing elevel
2564 error_severity(int elevel)
2575 prefix = _("DEBUG");
2585 prefix = _("NOTICE");
2588 prefix = _("WARNING");
2591 prefix = _("ERROR");
2594 prefix = _("FATAL");
2597 prefix = _("PANIC");
2611 * Append the string to the StringInfo buffer, inserting a tab after any
2615 append_with_tabs(StringInfo buf, const char *str)
2619 while ((ch = *str++) != '\0')
2621 appendStringInfoCharMacro(buf, ch);
2623 appendStringInfoCharMacro(buf, '\t');
2629 * Write errors to stderr (or by equal means when stderr is
2630 * not available). Used before ereport/elog can be used
2631 * safely (memory context, GUC load etc)
2634 write_stderr(const char *fmt,...)
2642 /* On Unix, we just fprintf to stderr */
2643 vfprintf(stderr, fmt, ap);
2648 * On Win32, we print to stderr if running on a console, or write to
2649 * eventlog if running as a service
2651 if (pgwin32_is_service()) /* Running as a service */
2653 char errbuf[2048]; /* Arbitrary size? */
2655 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2657 write_eventlog(ERROR, errbuf);
2661 /* Not running as service, write to stderr */
2662 vfprintf(stderr, fmt, ap);
2671 * is_log_level_output -- is elevel logically >= log_min_level?
2673 * We use this for tests that should consider LOG to sort out-of-order,
2674 * between ERROR and FATAL. Generally this is the right thing for testing
2675 * whether a message should go to the postmaster log, whereas a simple >=
2676 * test is correct for testing whether the message should go to the client.
2679 is_log_level_output(int elevel, int log_min_level)
2681 if (elevel == LOG || elevel == COMMERROR)
2683 if (log_min_level == LOG || log_min_level <= ERROR)
2686 else if (log_min_level == LOG)
2689 if (elevel >= FATAL)
2692 /* Neither is LOG */
2693 else if (elevel >= log_min_level)