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-2014, PostgreSQL Global Development Group
47 * Portions Copyright (c) 1994, Regents of the University of California
51 * src/backend/utils/error/elog.c
53 *-------------------------------------------------------------------------
66 #include "access/transam.h"
67 #include "access/xact.h"
68 #include "libpq/libpq.h"
69 #include "libpq/pqformat.h"
70 #include "mb/pg_wchar.h"
71 #include "miscadmin.h"
72 #include "postmaster/postmaster.h"
73 #include "postmaster/syslogger.h"
74 #include "storage/ipc.h"
75 #include "storage/proc.h"
76 #include "tcop/tcopprot.h"
77 #include "utils/guc.h"
78 #include "utils/memutils.h"
79 #include "utils/ps_status.h"
83 #define _(x) err_gettext(x)
86 err_gettext(const char *str)
87 /* This extension allows gcc to check the format string for consistency with
88 the supplied arguments. */
89 __attribute__((format_arg(1)));
90 static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
92 /* Global variables */
93 ErrorContextCallback *error_context_stack = NULL;
95 sigjmp_buf *PG_exception_stack = NULL;
97 extern bool redirection_done;
100 * Hook for intercepting messages before they are sent to the server log.
101 * Note that the hook will not get called for messages that are suppressed
102 * by log_min_messages. Also note that logging hooks implemented in preload
103 * libraries will miss any log messages that are generated before the
106 emit_log_hook_type emit_log_hook = NULL;
109 int Log_error_verbosity = PGERROR_VERBOSE;
110 char *Log_line_prefix = NULL; /* format for extra log line info */
111 int Log_destination = LOG_DESTINATION_STDERR;
112 char *Log_destination_string = NULL;
117 * Max string length to send to syslog(). Note that this doesn't count the
118 * sequence-number prefix we add, and of course it doesn't count the prefix
119 * added by syslog itself. Solaris and sysklogd truncate the final message
120 * at 1024 bytes, so this value leaves 124 bytes for those prefixes. (Most
121 * other syslog implementations seem to have limits of 2KB or so.)
123 #ifndef PG_SYSLOG_LIMIT
124 #define PG_SYSLOG_LIMIT 900
127 static bool openlog_done = false;
128 static char *syslog_ident = NULL;
129 static int syslog_facility = LOG_LOCAL0;
131 static void write_syslog(int level, const char *line);
134 static void write_console(const char *line, int len);
137 extern char *event_source;
138 static void write_eventlog(int level, const char *line, int len);
141 /* We provide a small stack of ErrorData records for re-entrant cases */
142 #define ERRORDATA_STACK_SIZE 5
144 static ErrorData errordata[ERRORDATA_STACK_SIZE];
146 static int errordata_stack_depth = -1; /* index of topmost active frame */
148 static int recursion_depth = 0; /* to detect actual recursion */
150 /* buffers for formatted timestamps that might be used by both
151 * log_line_prefix and csv logs.
154 #define FORMATTED_TS_LEN 128
155 static char formatted_start_time[FORMATTED_TS_LEN];
156 static char formatted_log_time[FORMATTED_TS_LEN];
159 /* Macro for checking errordata_stack_depth is reasonable */
160 #define CHECK_STACK_DEPTH() \
162 if (errordata_stack_depth < 0) \
164 errordata_stack_depth = -1; \
165 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
170 static const char *process_log_prefix_padding(const char *p, int *padding);
171 static void log_line_prefix(StringInfo buf, ErrorData *edata);
172 static void send_message_to_server_log(ErrorData *edata);
173 static void send_message_to_frontend(ErrorData *edata);
174 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
175 static const char *useful_strerror(int errnum);
176 static const char *get_errno_symbol(int errnum);
177 static const char *error_severity(int elevel);
178 static void append_with_tabs(StringInfo buf, const char *str);
179 static bool is_log_level_output(int elevel, int log_min_level);
180 static void write_pipe_chunks(char *data, int len, int dest);
181 static void write_csvlog(ErrorData *edata);
182 static void setup_formatted_log_time(void);
183 static void setup_formatted_start_time(void);
187 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
189 * This function exists to provide common control of various fallback steps
190 * that we take if we think we are facing infinite error recursion. See the
191 * callers for details.
194 in_error_recursion_trouble(void)
196 /* Pull the plug if recurse more than once */
197 return (recursion_depth > 2);
201 * One of those fallback steps is to stop trying to localize the error
202 * message, since there's a significant probability that that's exactly
203 * what's causing the recursion.
205 static inline const char *
206 err_gettext(const char *str)
209 if (in_error_recursion_trouble())
220 * errstart --- begin an error-reporting cycle
222 * Create a stack entry and store the given parameters in it. Subsequently,
223 * errmsg() and perhaps other routines will be called to further populate
224 * the stack entry. Finally, errfinish() will be called to actually process
227 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
228 * report (if it's a warning or lower and not to be reported anywhere).
231 errstart(int elevel, const char *filename, int lineno,
232 const char *funcname, const char *domain)
235 bool output_to_server;
236 bool output_to_client = false;
240 * Check some cases in which we want to promote an error into a more
241 * severe error. None of this logic applies for non-error messages.
246 * If we are inside a critical section, all errors become PANIC
247 * errors. See miscadmin.h.
249 if (CritSectionCount > 0)
253 * Check reasons for treating ERROR as FATAL:
255 * 1. we have no handler to pass the error to (implies we are in the
256 * postmaster or in backend startup).
258 * 2. ExitOnAnyError mode switch is set (initdb uses this).
260 * 3. the error occurred after proc_exit has begun to run. (It's
261 * proc_exit's responsibility to see that this doesn't turn into
262 * infinite recursion!)
266 if (PG_exception_stack == NULL ||
268 proc_exit_inprogress)
273 * If the error level is ERROR or more, errfinish is not going to
274 * return to caller; therefore, if there is any stacked error already
275 * in progress it will be lost. This is more or less okay, except we
276 * do not want to have a FATAL or PANIC error downgraded because the
277 * reporting process was interrupted by a lower-grade error. So check
278 * the stack and make sure we panic if panic is warranted.
280 for (i = 0; i <= errordata_stack_depth; i++)
281 elevel = Max(elevel, errordata[i].elevel);
285 * Now decide whether we need to process this report at all; if it's
286 * warning or less and not enabled for logging, just return FALSE without
287 * starting up any error logging machinery.
290 /* Determine whether message is enabled for server log output */
291 output_to_server = is_log_level_output(elevel, log_min_messages);
293 /* Determine whether message is enabled for client output */
294 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
297 * client_min_messages is honored only after we complete the
298 * authentication handshake. This is required both for security
299 * reasons and because many clients can't handle NOTICE messages
300 * during authentication.
302 if (ClientAuthInProgress)
303 output_to_client = (elevel >= ERROR);
305 output_to_client = (elevel >= client_min_messages ||
309 /* Skip processing effort if non-error message will not be output */
310 if (elevel < ERROR && !output_to_server && !output_to_client)
314 * We need to do some actual work. Make sure that memory context
315 * initialization has finished, else we can't do anything useful.
317 if (ErrorContext == NULL)
319 /* Ooops, hard crash time; very little we can do safely here */
320 write_stderr("error occurred at %s:%d before error message processing is available\n",
321 filename ? filename : "(unknown file)", lineno);
326 * Okay, crank up a stack entry to store the info in.
329 if (recursion_depth++ > 0 && elevel >= ERROR)
332 * Ooops, error during error processing. Clear ErrorContext as
333 * discussed at top of file. We will not return to the original
334 * error's reporter or handler, so we don't need it.
336 MemoryContextReset(ErrorContext);
339 * Infinite error recursion might be due to something broken in a
340 * context traceback routine. Abandon them too. We also abandon
341 * attempting to print the error statement (which, if long, could
342 * itself be the source of the recursive failure).
344 if (in_error_recursion_trouble())
346 error_context_stack = NULL;
347 debug_query_string = NULL;
350 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
353 * Wups, stack not big enough. We treat this as a PANIC condition
354 * because it suggests an infinite loop of errors during error
357 errordata_stack_depth = -1; /* make room on stack */
358 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
361 /* Initialize data for this error frame */
362 edata = &errordata[errordata_stack_depth];
363 MemSet(edata, 0, sizeof(ErrorData));
364 edata->elevel = elevel;
365 edata->output_to_server = output_to_server;
366 edata->output_to_client = output_to_client;
371 /* keep only base name, useful especially for vpath builds */
372 slash = strrchr(filename, '/');
374 filename = slash + 1;
376 edata->filename = filename;
377 edata->lineno = lineno;
378 edata->funcname = funcname;
379 /* the default text domain is the backend's */
380 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
381 /* Select default errcode based on elevel */
383 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
384 else if (elevel == WARNING)
385 edata->sqlerrcode = ERRCODE_WARNING;
387 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
388 /* errno is saved here so that error parameter eval can't change it */
389 edata->saved_errno = errno;
392 * Any allocations for this error state level should go into ErrorContext
394 edata->assoc_context = ErrorContext;
401 * errfinish --- end an error-reporting cycle
403 * Produce the appropriate error report(s) and pop the error stack.
405 * If elevel is ERROR or worse, control does not return to the caller.
406 * See elog.h for the error level definitions.
409 errfinish(int dummy,...)
411 ErrorData *edata = &errordata[errordata_stack_depth];
413 bool save_ImmediateInterruptOK;
414 MemoryContext oldcontext;
415 ErrorContextCallback *econtext;
419 elevel = edata->elevel;
422 * Ensure we can't get interrupted while performing error reporting. This
423 * is needed to prevent recursive entry to functions like syslog(), which
424 * may not be re-entrant.
426 * Note: other places that save-and-clear ImmediateInterruptOK also do
427 * HOLD_INTERRUPTS(), but that should not be necessary here since we don't
428 * call anything that could turn on ImmediateInterruptOK.
430 save_ImmediateInterruptOK = ImmediateInterruptOK;
431 ImmediateInterruptOK = false;
434 * Do processing in ErrorContext, which we hope has enough reserved space
435 * to report an error.
437 oldcontext = MemoryContextSwitchTo(ErrorContext);
440 * Call any context callback functions. Errors occurring in callback
441 * functions will be treated as recursive errors --- this ensures we will
442 * avoid infinite recursion (see errstart).
444 for (econtext = error_context_stack;
446 econtext = econtext->previous)
447 (*econtext->callback) (econtext->arg);
450 * If ERROR (not more nor less) we pass it off to the current handler.
451 * Printing it and popping the stack is the responsibility of the handler.
456 * We do some minimal cleanup before longjmp'ing so that handlers can
457 * execute in a reasonably sane state.
459 * Reset InterruptHoldoffCount in case we ereport'd from inside an
460 * interrupt holdoff section. (We assume here that no handler will
461 * itself be inside a holdoff section. If necessary, such a handler
462 * could save and restore InterruptHoldoffCount for itself, but this
463 * should make life easier for most.)
465 * Note that we intentionally don't restore ImmediateInterruptOK here,
466 * even if it was set at entry. We definitely don't want that on
467 * while doing error cleanup.
469 InterruptHoldoffCount = 0;
471 CritSectionCount = 0; /* should be unnecessary, but... */
474 * Note that we leave CurrentMemoryContext set to ErrorContext. The
475 * handler should reset it to something else soon.
483 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
484 * progress, so that we can report the message before dying. (Without
485 * this, pq_putmessage will refuse to send the message at all, which is
486 * what we want for NOTICE messages, but not for fatal exits.) This hack
487 * is necessary because of poor design of old-style copy protocol. Note
488 * we must do this even if client is fool enough to have set
489 * client_min_messages above FATAL, so don't look at output_to_client.
491 if (elevel >= FATAL && whereToSendOutput == DestRemote)
494 /* Emit the message to the right places */
497 /* Now free up subsidiary data attached to stack entry, and release it */
499 pfree(edata->message);
501 pfree(edata->detail);
502 if (edata->detail_log)
503 pfree(edata->detail_log);
507 pfree(edata->context);
508 if (edata->schema_name)
509 pfree(edata->schema_name);
510 if (edata->table_name)
511 pfree(edata->table_name);
512 if (edata->column_name)
513 pfree(edata->column_name);
514 if (edata->datatype_name)
515 pfree(edata->datatype_name);
516 if (edata->constraint_name)
517 pfree(edata->constraint_name);
518 if (edata->internalquery)
519 pfree(edata->internalquery);
521 errordata_stack_depth--;
523 /* Exit error-handling context */
524 MemoryContextSwitchTo(oldcontext);
528 * Perform error recovery action as specified by elevel.
533 * For a FATAL error, we let proc_exit clean up and exit.
535 * If we just reported a startup failure, the client will disconnect
536 * on receiving it, so don't send any more to the client.
538 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
539 whereToSendOutput = DestNone;
542 * fflush here is just to improve the odds that we get to see the
543 * error message, in case things are so hosed that proc_exit crashes.
544 * Any other code you might be tempted to add here should probably be
545 * in an on_proc_exit or on_shmem_exit callback instead.
551 * Do normal process-exit cleanup, then return exit code 1 to indicate
552 * FATAL termination. The postmaster may or may not consider this
553 * worthy of panic, depending on which subprocess returns it.
561 * Serious crash time. Postmaster will observe SIGABRT process exit
562 * status and kill the other backends too.
564 * XXX: what if we are *in* the postmaster? abort() won't kill our
573 * We reach here if elevel <= WARNING. OK to return to caller, so restore
574 * caller's setting of ImmediateInterruptOK.
576 ImmediateInterruptOK = save_ImmediateInterruptOK;
579 * But check for cancel/die interrupt first --- this is so that the user
580 * can stop a query emitting tons of notice or warning messages, even if
581 * it's in a loop that otherwise fails to check for interrupts.
583 CHECK_FOR_INTERRUPTS();
588 * errcode --- add SQLSTATE error code to the current error
590 * The code is expected to be represented as per MAKE_SQLSTATE().
593 errcode(int sqlerrcode)
595 ErrorData *edata = &errordata[errordata_stack_depth];
597 /* we don't bother incrementing recursion_depth */
600 edata->sqlerrcode = sqlerrcode;
602 return 0; /* return value does not matter */
607 * errcode_for_file_access --- add SQLSTATE error code to the current error
609 * The SQLSTATE code is chosen based on the saved errno value. We assume
610 * that the failing operation was some type of disk file access.
612 * NOTE: the primary error message string should generally include %m
616 errcode_for_file_access(void)
618 ErrorData *edata = &errordata[errordata_stack_depth];
620 /* we don't bother incrementing recursion_depth */
623 switch (edata->saved_errno)
625 /* Permission-denied failures */
626 case EPERM: /* Not super-user */
627 case EACCES: /* Permission denied */
629 case EROFS: /* Read only file system */
631 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
635 case ENOENT: /* No such file or directory */
636 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
640 case EEXIST: /* File exists */
641 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
644 /* Wrong object type or state */
645 case ENOTDIR: /* Not a directory */
646 case EISDIR: /* Is a directory */
647 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
648 case ENOTEMPTY: /* Directory not empty */
650 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
653 /* Insufficient resources */
654 case ENOSPC: /* No space left on device */
655 edata->sqlerrcode = ERRCODE_DISK_FULL;
658 case ENFILE: /* File table overflow */
659 case EMFILE: /* Too many open files */
660 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
663 /* Hardware failure */
664 case EIO: /* I/O error */
665 edata->sqlerrcode = ERRCODE_IO_ERROR;
668 /* All else is classified as internal errors */
670 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
674 return 0; /* return value does not matter */
678 * errcode_for_socket_access --- add SQLSTATE error code to the current error
680 * The SQLSTATE code is chosen based on the saved errno value. We assume
681 * that the failing operation was some type of socket access.
683 * NOTE: the primary error message string should generally include %m
687 errcode_for_socket_access(void)
689 ErrorData *edata = &errordata[errordata_stack_depth];
691 /* we don't bother incrementing recursion_depth */
694 switch (edata->saved_errno)
696 /* Loss of connection */
701 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
704 /* All else is classified as internal errors */
706 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
710 return 0; /* return value does not matter */
715 * This macro handles expansion of a format string and associated parameters;
716 * it's common code for errmsg(), errdetail(), etc. Must be called inside
717 * a routine that is declared like "const char *fmt, ..." and has an edata
718 * pointer set up. The message is assigned to edata->targetfield, or
719 * appended to it if appendval is true. The message is subject to translation
720 * if translateit is true.
722 * Note: we pstrdup the buffer rather than just transferring its storage
723 * to the edata field because the buffer might be considerably larger than
726 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
729 StringInfoData buf; \
730 /* Internationalize the error format string */ \
731 if (translateit && !in_error_recursion_trouble()) \
732 fmt = dgettext((domain), fmt); \
733 /* Expand %m in format string */ \
734 fmtbuf = expand_fmt_string(fmt, edata); \
735 initStringInfo(&buf); \
736 if ((appendval) && edata->targetfield) { \
737 appendStringInfoString(&buf, edata->targetfield); \
738 appendStringInfoChar(&buf, '\n'); \
740 /* Generate actual output --- have to use appendStringInfoVA */ \
745 va_start(args, fmt); \
746 needed = appendStringInfoVA(&buf, fmtbuf, args); \
750 enlargeStringInfo(&buf, needed); \
752 /* Done with expanded fmt */ \
754 /* Save the completed message into the stack item */ \
755 if (edata->targetfield) \
756 pfree(edata->targetfield); \
757 edata->targetfield = pstrdup(buf.data); \
762 * Same as above, except for pluralized error messages. The calling routine
763 * must be declared like "const char *fmt_singular, const char *fmt_plural,
764 * unsigned long n, ...". Translation is assumed always wanted.
766 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
770 StringInfoData buf; \
771 /* Internationalize the error format string */ \
772 if (!in_error_recursion_trouble()) \
773 fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
775 fmt = (n == 1 ? fmt_singular : fmt_plural); \
776 /* Expand %m in format string */ \
777 fmtbuf = expand_fmt_string(fmt, edata); \
778 initStringInfo(&buf); \
779 if ((appendval) && edata->targetfield) { \
780 appendStringInfoString(&buf, edata->targetfield); \
781 appendStringInfoChar(&buf, '\n'); \
783 /* Generate actual output --- have to use appendStringInfoVA */ \
789 needed = appendStringInfoVA(&buf, fmtbuf, args); \
793 enlargeStringInfo(&buf, needed); \
795 /* Done with expanded fmt */ \
797 /* Save the completed message into the stack item */ \
798 if (edata->targetfield) \
799 pfree(edata->targetfield); \
800 edata->targetfield = pstrdup(buf.data); \
806 * errmsg --- add a primary error message text to the current error
808 * In addition to the usual %-escapes recognized by printf, "%m" in
809 * fmt is replaced by the error message for the caller's value of errno.
811 * Note: no newline is needed at the end of the fmt string, since
812 * ereport will provide one for the output methods that need it.
815 errmsg(const char *fmt,...)
817 ErrorData *edata = &errordata[errordata_stack_depth];
818 MemoryContext oldcontext;
822 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
824 EVALUATE_MESSAGE(edata->domain, message, false, true);
826 MemoryContextSwitchTo(oldcontext);
828 return 0; /* return value does not matter */
833 * errmsg_internal --- add a primary error message text to the current error
835 * This is exactly like errmsg() except that strings passed to errmsg_internal
836 * are not translated, and are customarily left out of the
837 * internationalization message dictionary. This should be used for "can't
838 * happen" cases that are probably not worth spending translation effort on.
839 * We also use this for certain cases where we *must* not try to translate
840 * the message because the translation would fail and result in infinite
844 errmsg_internal(const char *fmt,...)
846 ErrorData *edata = &errordata[errordata_stack_depth];
847 MemoryContext oldcontext;
851 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
853 EVALUATE_MESSAGE(edata->domain, message, false, false);
855 MemoryContextSwitchTo(oldcontext);
857 return 0; /* return value does not matter */
862 * errmsg_plural --- add a primary error message text to the current error,
863 * with support for pluralization of the message text
866 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
869 ErrorData *edata = &errordata[errordata_stack_depth];
870 MemoryContext oldcontext;
874 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
876 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
878 MemoryContextSwitchTo(oldcontext);
880 return 0; /* return value does not matter */
885 * errdetail --- add a detail error message text to the current error
888 errdetail(const char *fmt,...)
890 ErrorData *edata = &errordata[errordata_stack_depth];
891 MemoryContext oldcontext;
895 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
897 EVALUATE_MESSAGE(edata->domain, detail, false, true);
899 MemoryContextSwitchTo(oldcontext);
901 return 0; /* return value does not matter */
906 * errdetail_internal --- add a detail error message text to the current error
908 * This is exactly like errdetail() except that strings passed to
909 * errdetail_internal are not translated, and are customarily left out of the
910 * internationalization message dictionary. This should be used for detail
911 * messages that seem not worth translating for one reason or another
912 * (typically, that they don't seem to be useful to average users).
915 errdetail_internal(const char *fmt,...)
917 ErrorData *edata = &errordata[errordata_stack_depth];
918 MemoryContext oldcontext;
922 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
924 EVALUATE_MESSAGE(edata->domain, detail, false, false);
926 MemoryContextSwitchTo(oldcontext);
928 return 0; /* return value does not matter */
933 * errdetail_log --- add a detail_log error message text to the current error
936 errdetail_log(const char *fmt,...)
938 ErrorData *edata = &errordata[errordata_stack_depth];
939 MemoryContext oldcontext;
943 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
945 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
947 MemoryContextSwitchTo(oldcontext);
949 return 0; /* return value does not matter */
953 * errdetail_log_plural --- add a detail_log error message text to the current error
954 * with support for pluralization of the message text
957 errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
960 ErrorData *edata = &errordata[errordata_stack_depth];
961 MemoryContext oldcontext;
965 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
967 EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
969 MemoryContextSwitchTo(oldcontext);
971 return 0; /* return value does not matter */
976 * errdetail_plural --- add a detail error message text to the current error,
977 * with support for pluralization of the message text
980 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
983 ErrorData *edata = &errordata[errordata_stack_depth];
984 MemoryContext oldcontext;
988 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
990 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
992 MemoryContextSwitchTo(oldcontext);
994 return 0; /* return value does not matter */
999 * errhint --- add a hint error message text to the current error
1002 errhint(const char *fmt,...)
1004 ErrorData *edata = &errordata[errordata_stack_depth];
1005 MemoryContext oldcontext;
1008 CHECK_STACK_DEPTH();
1009 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1011 EVALUATE_MESSAGE(edata->domain, hint, false, true);
1013 MemoryContextSwitchTo(oldcontext);
1015 return 0; /* return value does not matter */
1020 * errcontext_msg --- add a context error message text to the current error
1022 * Unlike other cases, multiple calls are allowed to build up a stack of
1023 * context information. We assume earlier calls represent more-closely-nested
1027 errcontext_msg(const char *fmt,...)
1029 ErrorData *edata = &errordata[errordata_stack_depth];
1030 MemoryContext oldcontext;
1033 CHECK_STACK_DEPTH();
1034 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1036 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1038 MemoryContextSwitchTo(oldcontext);
1040 return 0; /* return value does not matter */
1044 * set_errcontext_domain --- set message domain to be used by errcontext()
1046 * errcontext_msg() can be called from a different module than the original
1047 * ereport(), so we cannot use the message domain passed in errstart() to
1048 * translate it. Instead, each errcontext_msg() call should be preceded by
1049 * a set_errcontext_domain() call to specify the domain. This is usually
1050 * done transparently by the errcontext() macro.
1053 set_errcontext_domain(const char *domain)
1055 ErrorData *edata = &errordata[errordata_stack_depth];
1057 /* we don't bother incrementing recursion_depth */
1058 CHECK_STACK_DEPTH();
1060 edata->context_domain = domain;
1062 return 0; /* return value does not matter */
1067 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1069 * This should be called if the message text already includes the statement.
1072 errhidestmt(bool hide_stmt)
1074 ErrorData *edata = &errordata[errordata_stack_depth];
1076 /* we don't bother incrementing recursion_depth */
1077 CHECK_STACK_DEPTH();
1079 edata->hide_stmt = hide_stmt;
1081 return 0; /* return value does not matter */
1086 * errfunction --- add reporting function name to the current error
1088 * This is used when backwards compatibility demands that the function
1089 * name appear in messages sent to old-protocol clients. Note that the
1090 * passed string is expected to be a non-freeable constant string.
1093 errfunction(const char *funcname)
1095 ErrorData *edata = &errordata[errordata_stack_depth];
1097 /* we don't bother incrementing recursion_depth */
1098 CHECK_STACK_DEPTH();
1100 edata->funcname = funcname;
1101 edata->show_funcname = true;
1103 return 0; /* return value does not matter */
1107 * errposition --- add cursor position to the current error
1110 errposition(int cursorpos)
1112 ErrorData *edata = &errordata[errordata_stack_depth];
1114 /* we don't bother incrementing recursion_depth */
1115 CHECK_STACK_DEPTH();
1117 edata->cursorpos = cursorpos;
1119 return 0; /* return value does not matter */
1123 * internalerrposition --- add internal cursor position to the current error
1126 internalerrposition(int cursorpos)
1128 ErrorData *edata = &errordata[errordata_stack_depth];
1130 /* we don't bother incrementing recursion_depth */
1131 CHECK_STACK_DEPTH();
1133 edata->internalpos = cursorpos;
1135 return 0; /* return value does not matter */
1139 * internalerrquery --- add internal query text to the current error
1141 * Can also pass NULL to drop the internal query text entry. This case
1142 * is intended for use in error callback subroutines that are editorializing
1143 * on the layout of the error report.
1146 internalerrquery(const char *query)
1148 ErrorData *edata = &errordata[errordata_stack_depth];
1150 /* we don't bother incrementing recursion_depth */
1151 CHECK_STACK_DEPTH();
1153 if (edata->internalquery)
1155 pfree(edata->internalquery);
1156 edata->internalquery = NULL;
1160 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1162 return 0; /* return value does not matter */
1166 * err_generic_string -- used to set individual ErrorData string fields
1167 * identified by PG_DIAG_xxx codes.
1169 * This intentionally only supports fields that don't use localized strings,
1170 * so that there are no translation considerations.
1172 * Most potential callers should not use this directly, but instead prefer
1173 * higher-level abstractions, such as errtablecol() (see relcache.c).
1176 err_generic_string(int field, const char *str)
1178 ErrorData *edata = &errordata[errordata_stack_depth];
1180 /* we don't bother incrementing recursion_depth */
1181 CHECK_STACK_DEPTH();
1185 case PG_DIAG_SCHEMA_NAME:
1186 set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1188 case PG_DIAG_TABLE_NAME:
1189 set_errdata_field(edata->assoc_context, &edata->table_name, str);
1191 case PG_DIAG_COLUMN_NAME:
1192 set_errdata_field(edata->assoc_context, &edata->column_name, str);
1194 case PG_DIAG_DATATYPE_NAME:
1195 set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1197 case PG_DIAG_CONSTRAINT_NAME:
1198 set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1201 elog(ERROR, "unsupported ErrorData field id: %d", field);
1205 return 0; /* return value does not matter */
1209 * set_errdata_field --- set an ErrorData string field
1212 set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1214 Assert(*ptr == NULL);
1215 *ptr = MemoryContextStrdup(cxt, str);
1219 * geterrcode --- return the currently set SQLSTATE error code
1221 * This is only intended for use in error callback subroutines, since there
1222 * is no other place outside elog.c where the concept is meaningful.
1227 ErrorData *edata = &errordata[errordata_stack_depth];
1229 /* we don't bother incrementing recursion_depth */
1230 CHECK_STACK_DEPTH();
1232 return edata->sqlerrcode;
1236 * geterrposition --- return the currently set error position (0 if none)
1238 * This is only intended for use in error callback subroutines, since there
1239 * is no other place outside elog.c where the concept is meaningful.
1242 geterrposition(void)
1244 ErrorData *edata = &errordata[errordata_stack_depth];
1246 /* we don't bother incrementing recursion_depth */
1247 CHECK_STACK_DEPTH();
1249 return edata->cursorpos;
1253 * getinternalerrposition --- same for internal error position
1255 * This is only intended for use in error callback subroutines, since there
1256 * is no other place outside elog.c where the concept is meaningful.
1259 getinternalerrposition(void)
1261 ErrorData *edata = &errordata[errordata_stack_depth];
1263 /* we don't bother incrementing recursion_depth */
1264 CHECK_STACK_DEPTH();
1266 return edata->internalpos;
1271 * elog_start --- startup for old-style API
1273 * All that we do here is stash the hidden filename/lineno/funcname
1274 * arguments into a stack entry, along with the current value of errno.
1276 * We need this to be separate from elog_finish because there's no other
1277 * C89-compliant way to deal with inserting extra arguments into the elog
1278 * call. (When using C99's __VA_ARGS__, we could possibly merge this with
1279 * elog_finish, but there doesn't seem to be a good way to save errno before
1280 * evaluating the format arguments if we do that.)
1283 elog_start(const char *filename, int lineno, const char *funcname)
1287 /* Make sure that memory context initialization has finished */
1288 if (ErrorContext == NULL)
1290 /* Ooops, hard crash time; very little we can do safely here */
1291 write_stderr("error occurred at %s:%d before error message processing is available\n",
1292 filename ? filename : "(unknown file)", lineno);
1296 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1299 * Wups, stack not big enough. We treat this as a PANIC condition
1300 * because it suggests an infinite loop of errors during error
1301 * recovery. Note that the message is intentionally not localized,
1302 * else failure to convert it to client encoding could cause further
1305 errordata_stack_depth = -1; /* make room on stack */
1306 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1309 edata = &errordata[errordata_stack_depth];
1314 /* keep only base name, useful especially for vpath builds */
1315 slash = strrchr(filename, '/');
1317 filename = slash + 1;
1319 edata->filename = filename;
1320 edata->lineno = lineno;
1321 edata->funcname = funcname;
1322 /* errno is saved now so that error parameter eval can't change it */
1323 edata->saved_errno = errno;
1325 /* Use ErrorContext for any allocations done at this level. */
1326 edata->assoc_context = ErrorContext;
1330 * elog_finish --- finish up for old-style API
1333 elog_finish(int elevel, const char *fmt,...)
1335 ErrorData *edata = &errordata[errordata_stack_depth];
1336 MemoryContext oldcontext;
1338 CHECK_STACK_DEPTH();
1341 * Do errstart() to see if we actually want to report the message.
1343 errordata_stack_depth--;
1344 errno = edata->saved_errno;
1345 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1346 return; /* nothing to do */
1349 * Format error message just like errmsg_internal().
1352 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1354 EVALUATE_MESSAGE(edata->domain, message, false, false);
1356 MemoryContextSwitchTo(oldcontext);
1360 * And let errfinish() finish up.
1367 * Functions to allow construction of error message strings separately from
1368 * the ereport() call itself.
1370 * The expected calling convention is
1372 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1374 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1375 * assume that any functions called in the arguments of format_elog_string()
1376 * cannot result in re-entrant use of these functions --- otherwise the wrong
1377 * text domain might be used, or the wrong errno substituted for %m. This is
1378 * okay for the current usage with GUC check hooks, but might need further
1381 * The result of format_elog_string() is stored in ErrorContext, and will
1382 * therefore survive until FlushErrorState() is called.
1384 static int save_format_errnumber;
1385 static const char *save_format_domain;
1388 pre_format_elog_string(int errnumber, const char *domain)
1390 /* Save errno before evaluation of argument functions can change it */
1391 save_format_errnumber = errnumber;
1392 /* Save caller's text domain */
1393 save_format_domain = domain;
1397 format_elog_string(const char *fmt,...)
1401 MemoryContext oldcontext;
1403 /* Initialize a mostly-dummy error frame */
1405 MemSet(edata, 0, sizeof(ErrorData));
1406 /* the default text domain is the backend's */
1407 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1408 /* set the errno to be used to interpret %m */
1409 edata->saved_errno = save_format_errnumber;
1411 oldcontext = MemoryContextSwitchTo(ErrorContext);
1413 EVALUATE_MESSAGE(edata->domain, message, false, true);
1415 MemoryContextSwitchTo(oldcontext);
1417 return edata->message;
1422 * Actual output of the top-of-stack error message
1424 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1425 * if the error is caught by somebody). For all other severity levels this
1426 * is called by errfinish.
1429 EmitErrorReport(void)
1431 ErrorData *edata = &errordata[errordata_stack_depth];
1432 MemoryContext oldcontext;
1435 CHECK_STACK_DEPTH();
1436 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1439 * Call hook before sending message to log. The hook function is allowed
1440 * to turn off edata->output_to_server, so we must recheck that afterward.
1441 * Making any other change in the content of edata is not considered
1444 * Note: the reason why the hook can only turn off output_to_server, and
1445 * not turn it on, is that it'd be unreliable: we will never get here at
1446 * all if errstart() deems the message uninteresting. A hook that could
1447 * make decisions in that direction would have to hook into errstart(),
1448 * where it would have much less information available. emit_log_hook is
1449 * intended for custom log filtering and custom log message transmission
1452 if (edata->output_to_server && emit_log_hook)
1453 (*emit_log_hook) (edata);
1455 /* Send to server log, if enabled */
1456 if (edata->output_to_server)
1457 send_message_to_server_log(edata);
1459 /* Send to client, if enabled */
1460 if (edata->output_to_client)
1461 send_message_to_frontend(edata);
1463 MemoryContextSwitchTo(oldcontext);
1468 * CopyErrorData --- obtain a copy of the topmost error stack entry
1470 * This is only for use in error handler code. The data is copied into the
1471 * current memory context, so callers should always switch away from
1472 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1477 ErrorData *edata = &errordata[errordata_stack_depth];
1478 ErrorData *newedata;
1481 * we don't increment recursion_depth because out-of-memory here does not
1482 * indicate a problem within the error subsystem.
1484 CHECK_STACK_DEPTH();
1486 Assert(CurrentMemoryContext != ErrorContext);
1488 /* Copy the struct itself */
1489 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1490 memcpy(newedata, edata, sizeof(ErrorData));
1492 /* Make copies of separately-allocated fields */
1493 if (newedata->message)
1494 newedata->message = pstrdup(newedata->message);
1495 if (newedata->detail)
1496 newedata->detail = pstrdup(newedata->detail);
1497 if (newedata->detail_log)
1498 newedata->detail_log = pstrdup(newedata->detail_log);
1500 newedata->hint = pstrdup(newedata->hint);
1501 if (newedata->context)
1502 newedata->context = pstrdup(newedata->context);
1503 if (newedata->schema_name)
1504 newedata->schema_name = pstrdup(newedata->schema_name);
1505 if (newedata->table_name)
1506 newedata->table_name = pstrdup(newedata->table_name);
1507 if (newedata->column_name)
1508 newedata->column_name = pstrdup(newedata->column_name);
1509 if (newedata->datatype_name)
1510 newedata->datatype_name = pstrdup(newedata->datatype_name);
1511 if (newedata->constraint_name)
1512 newedata->constraint_name = pstrdup(newedata->constraint_name);
1513 if (newedata->internalquery)
1514 newedata->internalquery = pstrdup(newedata->internalquery);
1516 /* Use the calling context for string allocation */
1517 newedata->assoc_context = CurrentMemoryContext;
1523 * FreeErrorData --- free the structure returned by CopyErrorData.
1525 * Error handlers should use this in preference to assuming they know all
1526 * the separately-allocated fields.
1529 FreeErrorData(ErrorData *edata)
1532 pfree(edata->message);
1534 pfree(edata->detail);
1535 if (edata->detail_log)
1536 pfree(edata->detail_log);
1540 pfree(edata->context);
1541 if (edata->schema_name)
1542 pfree(edata->schema_name);
1543 if (edata->table_name)
1544 pfree(edata->table_name);
1545 if (edata->column_name)
1546 pfree(edata->column_name);
1547 if (edata->datatype_name)
1548 pfree(edata->datatype_name);
1549 if (edata->constraint_name)
1550 pfree(edata->constraint_name);
1551 if (edata->internalquery)
1552 pfree(edata->internalquery);
1557 * FlushErrorState --- flush the error state after error recovery
1559 * This should be called by an error handler after it's done processing
1560 * the error; or as soon as it's done CopyErrorData, if it intends to
1561 * do stuff that is likely to provoke another error. You are not "out" of
1562 * the error subsystem until you have done this.
1565 FlushErrorState(void)
1568 * Reset stack to empty. The only case where it would be more than one
1569 * deep is if we serviced an error that interrupted construction of
1570 * another message. We assume control escaped out of that message
1571 * construction and won't ever go back.
1573 errordata_stack_depth = -1;
1574 recursion_depth = 0;
1575 /* Delete all data in ErrorContext */
1576 MemoryContextResetAndDeleteChildren(ErrorContext);
1580 * ReThrowError --- re-throw a previously copied error
1582 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1583 * subsystem, then do some processing, and finally ReThrowError to re-throw
1584 * the original error. This is slower than just PG_RE_THROW() but should
1585 * be used if the "some processing" is likely to incur another error.
1588 ReThrowError(ErrorData *edata)
1590 ErrorData *newedata;
1592 Assert(edata->elevel == ERROR);
1594 /* Push the data back into the error context */
1596 MemoryContextSwitchTo(ErrorContext);
1598 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1601 * Wups, stack not big enough. We treat this as a PANIC condition
1602 * because it suggests an infinite loop of errors during error
1605 errordata_stack_depth = -1; /* make room on stack */
1606 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1609 newedata = &errordata[errordata_stack_depth];
1610 memcpy(newedata, edata, sizeof(ErrorData));
1612 /* Make copies of separately-allocated fields */
1613 if (newedata->message)
1614 newedata->message = pstrdup(newedata->message);
1615 if (newedata->detail)
1616 newedata->detail = pstrdup(newedata->detail);
1617 if (newedata->detail_log)
1618 newedata->detail_log = pstrdup(newedata->detail_log);
1620 newedata->hint = pstrdup(newedata->hint);
1621 if (newedata->context)
1622 newedata->context = pstrdup(newedata->context);
1623 if (newedata->schema_name)
1624 newedata->schema_name = pstrdup(newedata->schema_name);
1625 if (newedata->table_name)
1626 newedata->table_name = pstrdup(newedata->table_name);
1627 if (newedata->column_name)
1628 newedata->column_name = pstrdup(newedata->column_name);
1629 if (newedata->datatype_name)
1630 newedata->datatype_name = pstrdup(newedata->datatype_name);
1631 if (newedata->constraint_name)
1632 newedata->constraint_name = pstrdup(newedata->constraint_name);
1633 if (newedata->internalquery)
1634 newedata->internalquery = pstrdup(newedata->internalquery);
1636 /* Reset the assoc_context to be ErrorContext */
1637 newedata->assoc_context = ErrorContext;
1644 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1649 /* If possible, throw the error to the next outer setjmp handler */
1650 if (PG_exception_stack != NULL)
1651 siglongjmp(*PG_exception_stack, 1);
1655 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1656 * we have now exited only to discover that there is no outer setjmp
1657 * handler to pass the error to. Had the error been thrown outside
1658 * the block to begin with, we'd have promoted the error to FATAL, so
1659 * the correct behavior is to make it FATAL now; that is, emit it and
1660 * then call proc_exit.
1662 ErrorData *edata = &errordata[errordata_stack_depth];
1664 Assert(errordata_stack_depth >= 0);
1665 Assert(edata->elevel == ERROR);
1666 edata->elevel = FATAL;
1669 * At least in principle, the increase in severity could have changed
1670 * where-to-output decisions, so recalculate. This should stay in
1671 * sync with errstart(), which see for comments.
1673 if (IsPostmasterEnvironment)
1674 edata->output_to_server = is_log_level_output(FATAL,
1677 edata->output_to_server = (FATAL >= log_min_messages);
1678 if (whereToSendOutput == DestRemote)
1680 if (ClientAuthInProgress)
1681 edata->output_to_client = true;
1683 edata->output_to_client = (FATAL >= client_min_messages);
1687 * We can use errfinish() for the rest, but we don't want it to call
1688 * any error context routines a second time. Since we know we are
1689 * about to exit, it should be OK to just clear the context stack.
1691 error_context_stack = NULL;
1696 /* Doesn't return ... */
1697 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1698 __FILE__, __LINE__);
1703 * GetErrorContextStack - Return the context stack, for display/diags
1705 * Returns a pstrdup'd string in the caller's context which includes the PG
1706 * error call stack. It is the caller's responsibility to ensure this string
1707 * is pfree'd (or its context cleaned up) when done.
1709 * This information is collected by traversing the error contexts and calling
1710 * each context's callback function, each of which is expected to call
1711 * errcontext() to return a string which can be presented to the user.
1714 GetErrorContextStack(void)
1717 ErrorContextCallback *econtext;
1720 * Okay, crank up a stack entry to store the info in.
1724 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1727 * Wups, stack not big enough. We treat this as a PANIC condition
1728 * because it suggests an infinite loop of errors during error
1731 errordata_stack_depth = -1; /* make room on stack */
1732 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1736 * Things look good so far, so initialize our error frame
1738 edata = &errordata[errordata_stack_depth];
1739 MemSet(edata, 0, sizeof(ErrorData));
1742 * Set up assoc_context to be the caller's context, so any allocations
1743 * done (which will include edata->context) will use their context.
1745 edata->assoc_context = CurrentMemoryContext;
1748 * Call any context callback functions to collect the context information
1749 * into edata->context.
1751 * Errors occurring in callback functions should go through the regular
1752 * error handling code which should handle any recursive errors, though we
1753 * double-check above, just in case.
1755 for (econtext = error_context_stack;
1757 econtext = econtext->previous)
1758 (*econtext->callback) (econtext->arg);
1761 * Clean ourselves off the stack, any allocations done should have been
1762 * using edata->assoc_context, which we set up earlier to be the caller's
1763 * context, so we're free to just remove our entry off the stack and
1764 * decrement recursion depth and exit.
1766 errordata_stack_depth--;
1770 * Return a pointer to the string the caller asked for, which should have
1771 * been allocated in their context.
1773 return edata->context;
1778 * Initialization of error output file
1786 if (OutputFileName[0])
1789 * A debug-output file name was given.
1791 * Make sure we can write the file, and find out if it's a tty.
1793 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1796 (errcode_for_file_access(),
1797 errmsg("could not open file \"%s\": %m", OutputFileName)));
1802 * Redirect our stderr to the debug output file.
1804 if (!freopen(OutputFileName, "a", stderr))
1806 (errcode_for_file_access(),
1807 errmsg("could not reopen file \"%s\" as stderr: %m",
1811 * If the file is a tty and we're running under the postmaster, try to
1812 * send stdout there as well (if it isn't a tty then stderr will block
1813 * out stdout, so we may as well let stdout go wherever it was going
1816 if (istty && IsUnderPostmaster)
1817 if (!freopen(OutputFileName, "a", stdout))
1819 (errcode_for_file_access(),
1820 errmsg("could not reopen file \"%s\" as stdout: %m",
1829 * Set or update the parameters for syslog logging
1832 set_syslog_parameters(const char *ident, int facility)
1835 * guc.c is likely to call us repeatedly with same parameters, so don't
1836 * thrash the syslog connection unnecessarily. Also, we do not re-open
1837 * the connection until needed, since this routine will get called whether
1838 * or not Log_destination actually mentions syslog.
1840 * Note that we make our own copy of the ident string rather than relying
1841 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1842 * accidentally free a string that syslog is still using.
1844 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1845 syslog_facility != facility)
1850 openlog_done = false;
1854 syslog_ident = strdup(ident);
1855 /* if the strdup fails, we will cope in write_syslog() */
1856 syslog_facility = facility;
1862 * Write a message line to syslog
1865 write_syslog(int level, const char *line)
1867 static unsigned long seq = 0;
1872 /* Open syslog connection if not done yet */
1875 openlog(syslog_ident ? syslog_ident : "postgres",
1876 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1878 openlog_done = true;
1882 * We add a sequence number to each log message to suppress "same"
1888 * Our problem here is that many syslog implementations don't handle long
1889 * messages in an acceptable manner. While this function doesn't help that
1890 * fact, it does work around by splitting up messages into smaller pieces.
1892 * We divide into multiple syslog() calls if message is too long or if the
1893 * message contains embedded newline(s).
1896 nlpos = strchr(line, '\n');
1897 if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1903 char buf[PG_SYSLOG_LIMIT + 1];
1907 /* if we start at a newline, move ahead one char */
1908 if (line[0] == '\n')
1912 /* we need to recompute the next newline's position, too */
1913 nlpos = strchr(line, '\n');
1917 /* copy one line, or as much as will fit, to buf */
1919 buflen = nlpos - line;
1922 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1923 memcpy(buf, line, buflen);
1926 /* trim to multibyte letter boundary */
1927 buflen = pg_mbcliplen(buf, buflen, buflen);
1932 /* already word boundary? */
1933 if (line[buflen] != '\0' &&
1934 !isspace((unsigned char) line[buflen]))
1936 /* try to divide at word boundary */
1938 while (i > 0 && !isspace((unsigned char) buf[i]))
1941 if (i > 0) /* else couldn't divide word boundary */
1950 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1957 /* message short enough */
1958 syslog(level, "[%lu] %s", seq, line);
1961 #endif /* HAVE_SYSLOG */
1965 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
1966 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
1967 * Every process in a given system will find the same value at all times.
1970 GetACPEncoding(void)
1972 static int encoding = -2;
1975 encoding = pg_codepage_to_encoding(GetACP());
1981 * Write a message line to the windows event log
1984 write_eventlog(int level, const char *line, int len)
1987 int eventlevel = EVENTLOG_ERROR_TYPE;
1988 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1990 if (evtHandle == INVALID_HANDLE_VALUE)
1992 evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
1993 if (evtHandle == NULL)
1995 evtHandle = INVALID_HANDLE_VALUE;
2011 eventlevel = EVENTLOG_INFORMATION_TYPE;
2014 eventlevel = EVENTLOG_WARNING_TYPE;
2020 eventlevel = EVENTLOG_ERROR_TYPE;
2025 * If message character encoding matches the encoding expected by
2026 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
2027 * try to convert the message to UTF16 and write it with ReportEventW().
2028 * Fall back on ReportEventA() if conversion failed.
2030 * Also verify that we are not on our way into error recursion trouble due
2031 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2033 if (!in_error_recursion_trouble() &&
2034 GetMessageEncoding() != GetACPEncoding())
2036 utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2039 ReportEventW(evtHandle,
2042 0, /* All events are Id 0 */
2048 /* XXX Try ReportEventA() when ReportEventW() fails? */
2054 ReportEventA(evtHandle,
2057 0, /* All events are Id 0 */
2067 write_console(const char *line, int len)
2074 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2075 * Fall back on write() if anything fails.
2077 * In contrast to write_eventlog(), don't skip straight to write() based
2078 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2079 * on the suitability of the console output code page. Since we put
2080 * stderr into binary mode in SubPostmasterMain(), write() skips the
2081 * necessary translation anyway.
2083 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2084 * to writing unconverted to the logfile in this case.
2086 * Since we palloc the structure required for conversion, also fall
2087 * through to writing unconverted if we have not yet set up
2088 * CurrentMemoryContext.
2090 if (!in_error_recursion_trouble() &&
2091 !redirection_done &&
2092 CurrentMemoryContext != NULL)
2097 utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2103 stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2104 if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2111 * In case WriteConsoleW() failed, fall back to writing the
2112 * message unconverted.
2120 * Conversion on non-win32 platforms is not implemented yet. It requires
2121 * non-throw version of pg_do_encoding_conversion(), that converts
2122 * unconvertable characters to '?' without errors.
2127 * We ignore any error from write() here. We have no useful way to report
2128 * it ... certainly whining on stderr isn't likely to be productive.
2130 rc = write(fileno(stderr), line, len);
2135 * setup formatted_log_time, for consistent times between CSV and regular logs
2138 setup_formatted_log_time(void)
2141 pg_time_t stamp_time;
2144 gettimeofday(&tv, NULL);
2145 stamp_time = (pg_time_t) tv.tv_sec;
2148 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2149 * least with a minimal GMT value) before Log_line_prefix can become
2150 * nonempty or CSV mode can be selected.
2152 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
2153 /* leave room for milliseconds... */
2154 "%Y-%m-%d %H:%M:%S %Z",
2155 pg_localtime(&stamp_time, log_timezone));
2157 /* 'paste' milliseconds into place... */
2158 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
2159 strncpy(formatted_log_time + 19, msbuf, 4);
2163 * setup formatted_start_time
2166 setup_formatted_start_time(void)
2168 pg_time_t stamp_time = (pg_time_t) MyStartTime;
2171 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2172 * least with a minimal GMT value) before Log_line_prefix can become
2173 * nonempty or CSV mode can be selected.
2175 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
2176 "%Y-%m-%d %H:%M:%S %Z",
2177 pg_localtime(&stamp_time, log_timezone));
2181 * process_log_prefix_padding --- helper function for processing the format
2182 * string in log_line_prefix
2184 * Note: This function returns NULL if it finds something which
2185 * it deems invalid in the format string.
2188 process_log_prefix_padding(const char *p, int *ppadding)
2190 int paddingsign = 1;
2197 if (*p == '\0') /* Did the buf end in %- ? */
2202 /* generate an int version of the numerical string */
2203 while (*p >= '0' && *p <= '9')
2204 padding = padding * 10 + (*p++ - '0');
2206 /* format is invalid if it ends with the padding number */
2210 padding *= paddingsign;
2211 *ppadding = padding;
2216 * Format tag info for log lines; append to the provided buffer.
2219 log_line_prefix(StringInfo buf, ErrorData *edata)
2221 /* static counter for line numbers */
2222 static long log_line_number = 0;
2224 /* has counter been reset in current process? */
2225 static int log_my_pid = 0;
2230 * This is one of the few places where we'd rather not inherit a static
2231 * variable's value from the postmaster. But since we will, reset it when
2232 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2233 * reset the formatted start timestamp too.
2235 if (log_my_pid != MyProcPid)
2237 log_line_number = 0;
2238 log_my_pid = MyProcPid;
2239 formatted_start_time[0] = '\0';
2243 if (Log_line_prefix == NULL)
2244 return; /* in case guc hasn't run yet */
2246 for (p = Log_line_prefix; *p != '\0'; p++)
2250 /* literal char, just copy */
2251 appendStringInfoChar(buf, *p);
2255 /* must be a '%', so skip to the next char */
2258 break; /* format error - ignore it */
2261 /* string contains %% */
2262 appendStringInfoChar(buf, '%');
2268 * Process any formatting which may exist after the '%'. Note that
2269 * process_log_prefix_padding moves p past the padding number if it
2272 * Note: Since only '-', '0' to '9' are valid formatting characters we
2273 * can do a quick check here to pre-check for formatting. If the char
2274 * is not formatting then we can skip a useless function call.
2276 * Further note: At least on some platforms, passing %*s rather than
2277 * %s to appendStringInfo() is substantially slower, so many of the
2278 * cases below avoid doing that unless non-zero padding is in fact
2283 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2286 /* process the option */
2292 const char *appname = application_name;
2294 if (appname == NULL || *appname == '\0')
2295 appname = _("[unknown]");
2297 appendStringInfo(buf, "%*s", padding, appname);
2299 appendStringInfoString(buf, appname);
2301 else if (padding != 0)
2302 appendStringInfoSpaces(buf,
2303 padding > 0 ? padding : -padding);
2309 const char *username = MyProcPort->user_name;
2311 if (username == NULL || *username == '\0')
2312 username = _("[unknown]");
2314 appendStringInfo(buf, "%*s", padding, username);
2316 appendStringInfoString(buf, username);
2318 else if (padding != 0)
2319 appendStringInfoSpaces(buf,
2320 padding > 0 ? padding : -padding);
2325 const char *dbname = MyProcPort->database_name;
2327 if (dbname == NULL || *dbname == '\0')
2328 dbname = _("[unknown]");
2330 appendStringInfo(buf, "%*s", padding, dbname);
2332 appendStringInfoString(buf, dbname);
2334 else if (padding != 0)
2335 appendStringInfoSpaces(buf,
2336 padding > 0 ? padding : -padding);
2343 snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2344 (long) (MyStartTime), MyProcPid);
2345 appendStringInfo(buf, "%*s", padding, strfbuf);
2348 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2352 appendStringInfo(buf, "%*d", padding, MyProcPid);
2354 appendStringInfo(buf, "%d", MyProcPid);
2358 appendStringInfo(buf, "%*ld", padding, log_line_number);
2360 appendStringInfo(buf, "%ld", log_line_number);
2363 setup_formatted_log_time();
2365 appendStringInfo(buf, "%*s", padding, formatted_log_time);
2367 appendStringInfoString(buf, formatted_log_time);
2371 pg_time_t stamp_time = (pg_time_t) time(NULL);
2374 pg_strftime(strfbuf, sizeof(strfbuf),
2375 "%Y-%m-%d %H:%M:%S %Z",
2376 pg_localtime(&stamp_time, log_timezone));
2378 appendStringInfo(buf, "%*s", padding, strfbuf);
2380 appendStringInfoString(buf, strfbuf);
2384 if (formatted_start_time[0] == '\0')
2385 setup_formatted_start_time();
2387 appendStringInfo(buf, "%*s", padding, formatted_start_time);
2389 appendStringInfoString(buf, formatted_start_time);
2397 psdisp = get_ps_display(&displen);
2399 appendStringInfo(buf, "%*s", padding, psdisp);
2401 appendBinaryStringInfo(buf, psdisp, displen);
2404 else if (padding != 0)
2405 appendStringInfoSpaces(buf,
2406 padding > 0 ? padding : -padding);
2409 if (MyProcPort && MyProcPort->remote_host)
2413 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2416 * This option is slightly special as the port
2417 * number may be appended onto the end. Here we
2418 * need to build 1 string which contains the
2419 * remote_host and optionally the remote_port (if
2420 * set) so we can properly align the string.
2425 hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2426 appendStringInfo(buf, "%*s", padding, hostport);
2430 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2434 /* padding is 0, so we don't need a temp buffer */
2435 appendStringInfoString(buf, MyProcPort->remote_host);
2436 if (MyProcPort->remote_port &&
2437 MyProcPort->remote_port[0] != '\0')
2438 appendStringInfo(buf, "(%s)",
2439 MyProcPort->remote_port);
2443 else if (padding != 0)
2444 appendStringInfoSpaces(buf,
2445 padding > 0 ? padding : -padding);
2448 if (MyProcPort && MyProcPort->remote_host)
2451 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2453 appendStringInfoString(buf, MyProcPort->remote_host);
2455 else if (padding != 0)
2456 appendStringInfoSpaces(buf,
2457 padding > 0 ? padding : -padding);
2460 /* in postmaster and friends, stop if %q is seen */
2461 /* in a backend, just ignore */
2462 if (MyProcPort == NULL)
2466 /* keep VXID format in sync with lockfuncs.c */
2467 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2473 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2474 MyProc->backendId, MyProc->lxid);
2475 appendStringInfo(buf, "%*s", padding, strfbuf);
2478 appendStringInfo(buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2480 else if (padding != 0)
2481 appendStringInfoSpaces(buf,
2482 padding > 0 ? padding : -padding);
2486 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2488 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2492 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2494 appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2497 /* format error - ignore it */
2504 * append a CSV'd version of a string to a StringInfo
2505 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2506 * If it's NULL, append nothing.
2509 appendCSVLiteral(StringInfo buf, const char *data)
2511 const char *p = data;
2514 /* avoid confusing an empty string with NULL */
2518 appendStringInfoCharMacro(buf, '"');
2519 while ((c = *p++) != '\0')
2522 appendStringInfoCharMacro(buf, '"');
2523 appendStringInfoCharMacro(buf, c);
2525 appendStringInfoCharMacro(buf, '"');
2529 * Constructs the error message, depending on the Errordata it gets, in a CSV
2530 * format which is described in doc/src/sgml/config.sgml.
2533 write_csvlog(ErrorData *edata)
2536 bool print_stmt = false;
2538 /* static counter for line numbers */
2539 static long log_line_number = 0;
2541 /* has counter been reset in current process? */
2542 static int log_my_pid = 0;
2545 * This is one of the few places where we'd rather not inherit a static
2546 * variable's value from the postmaster. But since we will, reset it when
2547 * MyProcPid changes.
2549 if (log_my_pid != MyProcPid)
2551 log_line_number = 0;
2552 log_my_pid = MyProcPid;
2553 formatted_start_time[0] = '\0';
2557 initStringInfo(&buf);
2560 * timestamp with milliseconds
2562 * Check if the timestamp is already calculated for the syslog message,
2563 * and use it if so. Otherwise, get the current timestamp. This is done
2564 * to put same timestamp in both syslog and csvlog messages.
2566 if (formatted_log_time[0] == '\0')
2567 setup_formatted_log_time();
2569 appendStringInfoString(&buf, formatted_log_time);
2570 appendStringInfoChar(&buf, ',');
2574 appendCSVLiteral(&buf, MyProcPort->user_name);
2575 appendStringInfoChar(&buf, ',');
2579 appendCSVLiteral(&buf, MyProcPort->database_name);
2580 appendStringInfoChar(&buf, ',');
2584 appendStringInfo(&buf, "%d", MyProcPid);
2585 appendStringInfoChar(&buf, ',');
2587 /* Remote host and port */
2588 if (MyProcPort && MyProcPort->remote_host)
2590 appendStringInfoChar(&buf, '"');
2591 appendStringInfoString(&buf, MyProcPort->remote_host);
2592 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2594 appendStringInfoChar(&buf, ':');
2595 appendStringInfoString(&buf, MyProcPort->remote_port);
2597 appendStringInfoChar(&buf, '"');
2599 appendStringInfoChar(&buf, ',');
2602 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2603 appendStringInfoChar(&buf, ',');
2606 appendStringInfo(&buf, "%ld", log_line_number);
2607 appendStringInfoChar(&buf, ',');
2612 StringInfoData msgbuf;
2616 initStringInfo(&msgbuf);
2618 psdisp = get_ps_display(&displen);
2619 appendBinaryStringInfo(&msgbuf, psdisp, displen);
2620 appendCSVLiteral(&buf, msgbuf.data);
2624 appendStringInfoChar(&buf, ',');
2626 /* session start timestamp */
2627 if (formatted_start_time[0] == '\0')
2628 setup_formatted_start_time();
2629 appendStringInfoString(&buf, formatted_start_time);
2630 appendStringInfoChar(&buf, ',');
2632 /* Virtual transaction id */
2633 /* keep VXID format in sync with lockfuncs.c */
2634 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2635 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2636 appendStringInfoChar(&buf, ',');
2638 /* Transaction id */
2639 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2640 appendStringInfoChar(&buf, ',');
2642 /* Error severity */
2643 appendStringInfoString(&buf, error_severity(edata->elevel));
2644 appendStringInfoChar(&buf, ',');
2646 /* SQL state code */
2647 appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2648 appendStringInfoChar(&buf, ',');
2651 appendCSVLiteral(&buf, edata->message);
2652 appendStringInfoChar(&buf, ',');
2654 /* errdetail or errdetail_log */
2655 if (edata->detail_log)
2656 appendCSVLiteral(&buf, edata->detail_log);
2658 appendCSVLiteral(&buf, edata->detail);
2659 appendStringInfoChar(&buf, ',');
2662 appendCSVLiteral(&buf, edata->hint);
2663 appendStringInfoChar(&buf, ',');
2665 /* internal query */
2666 appendCSVLiteral(&buf, edata->internalquery);
2667 appendStringInfoChar(&buf, ',');
2669 /* if printed internal query, print internal pos too */
2670 if (edata->internalpos > 0 && edata->internalquery != NULL)
2671 appendStringInfo(&buf, "%d", edata->internalpos);
2672 appendStringInfoChar(&buf, ',');
2675 appendCSVLiteral(&buf, edata->context);
2676 appendStringInfoChar(&buf, ',');
2678 /* user query --- only reported if not disabled by the caller */
2679 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2680 debug_query_string != NULL &&
2684 appendCSVLiteral(&buf, debug_query_string);
2685 appendStringInfoChar(&buf, ',');
2686 if (print_stmt && edata->cursorpos > 0)
2687 appendStringInfo(&buf, "%d", edata->cursorpos);
2688 appendStringInfoChar(&buf, ',');
2690 /* file error location */
2691 if (Log_error_verbosity >= PGERROR_VERBOSE)
2693 StringInfoData msgbuf;
2695 initStringInfo(&msgbuf);
2697 if (edata->funcname && edata->filename)
2698 appendStringInfo(&msgbuf, "%s, %s:%d",
2699 edata->funcname, edata->filename,
2701 else if (edata->filename)
2702 appendStringInfo(&msgbuf, "%s:%d",
2703 edata->filename, edata->lineno);
2704 appendCSVLiteral(&buf, msgbuf.data);
2707 appendStringInfoChar(&buf, ',');
2709 /* application name */
2710 if (application_name)
2711 appendCSVLiteral(&buf, application_name);
2713 appendStringInfoChar(&buf, '\n');
2715 /* If in the syslogger process, try to write messages direct to file */
2717 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2719 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2725 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2729 unpack_sql_state(int sql_state)
2731 static char buf[12];
2734 for (i = 0; i < 5; i++)
2736 buf[i] = PGUNSIXBIT(sql_state);
2746 * Write error report to server's log
2749 send_message_to_server_log(ErrorData *edata)
2753 initStringInfo(&buf);
2755 formatted_log_time[0] = '\0';
2757 log_line_prefix(&buf, edata);
2758 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2760 if (Log_error_verbosity >= PGERROR_VERBOSE)
2761 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2764 append_with_tabs(&buf, edata->message);
2766 append_with_tabs(&buf, _("missing error text"));
2768 if (edata->cursorpos > 0)
2769 appendStringInfo(&buf, _(" at character %d"),
2771 else if (edata->internalpos > 0)
2772 appendStringInfo(&buf, _(" at character %d"),
2773 edata->internalpos);
2775 appendStringInfoChar(&buf, '\n');
2777 if (Log_error_verbosity >= PGERROR_DEFAULT)
2779 if (edata->detail_log)
2781 log_line_prefix(&buf, edata);
2782 appendStringInfoString(&buf, _("DETAIL: "));
2783 append_with_tabs(&buf, edata->detail_log);
2784 appendStringInfoChar(&buf, '\n');
2786 else if (edata->detail)
2788 log_line_prefix(&buf, edata);
2789 appendStringInfoString(&buf, _("DETAIL: "));
2790 append_with_tabs(&buf, edata->detail);
2791 appendStringInfoChar(&buf, '\n');
2795 log_line_prefix(&buf, edata);
2796 appendStringInfoString(&buf, _("HINT: "));
2797 append_with_tabs(&buf, edata->hint);
2798 appendStringInfoChar(&buf, '\n');
2800 if (edata->internalquery)
2802 log_line_prefix(&buf, edata);
2803 appendStringInfoString(&buf, _("QUERY: "));
2804 append_with_tabs(&buf, edata->internalquery);
2805 appendStringInfoChar(&buf, '\n');
2809 log_line_prefix(&buf, edata);
2810 appendStringInfoString(&buf, _("CONTEXT: "));
2811 append_with_tabs(&buf, edata->context);
2812 appendStringInfoChar(&buf, '\n');
2814 if (Log_error_verbosity >= PGERROR_VERBOSE)
2816 /* assume no newlines in funcname or filename... */
2817 if (edata->funcname && edata->filename)
2819 log_line_prefix(&buf, edata);
2820 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2821 edata->funcname, edata->filename,
2824 else if (edata->filename)
2826 log_line_prefix(&buf, edata);
2827 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2828 edata->filename, edata->lineno);
2834 * If the user wants the query that generated this error logged, do it.
2836 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2837 debug_query_string != NULL &&
2840 log_line_prefix(&buf, edata);
2841 appendStringInfoString(&buf, _("STATEMENT: "));
2842 append_with_tabs(&buf, debug_query_string);
2843 appendStringInfoChar(&buf, '\n');
2847 /* Write to syslog, if enabled */
2848 if (Log_destination & LOG_DESTINATION_SYSLOG)
2852 switch (edata->elevel)
2859 syslog_level = LOG_DEBUG;
2864 syslog_level = LOG_INFO;
2868 syslog_level = LOG_NOTICE;
2871 syslog_level = LOG_WARNING;
2874 syslog_level = LOG_ERR;
2878 syslog_level = LOG_CRIT;
2882 write_syslog(syslog_level, buf.data);
2884 #endif /* HAVE_SYSLOG */
2887 /* Write to eventlog, if enabled */
2888 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2890 write_eventlog(edata->elevel, buf.data, buf.len);
2894 /* Write to stderr, if enabled */
2895 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2898 * Use the chunking protocol if we know the syslogger should be
2899 * catching stderr output, and we are not ourselves the syslogger.
2900 * Otherwise, just do a vanilla write to stderr.
2902 if (redirection_done && !am_syslogger)
2903 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2907 * In a win32 service environment, there is no usable stderr. Capture
2908 * anything going there and write it to the eventlog instead.
2910 * If stderr redirection is active, it was OK to write to stderr above
2911 * because that's really a pipe to the syslogger process.
2913 else if (pgwin32_is_service())
2914 write_eventlog(edata->elevel, buf.data, buf.len);
2917 write_console(buf.data, buf.len);
2920 /* If in the syslogger process, try to write messages direct to file */
2922 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2924 /* Write to CSV log if enabled */
2925 if (Log_destination & LOG_DESTINATION_CSVLOG)
2927 if (redirection_done || am_syslogger)
2930 * send CSV data if it's safe to do so (syslogger doesn't need the
2931 * pipe). First get back the space in the message buffer.
2934 write_csvlog(edata);
2939 * syslogger not up (yet), so just dump the message to stderr,
2940 * unless we already did so above.
2942 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2943 whereToSendOutput != DestDebug)
2944 write_console(buf.data, buf.len);
2955 * Send data to the syslogger using the chunked protocol
2957 * Note: when there are multiple backends writing into the syslogger pipe,
2958 * it's critical that each write go into the pipe indivisibly, and not
2959 * get interleaved with data from other processes. Fortunately, the POSIX
2960 * spec requires that writes to pipes be atomic so long as they are not
2961 * more than PIPE_BUF bytes long. So we divide long messages into chunks
2962 * that are no more than that length, and send one chunk per write() call.
2963 * The collector process knows how to reassemble the chunks.
2965 * Because of the atomic write requirement, there are only two possible
2966 * results from write() here: -1 for failure, or the requested number of
2967 * bytes. There is not really anything we can do about a failure; retry would
2968 * probably be an infinite loop, and we can't even report the error usefully.
2969 * (There is noplace else we could send it!) So we might as well just ignore
2970 * the result from write(). However, on some platforms you get a compiler
2971 * warning from ignoring write()'s result, so do a little dance with casting
2972 * rc to void to shut up the compiler.
2975 write_pipe_chunks(char *data, int len, int dest)
2978 int fd = fileno(stderr);
2983 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2984 p.proto.pid = MyProcPid;
2986 /* write all but the last chunk */
2987 while (len > PIPE_MAX_PAYLOAD)
2989 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2990 p.proto.len = PIPE_MAX_PAYLOAD;
2991 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2992 rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2994 data += PIPE_MAX_PAYLOAD;
2995 len -= PIPE_MAX_PAYLOAD;
2998 /* write the last chunk */
2999 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
3001 memcpy(p.proto.data, data, len);
3002 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3008 * Append a text string to the error report being built for the client.
3010 * This is ordinarily identical to pq_sendstring(), but if we are in
3011 * error recursion trouble we skip encoding conversion, because of the
3012 * possibility that the problem is a failure in the encoding conversion
3013 * subsystem itself. Code elsewhere should ensure that the passed-in
3014 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3015 * in such cases. (In particular, we disable localization of error messages
3016 * to help ensure that's true.)
3019 err_sendstring(StringInfo buf, const char *str)
3021 if (in_error_recursion_trouble())
3022 pq_send_ascii_string(buf, str);
3024 pq_sendstring(buf, str);
3028 * Write error report to client
3031 send_message_to_frontend(ErrorData *edata)
3033 StringInfoData msgbuf;
3035 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3036 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
3038 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
3040 /* New style with separate fields */
3045 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3046 err_sendstring(&msgbuf, error_severity(edata->elevel));
3048 /* unpack MAKE_SQLSTATE code */
3049 ssval = edata->sqlerrcode;
3050 for (i = 0; i < 5; i++)
3052 tbuf[i] = PGUNSIXBIT(ssval);
3057 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3058 err_sendstring(&msgbuf, tbuf);
3060 /* M field is required per protocol, so always send something */
3061 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
3063 err_sendstring(&msgbuf, edata->message);
3065 err_sendstring(&msgbuf, _("missing error text"));
3069 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
3070 err_sendstring(&msgbuf, edata->detail);
3073 /* detail_log is intentionally not used here */
3077 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
3078 err_sendstring(&msgbuf, edata->hint);
3083 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3084 err_sendstring(&msgbuf, edata->context);
3087 if (edata->schema_name)
3089 pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3090 err_sendstring(&msgbuf, edata->schema_name);
3093 if (edata->table_name)
3095 pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3096 err_sendstring(&msgbuf, edata->table_name);
3099 if (edata->column_name)
3101 pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3102 err_sendstring(&msgbuf, edata->column_name);
3105 if (edata->datatype_name)
3107 pq_sendbyte(&msgbuf, PG_DIAG_DATATYPE_NAME);
3108 err_sendstring(&msgbuf, edata->datatype_name);
3111 if (edata->constraint_name)
3113 pq_sendbyte(&msgbuf, PG_DIAG_CONSTRAINT_NAME);
3114 err_sendstring(&msgbuf, edata->constraint_name);
3117 if (edata->cursorpos > 0)
3119 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3120 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
3121 err_sendstring(&msgbuf, tbuf);
3124 if (edata->internalpos > 0)
3126 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3127 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
3128 err_sendstring(&msgbuf, tbuf);
3131 if (edata->internalquery)
3133 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
3134 err_sendstring(&msgbuf, edata->internalquery);
3137 if (edata->filename)
3139 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3140 err_sendstring(&msgbuf, edata->filename);
3143 if (edata->lineno > 0)
3145 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3146 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3147 err_sendstring(&msgbuf, tbuf);
3150 if (edata->funcname)
3152 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
3153 err_sendstring(&msgbuf, edata->funcname);
3156 pq_sendbyte(&msgbuf, '\0'); /* terminator */
3160 /* Old style --- gin up a backwards-compatible message */
3163 initStringInfo(&buf);
3165 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
3167 if (edata->show_funcname && edata->funcname)
3168 appendStringInfo(&buf, "%s: ", edata->funcname);
3171 appendStringInfoString(&buf, edata->message);
3173 appendStringInfoString(&buf, _("missing error text"));
3175 if (edata->cursorpos > 0)
3176 appendStringInfo(&buf, _(" at character %d"),
3178 else if (edata->internalpos > 0)
3179 appendStringInfo(&buf, _(" at character %d"),
3180 edata->internalpos);
3182 appendStringInfoChar(&buf, '\n');
3184 err_sendstring(&msgbuf, buf.data);
3189 pq_endmessage(&msgbuf);
3192 * This flush is normally not necessary, since postgres.c will flush out
3193 * waiting data when control returns to the main loop. But it seems best
3194 * to leave it here, so that the client has some clue what happened if the
3195 * backend dies before getting back to the main loop ... error/notice
3196 * messages should not be a performance-critical path anyway, so an extra
3197 * flush won't hurt much ...
3204 * Support routines for formatting error messages.
3209 * expand_fmt_string --- process special format codes in a format string
3211 * We must replace %m with the appropriate strerror string, since vsnprintf
3212 * won't know what to do with it.
3214 * The result is a palloc'd string.
3217 expand_fmt_string(const char *fmt, ErrorData *edata)
3222 initStringInfo(&buf);
3224 for (cp = fmt; *cp; cp++)
3226 if (cp[0] == '%' && cp[1] != '\0')
3232 * Replace %m by system error string. If there are any %'s in
3233 * the string, we'd better double them so that vsnprintf won't
3238 cp2 = useful_strerror(edata->saved_errno);
3242 appendStringInfoCharMacro(&buf, '%');
3243 appendStringInfoCharMacro(&buf, *cp2);
3248 /* copy % and next char --- this avoids trouble with %%m */
3249 appendStringInfoCharMacro(&buf, '%');
3250 appendStringInfoCharMacro(&buf, *cp);
3254 appendStringInfoCharMacro(&buf, *cp);
3262 * A slightly cleaned-up version of strerror()
3265 useful_strerror(int errnum)
3267 /* this buffer is only used if strerror() and get_errno_symbol() fail */
3268 static char errorstr_buf[48];
3272 /* Winsock error code range, per WinError.h */
3273 if (errnum >= 10000 && errnum <= 11999)
3274 return pgwin32_socket_strerror(errnum);
3276 str = strerror(errnum);
3279 * Some strerror()s return an empty string for out-of-range errno. This
3280 * is ANSI C spec compliant, but not exactly useful. Also, we may get
3281 * back strings of question marks if libc cannot transcode the message to
3282 * the codeset specified by LC_CTYPE. If we get nothing useful, first try
3283 * get_errno_symbol(), and if that fails, print the numeric errno.
3285 if (str == NULL || *str == '\0' || *str == '?')
3286 str = get_errno_symbol(errnum);
3290 snprintf(errorstr_buf, sizeof(errorstr_buf),
3292 translator: This string will be truncated at 47
3293 characters expanded. */
3294 _("operating system error %d"), errnum);
3302 * Returns a symbol (e.g. "ENOENT") for an errno code.
3303 * Returns NULL if the code is unrecognized.
3306 get_errno_symbol(int errnum)
3316 return "EADDRINUSE";
3318 #ifdef EADDRNOTAVAIL
3320 return "EADDRNOTAVAIL";
3323 return "EAFNOSUPPORT";
3344 return "ECONNABORTED";
3347 return "ECONNREFUSED";
3350 return "ECONNRESET";
3364 return "EHOSTUNREACH";
3369 return "EINPROGRESS";
3393 return "ENAMETOOLONG";
3416 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
3432 #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP))
3434 return "EOPNOTSUPP";
3444 case EPROTONOSUPPORT:
3445 return "EPROTONOSUPPORT";
3462 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
3464 return "EWOULDBLOCK";
3475 * error_severity --- get localized string representing elevel
3478 error_severity(int elevel)
3489 prefix = _("DEBUG");
3499 prefix = _("NOTICE");
3502 prefix = _("WARNING");
3505 prefix = _("ERROR");
3508 prefix = _("FATAL");
3511 prefix = _("PANIC");
3525 * Append the string to the StringInfo buffer, inserting a tab after any
3529 append_with_tabs(StringInfo buf, const char *str)
3533 while ((ch = *str++) != '\0')
3535 appendStringInfoCharMacro(buf, ch);
3537 appendStringInfoCharMacro(buf, '\t');
3543 * Write errors to stderr (or by equal means when stderr is
3544 * not available). Used before ereport/elog can be used
3545 * safely (memory context, GUC load etc)
3548 write_stderr(const char *fmt,...)
3553 char errbuf[2048]; /* Arbitrary size? */
3560 /* On Unix, we just fprintf to stderr */
3561 vfprintf(stderr, fmt, ap);
3564 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3567 * On Win32, we print to stderr if running on a console, or write to
3568 * eventlog if running as a service
3570 if (pgwin32_is_service()) /* Running as a service */
3572 write_eventlog(ERROR, errbuf, strlen(errbuf));
3576 /* Not running as service, write to stderr */
3577 write_console(errbuf, strlen(errbuf));
3586 * is_log_level_output -- is elevel logically >= log_min_level?
3588 * We use this for tests that should consider LOG to sort out-of-order,
3589 * between ERROR and FATAL. Generally this is the right thing for testing
3590 * whether a message should go to the postmaster log, whereas a simple >=
3591 * test is correct for testing whether the message should go to the client.
3594 is_log_level_output(int elevel, int log_min_level)
3596 if (elevel == LOG || elevel == COMMERROR)
3598 if (log_min_level == LOG || log_min_level <= ERROR)
3601 else if (log_min_level == LOG)
3604 if (elevel >= FATAL)
3607 /* Neither is LOG */
3608 else if (elevel >= log_min_level)
3615 * Adjust the level of a recovery-related message per trace_recovery_messages.
3617 * The argument is the default log level of the message, eg, DEBUG2. (This
3618 * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3619 * If the level is >= trace_recovery_messages, we return LOG, causing the
3620 * message to be logged unconditionally (for most settings of
3621 * log_min_messages). Otherwise, we return the argument unchanged.
3622 * The message will then be shown based on the setting of log_min_messages.
3624 * Intention is to keep this for at least the whole of the 9.0 production
3625 * release, so we can more easily diagnose production problems in the field.
3626 * It should go away eventually, though, because it's an ugly and
3627 * hard-to-explain kluge.
3630 trace_recovery(int trace_level)
3632 if (trace_level < LOG &&
3633 trace_level >= trace_recovery_messages)