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-2013, 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 * Okay, crank up a stack entry to store the info in.
317 if (recursion_depth++ > 0 && elevel >= ERROR)
320 * Ooops, error during error processing. Clear ErrorContext as
321 * discussed at top of file. We will not return to the original
322 * error's reporter or handler, so we don't need it.
324 MemoryContextReset(ErrorContext);
327 * Infinite error recursion might be due to something broken in a
328 * context traceback routine. Abandon them too. We also abandon
329 * attempting to print the error statement (which, if long, could
330 * itself be the source of the recursive failure).
332 if (in_error_recursion_trouble())
334 error_context_stack = NULL;
335 debug_query_string = NULL;
338 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
341 * Wups, stack not big enough. We treat this as a PANIC condition
342 * because it suggests an infinite loop of errors during error
345 errordata_stack_depth = -1; /* make room on stack */
346 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
349 /* Initialize data for this error frame */
350 edata = &errordata[errordata_stack_depth];
351 MemSet(edata, 0, sizeof(ErrorData));
352 edata->elevel = elevel;
353 edata->output_to_server = output_to_server;
354 edata->output_to_client = output_to_client;
359 /* keep only base name, useful especially for vpath builds */
360 slash = strrchr(filename, '/');
362 filename = slash + 1;
364 edata->filename = filename;
365 edata->lineno = lineno;
366 edata->funcname = funcname;
367 /* the default text domain is the backend's */
368 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
369 /* Select default errcode based on elevel */
371 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
372 else if (elevel == WARNING)
373 edata->sqlerrcode = ERRCODE_WARNING;
375 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
376 /* errno is saved here so that error parameter eval can't change it */
377 edata->saved_errno = errno;
380 * Any allocations for this error state level should go into ErrorContext
382 edata->assoc_context = ErrorContext;
389 * errfinish --- end an error-reporting cycle
391 * Produce the appropriate error report(s) and pop the error stack.
393 * If elevel is ERROR or worse, control does not return to the caller.
394 * See elog.h for the error level definitions.
397 errfinish(int dummy,...)
399 ErrorData *edata = &errordata[errordata_stack_depth];
401 MemoryContext oldcontext;
402 ErrorContextCallback *econtext;
406 elevel = edata->elevel;
409 * Do processing in ErrorContext, which we hope has enough reserved space
410 * to report an error.
412 oldcontext = MemoryContextSwitchTo(ErrorContext);
415 * Call any context callback functions. Errors occurring in callback
416 * functions will be treated as recursive errors --- this ensures we will
417 * avoid infinite recursion (see errstart).
419 for (econtext = error_context_stack;
421 econtext = econtext->previous)
422 (*econtext->callback) (econtext->arg);
425 * If ERROR (not more nor less) we pass it off to the current handler.
426 * Printing it and popping the stack is the responsibility of the handler.
431 * We do some minimal cleanup before longjmp'ing so that handlers can
432 * execute in a reasonably sane state.
435 /* This is just in case the error came while waiting for input */
436 ImmediateInterruptOK = false;
439 * Reset InterruptHoldoffCount in case we ereport'd from inside an
440 * interrupt holdoff section. (We assume here that no handler will
441 * itself be inside a holdoff section. If necessary, such a handler
442 * could save and restore InterruptHoldoffCount for itself, but this
443 * should make life easier for most.)
445 InterruptHoldoffCount = 0;
447 CritSectionCount = 0; /* should be unnecessary, but... */
450 * Note that we leave CurrentMemoryContext set to ErrorContext. The
451 * handler should reset it to something else soon.
459 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
460 * progress, so that we can report the message before dying. (Without
461 * this, pq_putmessage will refuse to send the message at all, which is
462 * what we want for NOTICE messages, but not for fatal exits.) This hack
463 * is necessary because of poor design of old-style copy protocol. Note
464 * we must do this even if client is fool enough to have set
465 * client_min_messages above FATAL, so don't look at output_to_client.
467 if (elevel >= FATAL && whereToSendOutput == DestRemote)
470 /* Emit the message to the right places */
473 /* Now free up subsidiary data attached to stack entry, and release it */
475 pfree(edata->message);
477 pfree(edata->detail);
478 if (edata->detail_log)
479 pfree(edata->detail_log);
483 pfree(edata->context);
484 if (edata->schema_name)
485 pfree(edata->schema_name);
486 if (edata->table_name)
487 pfree(edata->table_name);
488 if (edata->column_name)
489 pfree(edata->column_name);
490 if (edata->datatype_name)
491 pfree(edata->datatype_name);
492 if (edata->constraint_name)
493 pfree(edata->constraint_name);
494 if (edata->internalquery)
495 pfree(edata->internalquery);
497 errordata_stack_depth--;
499 /* Exit error-handling context */
500 MemoryContextSwitchTo(oldcontext);
504 * Perform error recovery action as specified by elevel.
509 * For a FATAL error, we let proc_exit clean up and exit.
511 ImmediateInterruptOK = false;
514 * If we just reported a startup failure, the client will disconnect
515 * on receiving it, so don't send any more to the client.
517 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
518 whereToSendOutput = DestNone;
521 * fflush here is just to improve the odds that we get to see the
522 * error message, in case things are so hosed that proc_exit crashes.
523 * Any other code you might be tempted to add here should probably be
524 * in an on_proc_exit or on_shmem_exit callback instead.
530 * Do normal process-exit cleanup, then return exit code 1 to indicate
531 * FATAL termination. The postmaster may or may not consider this
532 * worthy of panic, depending on which subprocess returns it.
540 * Serious crash time. Postmaster will observe SIGABRT process exit
541 * status and kill the other backends too.
543 * XXX: what if we are *in* the postmaster? abort() won't kill our
546 ImmediateInterruptOK = false;
553 * We reach here if elevel <= WARNING. OK to return to caller.
555 * But check for cancel/die interrupt first --- this is so that the user
556 * can stop a query emitting tons of notice or warning messages, even if
557 * it's in a loop that otherwise fails to check for interrupts.
559 CHECK_FOR_INTERRUPTS();
564 * errcode --- add SQLSTATE error code to the current error
566 * The code is expected to be represented as per MAKE_SQLSTATE().
569 errcode(int sqlerrcode)
571 ErrorData *edata = &errordata[errordata_stack_depth];
573 /* we don't bother incrementing recursion_depth */
576 edata->sqlerrcode = sqlerrcode;
578 return 0; /* return value does not matter */
583 * errcode_for_file_access --- add SQLSTATE error code to the current error
585 * The SQLSTATE code is chosen based on the saved errno value. We assume
586 * that the failing operation was some type of disk file access.
588 * NOTE: the primary error message string should generally include %m
592 errcode_for_file_access(void)
594 ErrorData *edata = &errordata[errordata_stack_depth];
596 /* we don't bother incrementing recursion_depth */
599 switch (edata->saved_errno)
601 /* Permission-denied failures */
602 case EPERM: /* Not super-user */
603 case EACCES: /* Permission denied */
605 case EROFS: /* Read only file system */
607 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
611 case ENOENT: /* No such file or directory */
612 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
616 case EEXIST: /* File exists */
617 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
620 /* Wrong object type or state */
621 case ENOTDIR: /* Not a directory */
622 case EISDIR: /* Is a directory */
623 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
624 case ENOTEMPTY: /* Directory not empty */
626 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
629 /* Insufficient resources */
630 case ENOSPC: /* No space left on device */
631 edata->sqlerrcode = ERRCODE_DISK_FULL;
634 case ENFILE: /* File table overflow */
635 case EMFILE: /* Too many open files */
636 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
639 /* Hardware failure */
640 case EIO: /* I/O error */
641 edata->sqlerrcode = ERRCODE_IO_ERROR;
644 /* All else is classified as internal errors */
646 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
650 return 0; /* return value does not matter */
654 * errcode_for_socket_access --- add SQLSTATE error code to the current error
656 * The SQLSTATE code is chosen based on the saved errno value. We assume
657 * that the failing operation was some type of socket access.
659 * NOTE: the primary error message string should generally include %m
663 errcode_for_socket_access(void)
665 ErrorData *edata = &errordata[errordata_stack_depth];
667 /* we don't bother incrementing recursion_depth */
670 switch (edata->saved_errno)
672 /* Loss of connection */
677 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
680 /* All else is classified as internal errors */
682 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
686 return 0; /* return value does not matter */
691 * This macro handles expansion of a format string and associated parameters;
692 * it's common code for errmsg(), errdetail(), etc. Must be called inside
693 * a routine that is declared like "const char *fmt, ..." and has an edata
694 * pointer set up. The message is assigned to edata->targetfield, or
695 * appended to it if appendval is true. The message is subject to translation
696 * if translateit is true.
698 * Note: we pstrdup the buffer rather than just transferring its storage
699 * to the edata field because the buffer might be considerably larger than
702 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit) \
705 StringInfoData buf; \
706 /* Internationalize the error format string */ \
707 if (translateit && !in_error_recursion_trouble()) \
708 fmt = dgettext((domain), fmt); \
709 /* Expand %m in format string */ \
710 fmtbuf = expand_fmt_string(fmt, edata); \
711 initStringInfo(&buf); \
712 if ((appendval) && edata->targetfield) { \
713 appendStringInfoString(&buf, edata->targetfield); \
714 appendStringInfoChar(&buf, '\n'); \
716 /* Generate actual output --- have to use appendStringInfoVA */ \
721 va_start(args, fmt); \
722 needed = appendStringInfoVA(&buf, fmtbuf, args); \
726 enlargeStringInfo(&buf, needed); \
728 /* Done with expanded fmt */ \
730 /* Save the completed message into the stack item */ \
731 if (edata->targetfield) \
732 pfree(edata->targetfield); \
733 edata->targetfield = pstrdup(buf.data); \
738 * Same as above, except for pluralized error messages. The calling routine
739 * must be declared like "const char *fmt_singular, const char *fmt_plural,
740 * unsigned long n, ...". Translation is assumed always wanted.
742 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval) \
746 StringInfoData buf; \
747 /* Internationalize the error format string */ \
748 if (!in_error_recursion_trouble()) \
749 fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
751 fmt = (n == 1 ? fmt_singular : fmt_plural); \
752 /* Expand %m in format string */ \
753 fmtbuf = expand_fmt_string(fmt, edata); \
754 initStringInfo(&buf); \
755 if ((appendval) && edata->targetfield) { \
756 appendStringInfoString(&buf, edata->targetfield); \
757 appendStringInfoChar(&buf, '\n'); \
759 /* Generate actual output --- have to use appendStringInfoVA */ \
765 needed = appendStringInfoVA(&buf, fmtbuf, args); \
769 enlargeStringInfo(&buf, needed); \
771 /* Done with expanded fmt */ \
773 /* Save the completed message into the stack item */ \
774 if (edata->targetfield) \
775 pfree(edata->targetfield); \
776 edata->targetfield = pstrdup(buf.data); \
782 * errmsg --- add a primary error message text to the current error
784 * In addition to the usual %-escapes recognized by printf, "%m" in
785 * fmt is replaced by the error message for the caller's value of errno.
787 * Note: no newline is needed at the end of the fmt string, since
788 * ereport will provide one for the output methods that need it.
791 errmsg(const char *fmt,...)
793 ErrorData *edata = &errordata[errordata_stack_depth];
794 MemoryContext oldcontext;
798 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
800 EVALUATE_MESSAGE(edata->domain, message, false, true);
802 MemoryContextSwitchTo(oldcontext);
804 return 0; /* return value does not matter */
809 * errmsg_internal --- add a primary error message text to the current error
811 * This is exactly like errmsg() except that strings passed to errmsg_internal
812 * are not translated, and are customarily left out of the
813 * internationalization message dictionary. This should be used for "can't
814 * happen" cases that are probably not worth spending translation effort on.
815 * We also use this for certain cases where we *must* not try to translate
816 * the message because the translation would fail and result in infinite
820 errmsg_internal(const char *fmt,...)
822 ErrorData *edata = &errordata[errordata_stack_depth];
823 MemoryContext oldcontext;
827 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
829 EVALUATE_MESSAGE(edata->domain, message, false, false);
831 MemoryContextSwitchTo(oldcontext);
833 return 0; /* return value does not matter */
838 * errmsg_plural --- add a primary error message text to the current error,
839 * with support for pluralization of the message text
842 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
845 ErrorData *edata = &errordata[errordata_stack_depth];
846 MemoryContext oldcontext;
850 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
852 EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
854 MemoryContextSwitchTo(oldcontext);
856 return 0; /* return value does not matter */
861 * errdetail --- add a detail error message text to the current error
864 errdetail(const char *fmt,...)
866 ErrorData *edata = &errordata[errordata_stack_depth];
867 MemoryContext oldcontext;
871 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
873 EVALUATE_MESSAGE(edata->domain, detail, false, true);
875 MemoryContextSwitchTo(oldcontext);
877 return 0; /* return value does not matter */
882 * errdetail_internal --- add a detail error message text to the current error
884 * This is exactly like errdetail() except that strings passed to
885 * errdetail_internal are not translated, and are customarily left out of the
886 * internationalization message dictionary. This should be used for detail
887 * messages that seem not worth translating for one reason or another
888 * (typically, that they don't seem to be useful to average users).
891 errdetail_internal(const char *fmt,...)
893 ErrorData *edata = &errordata[errordata_stack_depth];
894 MemoryContext oldcontext;
898 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
900 EVALUATE_MESSAGE(edata->domain, detail, false, false);
902 MemoryContextSwitchTo(oldcontext);
904 return 0; /* return value does not matter */
909 * errdetail_log --- add a detail_log error message text to the current error
912 errdetail_log(const char *fmt,...)
914 ErrorData *edata = &errordata[errordata_stack_depth];
915 MemoryContext oldcontext;
919 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
921 EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
923 MemoryContextSwitchTo(oldcontext);
925 return 0; /* return value does not matter */
930 * errdetail_plural --- add a detail error message text to the current error,
931 * with support for pluralization of the message text
934 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
937 ErrorData *edata = &errordata[errordata_stack_depth];
938 MemoryContext oldcontext;
942 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
944 EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
946 MemoryContextSwitchTo(oldcontext);
948 return 0; /* return value does not matter */
953 * errhint --- add a hint error message text to the current error
956 errhint(const char *fmt,...)
958 ErrorData *edata = &errordata[errordata_stack_depth];
959 MemoryContext oldcontext;
963 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
965 EVALUATE_MESSAGE(edata->domain, hint, false, true);
967 MemoryContextSwitchTo(oldcontext);
969 return 0; /* return value does not matter */
974 * errcontext_msg --- add a context error message text to the current error
976 * Unlike other cases, multiple calls are allowed to build up a stack of
977 * context information. We assume earlier calls represent more-closely-nested
981 errcontext_msg(const char *fmt,...)
983 ErrorData *edata = &errordata[errordata_stack_depth];
984 MemoryContext oldcontext;
988 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
990 EVALUATE_MESSAGE(edata->context_domain, context, true, true);
992 MemoryContextSwitchTo(oldcontext);
994 return 0; /* return value does not matter */
998 * set_errcontext_domain --- set message domain to be used by errcontext()
1000 * errcontext_msg() can be called from a different module than the original
1001 * ereport(), so we cannot use the message domain passed in errstart() to
1002 * translate it. Instead, each errcontext_msg() call should be preceded by
1003 * a set_errcontext_domain() call to specify the domain. This is usually
1004 * done transparently by the errcontext() macro.
1007 set_errcontext_domain(const char *domain)
1009 ErrorData *edata = &errordata[errordata_stack_depth];
1011 /* we don't bother incrementing recursion_depth */
1012 CHECK_STACK_DEPTH();
1014 edata->context_domain = domain;
1016 return 0; /* return value does not matter */
1021 * errhidestmt --- optionally suppress STATEMENT: field of log entry
1023 * This should be called if the message text already includes the statement.
1026 errhidestmt(bool hide_stmt)
1028 ErrorData *edata = &errordata[errordata_stack_depth];
1030 /* we don't bother incrementing recursion_depth */
1031 CHECK_STACK_DEPTH();
1033 edata->hide_stmt = hide_stmt;
1035 return 0; /* return value does not matter */
1040 * errfunction --- add reporting function name to the current error
1042 * This is used when backwards compatibility demands that the function
1043 * name appear in messages sent to old-protocol clients. Note that the
1044 * passed string is expected to be a non-freeable constant string.
1047 errfunction(const char *funcname)
1049 ErrorData *edata = &errordata[errordata_stack_depth];
1051 /* we don't bother incrementing recursion_depth */
1052 CHECK_STACK_DEPTH();
1054 edata->funcname = funcname;
1055 edata->show_funcname = true;
1057 return 0; /* return value does not matter */
1061 * errposition --- add cursor position to the current error
1064 errposition(int cursorpos)
1066 ErrorData *edata = &errordata[errordata_stack_depth];
1068 /* we don't bother incrementing recursion_depth */
1069 CHECK_STACK_DEPTH();
1071 edata->cursorpos = cursorpos;
1073 return 0; /* return value does not matter */
1077 * internalerrposition --- add internal cursor position to the current error
1080 internalerrposition(int cursorpos)
1082 ErrorData *edata = &errordata[errordata_stack_depth];
1084 /* we don't bother incrementing recursion_depth */
1085 CHECK_STACK_DEPTH();
1087 edata->internalpos = cursorpos;
1089 return 0; /* return value does not matter */
1093 * internalerrquery --- add internal query text to the current error
1095 * Can also pass NULL to drop the internal query text entry. This case
1096 * is intended for use in error callback subroutines that are editorializing
1097 * on the layout of the error report.
1100 internalerrquery(const char *query)
1102 ErrorData *edata = &errordata[errordata_stack_depth];
1104 /* we don't bother incrementing recursion_depth */
1105 CHECK_STACK_DEPTH();
1107 if (edata->internalquery)
1109 pfree(edata->internalquery);
1110 edata->internalquery = NULL;
1114 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1116 return 0; /* return value does not matter */
1120 * err_generic_string -- used to set individual ErrorData string fields
1121 * identified by PG_DIAG_xxx codes.
1123 * This intentionally only supports fields that don't use localized strings,
1124 * so that there are no translation considerations.
1126 * Most potential callers should not use this directly, but instead prefer
1127 * higher-level abstractions, such as errtablecol() (see relcache.c).
1130 err_generic_string(int field, const char *str)
1132 ErrorData *edata = &errordata[errordata_stack_depth];
1134 /* we don't bother incrementing recursion_depth */
1135 CHECK_STACK_DEPTH();
1139 case PG_DIAG_SCHEMA_NAME:
1140 set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1142 case PG_DIAG_TABLE_NAME:
1143 set_errdata_field(edata->assoc_context, &edata->table_name, str);
1145 case PG_DIAG_COLUMN_NAME:
1146 set_errdata_field(edata->assoc_context, &edata->column_name, str);
1148 case PG_DIAG_DATATYPE_NAME:
1149 set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1151 case PG_DIAG_CONSTRAINT_NAME:
1152 set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1155 elog(ERROR, "unsupported ErrorData field id: %d", field);
1159 return 0; /* return value does not matter */
1163 * set_errdata_field --- set an ErrorData string field
1166 set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1168 Assert(*ptr == NULL);
1169 *ptr = MemoryContextStrdup(cxt, str);
1173 * geterrcode --- return the currently set SQLSTATE error code
1175 * This is only intended for use in error callback subroutines, since there
1176 * is no other place outside elog.c where the concept is meaningful.
1181 ErrorData *edata = &errordata[errordata_stack_depth];
1183 /* we don't bother incrementing recursion_depth */
1184 CHECK_STACK_DEPTH();
1186 return edata->sqlerrcode;
1190 * geterrposition --- return the currently set error position (0 if none)
1192 * This is only intended for use in error callback subroutines, since there
1193 * is no other place outside elog.c where the concept is meaningful.
1196 geterrposition(void)
1198 ErrorData *edata = &errordata[errordata_stack_depth];
1200 /* we don't bother incrementing recursion_depth */
1201 CHECK_STACK_DEPTH();
1203 return edata->cursorpos;
1207 * getinternalerrposition --- same for internal error position
1209 * This is only intended for use in error callback subroutines, since there
1210 * is no other place outside elog.c where the concept is meaningful.
1213 getinternalerrposition(void)
1215 ErrorData *edata = &errordata[errordata_stack_depth];
1217 /* we don't bother incrementing recursion_depth */
1218 CHECK_STACK_DEPTH();
1220 return edata->internalpos;
1225 * elog_start --- startup for old-style API
1227 * All that we do here is stash the hidden filename/lineno/funcname
1228 * arguments into a stack entry, along with the current value of errno.
1230 * We need this to be separate from elog_finish because there's no other
1231 * C89-compliant way to deal with inserting extra arguments into the elog
1232 * call. (When using C99's __VA_ARGS__, we could possibly merge this with
1233 * elog_finish, but there doesn't seem to be a good way to save errno before
1234 * evaluating the format arguments if we do that.)
1237 elog_start(const char *filename, int lineno, const char *funcname)
1241 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1244 * Wups, stack not big enough. We treat this as a PANIC condition
1245 * because it suggests an infinite loop of errors during error
1246 * recovery. Note that the message is intentionally not localized,
1247 * else failure to convert it to client encoding could cause further
1250 errordata_stack_depth = -1; /* make room on stack */
1251 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1254 edata = &errordata[errordata_stack_depth];
1259 /* keep only base name, useful especially for vpath builds */
1260 slash = strrchr(filename, '/');
1262 filename = slash + 1;
1264 edata->filename = filename;
1265 edata->lineno = lineno;
1266 edata->funcname = funcname;
1267 /* errno is saved now so that error parameter eval can't change it */
1268 edata->saved_errno = errno;
1270 /* Use ErrorContext for any allocations done at this level. */
1271 edata->assoc_context = ErrorContext;
1275 * elog_finish --- finish up for old-style API
1278 elog_finish(int elevel, const char *fmt,...)
1280 ErrorData *edata = &errordata[errordata_stack_depth];
1281 MemoryContext oldcontext;
1283 CHECK_STACK_DEPTH();
1286 * Do errstart() to see if we actually want to report the message.
1288 errordata_stack_depth--;
1289 errno = edata->saved_errno;
1290 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1291 return; /* nothing to do */
1294 * Format error message just like errmsg_internal().
1297 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1299 EVALUATE_MESSAGE(edata->domain, message, false, false);
1301 MemoryContextSwitchTo(oldcontext);
1305 * And let errfinish() finish up.
1312 * Functions to allow construction of error message strings separately from
1313 * the ereport() call itself.
1315 * The expected calling convention is
1317 * pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1319 * which can be hidden behind a macro such as GUC_check_errdetail(). We
1320 * assume that any functions called in the arguments of format_elog_string()
1321 * cannot result in re-entrant use of these functions --- otherwise the wrong
1322 * text domain might be used, or the wrong errno substituted for %m. This is
1323 * okay for the current usage with GUC check hooks, but might need further
1326 * The result of format_elog_string() is stored in ErrorContext, and will
1327 * therefore survive until FlushErrorState() is called.
1329 static int save_format_errnumber;
1330 static const char *save_format_domain;
1333 pre_format_elog_string(int errnumber, const char *domain)
1335 /* Save errno before evaluation of argument functions can change it */
1336 save_format_errnumber = errnumber;
1337 /* Save caller's text domain */
1338 save_format_domain = domain;
1342 format_elog_string(const char *fmt,...)
1346 MemoryContext oldcontext;
1348 /* Initialize a mostly-dummy error frame */
1350 MemSet(edata, 0, sizeof(ErrorData));
1351 /* the default text domain is the backend's */
1352 edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1353 /* set the errno to be used to interpret %m */
1354 edata->saved_errno = save_format_errnumber;
1356 oldcontext = MemoryContextSwitchTo(ErrorContext);
1358 EVALUATE_MESSAGE(edata->domain, message, false, true);
1360 MemoryContextSwitchTo(oldcontext);
1362 return edata->message;
1367 * Actual output of the top-of-stack error message
1369 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1370 * if the error is caught by somebody). For all other severity levels this
1371 * is called by errfinish.
1374 EmitErrorReport(void)
1376 ErrorData *edata = &errordata[errordata_stack_depth];
1377 MemoryContext oldcontext;
1380 CHECK_STACK_DEPTH();
1381 oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1384 * Call hook before sending message to log. The hook function is allowed
1385 * to turn off edata->output_to_server, so we must recheck that afterward.
1386 * Making any other change in the content of edata is not considered
1389 * Note: the reason why the hook can only turn off output_to_server, and
1390 * not turn it on, is that it'd be unreliable: we will never get here at
1391 * all if errstart() deems the message uninteresting. A hook that could
1392 * make decisions in that direction would have to hook into errstart(),
1393 * where it would have much less information available. emit_log_hook is
1394 * intended for custom log filtering and custom log message transmission
1397 if (edata->output_to_server && emit_log_hook)
1398 (*emit_log_hook) (edata);
1400 /* Send to server log, if enabled */
1401 if (edata->output_to_server)
1402 send_message_to_server_log(edata);
1404 /* Send to client, if enabled */
1405 if (edata->output_to_client)
1406 send_message_to_frontend(edata);
1408 MemoryContextSwitchTo(oldcontext);
1413 * CopyErrorData --- obtain a copy of the topmost error stack entry
1415 * This is only for use in error handler code. The data is copied into the
1416 * current memory context, so callers should always switch away from
1417 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1422 ErrorData *edata = &errordata[errordata_stack_depth];
1423 ErrorData *newedata;
1426 * we don't increment recursion_depth because out-of-memory here does not
1427 * indicate a problem within the error subsystem.
1429 CHECK_STACK_DEPTH();
1431 Assert(CurrentMemoryContext != ErrorContext);
1433 /* Copy the struct itself */
1434 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1435 memcpy(newedata, edata, sizeof(ErrorData));
1437 /* Make copies of separately-allocated fields */
1438 if (newedata->message)
1439 newedata->message = pstrdup(newedata->message);
1440 if (newedata->detail)
1441 newedata->detail = pstrdup(newedata->detail);
1442 if (newedata->detail_log)
1443 newedata->detail_log = pstrdup(newedata->detail_log);
1445 newedata->hint = pstrdup(newedata->hint);
1446 if (newedata->context)
1447 newedata->context = pstrdup(newedata->context);
1448 if (newedata->schema_name)
1449 newedata->schema_name = pstrdup(newedata->schema_name);
1450 if (newedata->table_name)
1451 newedata->table_name = pstrdup(newedata->table_name);
1452 if (newedata->column_name)
1453 newedata->column_name = pstrdup(newedata->column_name);
1454 if (newedata->datatype_name)
1455 newedata->datatype_name = pstrdup(newedata->datatype_name);
1456 if (newedata->constraint_name)
1457 newedata->constraint_name = pstrdup(newedata->constraint_name);
1458 if (newedata->internalquery)
1459 newedata->internalquery = pstrdup(newedata->internalquery);
1461 /* Use the calling context for string allocation */
1462 newedata->assoc_context = CurrentMemoryContext;
1468 * FreeErrorData --- free the structure returned by CopyErrorData.
1470 * Error handlers should use this in preference to assuming they know all
1471 * the separately-allocated fields.
1474 FreeErrorData(ErrorData *edata)
1477 pfree(edata->message);
1479 pfree(edata->detail);
1480 if (edata->detail_log)
1481 pfree(edata->detail_log);
1485 pfree(edata->context);
1486 if (edata->schema_name)
1487 pfree(edata->schema_name);
1488 if (edata->table_name)
1489 pfree(edata->table_name);
1490 if (edata->column_name)
1491 pfree(edata->column_name);
1492 if (edata->datatype_name)
1493 pfree(edata->datatype_name);
1494 if (edata->constraint_name)
1495 pfree(edata->constraint_name);
1496 if (edata->internalquery)
1497 pfree(edata->internalquery);
1502 * FlushErrorState --- flush the error state after error recovery
1504 * This should be called by an error handler after it's done processing
1505 * the error; or as soon as it's done CopyErrorData, if it intends to
1506 * do stuff that is likely to provoke another error. You are not "out" of
1507 * the error subsystem until you have done this.
1510 FlushErrorState(void)
1513 * Reset stack to empty. The only case where it would be more than one
1514 * deep is if we serviced an error that interrupted construction of
1515 * another message. We assume control escaped out of that message
1516 * construction and won't ever go back.
1518 errordata_stack_depth = -1;
1519 recursion_depth = 0;
1520 /* Delete all data in ErrorContext */
1521 MemoryContextResetAndDeleteChildren(ErrorContext);
1525 * ReThrowError --- re-throw a previously copied error
1527 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1528 * subsystem, then do some processing, and finally ReThrowError to re-throw
1529 * the original error. This is slower than just PG_RE_THROW() but should
1530 * be used if the "some processing" is likely to incur another error.
1533 ReThrowError(ErrorData *edata)
1535 ErrorData *newedata;
1537 Assert(edata->elevel == ERROR);
1539 /* Push the data back into the error context */
1541 MemoryContextSwitchTo(ErrorContext);
1543 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1546 * Wups, stack not big enough. We treat this as a PANIC condition
1547 * because it suggests an infinite loop of errors during error
1550 errordata_stack_depth = -1; /* make room on stack */
1551 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1554 newedata = &errordata[errordata_stack_depth];
1555 memcpy(newedata, edata, sizeof(ErrorData));
1557 /* Make copies of separately-allocated fields */
1558 if (newedata->message)
1559 newedata->message = pstrdup(newedata->message);
1560 if (newedata->detail)
1561 newedata->detail = pstrdup(newedata->detail);
1562 if (newedata->detail_log)
1563 newedata->detail_log = pstrdup(newedata->detail_log);
1565 newedata->hint = pstrdup(newedata->hint);
1566 if (newedata->context)
1567 newedata->context = pstrdup(newedata->context);
1568 if (newedata->schema_name)
1569 newedata->schema_name = pstrdup(newedata->schema_name);
1570 if (newedata->table_name)
1571 newedata->table_name = pstrdup(newedata->table_name);
1572 if (newedata->column_name)
1573 newedata->column_name = pstrdup(newedata->column_name);
1574 if (newedata->datatype_name)
1575 newedata->datatype_name = pstrdup(newedata->datatype_name);
1576 if (newedata->constraint_name)
1577 newedata->constraint_name = pstrdup(newedata->constraint_name);
1578 if (newedata->internalquery)
1579 newedata->internalquery = pstrdup(newedata->internalquery);
1581 /* Reset the assoc_context to be ErrorContext */
1582 newedata->assoc_context = ErrorContext;
1589 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1594 /* If possible, throw the error to the next outer setjmp handler */
1595 if (PG_exception_stack != NULL)
1596 siglongjmp(*PG_exception_stack, 1);
1600 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1601 * we have now exited only to discover that there is no outer setjmp
1602 * handler to pass the error to. Had the error been thrown outside
1603 * the block to begin with, we'd have promoted the error to FATAL, so
1604 * the correct behavior is to make it FATAL now; that is, emit it and
1605 * then call proc_exit.
1607 ErrorData *edata = &errordata[errordata_stack_depth];
1609 Assert(errordata_stack_depth >= 0);
1610 Assert(edata->elevel == ERROR);
1611 edata->elevel = FATAL;
1614 * At least in principle, the increase in severity could have changed
1615 * where-to-output decisions, so recalculate. This should stay in
1616 * sync with errstart(), which see for comments.
1618 if (IsPostmasterEnvironment)
1619 edata->output_to_server = is_log_level_output(FATAL,
1622 edata->output_to_server = (FATAL >= log_min_messages);
1623 if (whereToSendOutput == DestRemote)
1625 if (ClientAuthInProgress)
1626 edata->output_to_client = true;
1628 edata->output_to_client = (FATAL >= client_min_messages);
1632 * We can use errfinish() for the rest, but we don't want it to call
1633 * any error context routines a second time. Since we know we are
1634 * about to exit, it should be OK to just clear the context stack.
1636 error_context_stack = NULL;
1641 /* Doesn't return ... */
1642 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1643 __FILE__, __LINE__);
1648 * GetErrorContextStack - Return the context stack, for display/diags
1650 * Returns a pstrdup'd string in the caller's context which includes the PG
1651 * error call stack. It is the caller's responsibility to ensure this string
1652 * is pfree'd (or its context cleaned up) when done.
1654 * This information is collected by traversing the error contexts and calling
1655 * each context's callback function, each of which is expected to call
1656 * errcontext() to return a string which can be presented to the user.
1659 GetErrorContextStack(void)
1662 ErrorContextCallback *econtext;
1665 * Okay, crank up a stack entry to store the info in.
1669 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1672 * Wups, stack not big enough. We treat this as a PANIC condition
1673 * because it suggests an infinite loop of errors during error
1676 errordata_stack_depth = -1; /* make room on stack */
1677 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1681 * Things look good so far, so initialize our error frame
1683 edata = &errordata[errordata_stack_depth];
1684 MemSet(edata, 0, sizeof(ErrorData));
1687 * Set up assoc_context to be the caller's context, so any allocations
1688 * done (which will include edata->context) will use their context.
1690 edata->assoc_context = CurrentMemoryContext;
1693 * Call any context callback functions to collect the context information
1694 * into edata->context.
1696 * Errors occurring in callback functions should go through the regular
1697 * error handling code which should handle any recursive errors, though
1698 * we double-check above, just in case.
1700 for (econtext = error_context_stack;
1702 econtext = econtext->previous)
1703 (*econtext->callback) (econtext->arg);
1706 * Clean ourselves off the stack, any allocations done should have been
1707 * using edata->assoc_context, which we set up earlier to be the caller's
1708 * context, so we're free to just remove our entry off the stack and
1709 * decrement recursion depth and exit.
1711 errordata_stack_depth--;
1715 * Return a pointer to the string the caller asked for, which should have
1716 * been allocated in their context.
1718 return edata->context;
1723 * Initialization of error output file
1731 if (OutputFileName[0])
1734 * A debug-output file name was given.
1736 * Make sure we can write the file, and find out if it's a tty.
1738 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1741 (errcode_for_file_access(),
1742 errmsg("could not open file \"%s\": %m", OutputFileName)));
1747 * Redirect our stderr to the debug output file.
1749 if (!freopen(OutputFileName, "a", stderr))
1751 (errcode_for_file_access(),
1752 errmsg("could not reopen file \"%s\" as stderr: %m",
1756 * If the file is a tty and we're running under the postmaster, try to
1757 * send stdout there as well (if it isn't a tty then stderr will block
1758 * out stdout, so we may as well let stdout go wherever it was going
1761 if (istty && IsUnderPostmaster)
1762 if (!freopen(OutputFileName, "a", stdout))
1764 (errcode_for_file_access(),
1765 errmsg("could not reopen file \"%s\" as stdout: %m",
1774 * Set or update the parameters for syslog logging
1777 set_syslog_parameters(const char *ident, int facility)
1780 * guc.c is likely to call us repeatedly with same parameters, so don't
1781 * thrash the syslog connection unnecessarily. Also, we do not re-open
1782 * the connection until needed, since this routine will get called whether
1783 * or not Log_destination actually mentions syslog.
1785 * Note that we make our own copy of the ident string rather than relying
1786 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1787 * accidentally free a string that syslog is still using.
1789 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1790 syslog_facility != facility)
1795 openlog_done = false;
1799 syslog_ident = strdup(ident);
1800 /* if the strdup fails, we will cope in write_syslog() */
1801 syslog_facility = facility;
1807 * Write a message line to syslog
1810 write_syslog(int level, const char *line)
1812 static unsigned long seq = 0;
1817 /* Open syslog connection if not done yet */
1820 openlog(syslog_ident ? syslog_ident : "postgres",
1821 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1823 openlog_done = true;
1827 * We add a sequence number to each log message to suppress "same"
1833 * Our problem here is that many syslog implementations don't handle long
1834 * messages in an acceptable manner. While this function doesn't help that
1835 * fact, it does work around by splitting up messages into smaller pieces.
1837 * We divide into multiple syslog() calls if message is too long or if the
1838 * message contains embedded newline(s).
1841 nlpos = strchr(line, '\n');
1842 if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1848 char buf[PG_SYSLOG_LIMIT + 1];
1852 /* if we start at a newline, move ahead one char */
1853 if (line[0] == '\n')
1857 /* we need to recompute the next newline's position, too */
1858 nlpos = strchr(line, '\n');
1862 /* copy one line, or as much as will fit, to buf */
1864 buflen = nlpos - line;
1867 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1868 memcpy(buf, line, buflen);
1871 /* trim to multibyte letter boundary */
1872 buflen = pg_mbcliplen(buf, buflen, buflen);
1877 /* already word boundary? */
1878 if (line[buflen] != '\0' &&
1879 !isspace((unsigned char) line[buflen]))
1881 /* try to divide at word boundary */
1883 while (i > 0 && !isspace((unsigned char) buf[i]))
1886 if (i > 0) /* else couldn't divide word boundary */
1895 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1902 /* message short enough */
1903 syslog(level, "[%lu] %s", seq, line);
1906 #endif /* HAVE_SYSLOG */
1910 * Get the PostgreSQL equivalent of the Windows ANSI code page. "ANSI" system
1911 * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
1912 * Every process in a given system will find the same value at all times.
1915 GetACPEncoding(void)
1917 static int encoding = -2;
1920 encoding = pg_codepage_to_encoding(GetACP());
1926 * Write a message line to the windows event log
1929 write_eventlog(int level, const char *line, int len)
1932 int eventlevel = EVENTLOG_ERROR_TYPE;
1933 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1935 if (evtHandle == INVALID_HANDLE_VALUE)
1937 evtHandle = RegisterEventSource(NULL, event_source ? event_source : "PostgreSQL");
1938 if (evtHandle == NULL)
1940 evtHandle = INVALID_HANDLE_VALUE;
1956 eventlevel = EVENTLOG_INFORMATION_TYPE;
1959 eventlevel = EVENTLOG_WARNING_TYPE;
1965 eventlevel = EVENTLOG_ERROR_TYPE;
1970 * If message character encoding matches the encoding expected by
1971 * ReportEventA(), call it to avoid the hazards of conversion. Otherwise,
1972 * try to convert the message to UTF16 and write it with ReportEventW().
1973 * Fall back on ReportEventA() if conversion failed.
1975 * Also verify that we are not on our way into error recursion trouble due
1976 * to error messages thrown deep inside pgwin32_message_to_UTF16().
1978 if (!in_error_recursion_trouble() &&
1979 GetMessageEncoding() != GetACPEncoding())
1981 utf16 = pgwin32_message_to_UTF16(line, len, NULL);
1984 ReportEventW(evtHandle,
1987 0, /* All events are Id 0 */
1993 /* XXX Try ReportEventA() when ReportEventW() fails? */
1999 ReportEventA(evtHandle,
2002 0, /* All events are Id 0 */
2012 write_console(const char *line, int len)
2019 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2020 * Fall back on write() if anything fails.
2022 * In contrast to write_eventlog(), don't skip straight to write() based
2023 * on the applicable encodings. Unlike WriteConsoleW(), write() depends
2024 * on the suitability of the console output code page. Since we put
2025 * stderr into binary mode in SubPostmasterMain(), write() skips the
2026 * necessary translation anyway.
2028 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2029 * to writing unconverted to the logfile in this case.
2031 * Since we palloc the structure required for conversion, also fall
2032 * through to writing unconverted if we have not yet set up
2033 * CurrentMemoryContext.
2035 if (!in_error_recursion_trouble() &&
2036 !redirection_done &&
2037 CurrentMemoryContext != NULL)
2042 utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2048 stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2049 if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2056 * In case WriteConsoleW() failed, fall back to writing the
2057 * message unconverted.
2065 * Conversion on non-win32 platforms is not implemented yet. It requires
2066 * non-throw version of pg_do_encoding_conversion(), that converts
2067 * unconvertable characters to '?' without errors.
2072 * We ignore any error from write() here. We have no useful way to report
2073 * it ... certainly whining on stderr isn't likely to be productive.
2075 rc = write(fileno(stderr), line, len);
2080 * setup formatted_log_time, for consistent times between CSV and regular logs
2083 setup_formatted_log_time(void)
2086 pg_time_t stamp_time;
2089 gettimeofday(&tv, NULL);
2090 stamp_time = (pg_time_t) tv.tv_sec;
2093 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2094 * least with a minimal GMT value) before Log_line_prefix can become
2095 * nonempty or CSV mode can be selected.
2097 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
2098 /* leave room for milliseconds... */
2099 "%Y-%m-%d %H:%M:%S %Z",
2100 pg_localtime(&stamp_time, log_timezone));
2102 /* 'paste' milliseconds into place... */
2103 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
2104 strncpy(formatted_log_time + 19, msbuf, 4);
2108 * setup formatted_start_time
2111 setup_formatted_start_time(void)
2113 pg_time_t stamp_time = (pg_time_t) MyStartTime;
2116 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2117 * least with a minimal GMT value) before Log_line_prefix can become
2118 * nonempty or CSV mode can be selected.
2120 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
2121 "%Y-%m-%d %H:%M:%S %Z",
2122 pg_localtime(&stamp_time, log_timezone));
2126 * process_log_prefix_padding --- helper function for processing the format
2127 * string in log_line_prefix
2129 * Note: This function returns NULL if it finds something which
2130 * it deems invalid in the format string.
2133 process_log_prefix_padding(const char *p, int *ppadding)
2135 int paddingsign = 1;
2142 if (*p == '\0') /* Did the buf end in %- ? */
2147 /* generate an int version of the numerical string */
2148 while (*p >= '0' && *p <= '9')
2149 padding = padding * 10 + (*p++ - '0');
2151 /* format is invalid if it ends with the padding number */
2155 padding *= paddingsign;
2156 *ppadding = padding;
2161 * Format tag info for log lines; append to the provided buffer.
2164 log_line_prefix(StringInfo buf, ErrorData *edata)
2166 /* static counter for line numbers */
2167 static long log_line_number = 0;
2169 /* has counter been reset in current process? */
2170 static int log_my_pid = 0;
2175 * This is one of the few places where we'd rather not inherit a static
2176 * variable's value from the postmaster. But since we will, reset it when
2177 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2178 * reset the formatted start timestamp too.
2180 if (log_my_pid != MyProcPid)
2182 log_line_number = 0;
2183 log_my_pid = MyProcPid;
2184 formatted_start_time[0] = '\0';
2188 if (Log_line_prefix == NULL)
2189 return; /* in case guc hasn't run yet */
2191 for (p = Log_line_prefix; *p != '\0'; p++)
2195 /* literal char, just copy */
2196 appendStringInfoChar(buf, *p);
2200 /* must be a '%', so skip to the next char */
2203 break; /* format error - ignore it */
2206 /* string contains %% */
2207 appendStringInfoChar(buf, '%');
2213 * Process any formatting which may exist after the '%'. Note that
2214 * process_log_prefix_padding moves p past the padding number if it
2217 * Note: Since only '-', '0' to '9' are valid formatting characters
2218 * we can do a quick check here to pre-check for formatting. If the
2219 * char is not formatting then we can skip a useless function call.
2221 * Further note: At least on some platforms, passing %*s rather than
2222 * %s to appendStringInfo() is substantially slower, so many of the
2223 * cases below avoid doing that unless non-zero padding is in fact
2228 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2231 /* process the option */
2237 const char *appname = application_name;
2239 if (appname == NULL || *appname == '\0')
2240 appname = _("[unknown]");
2242 appendStringInfo(buf, "%*s", padding, appname);
2244 appendStringInfoString(buf, appname);
2246 else if (padding != 0)
2247 appendStringInfoSpaces(buf,
2248 padding > 0 ? padding : -padding);
2254 const char *username = MyProcPort->user_name;
2256 if (username == NULL || *username == '\0')
2257 username = _("[unknown]");
2259 appendStringInfo(buf, "%*s", padding, username);
2261 appendStringInfoString(buf, username);
2263 else if (padding != 0)
2264 appendStringInfoSpaces(buf,
2265 padding > 0 ? padding : -padding);
2270 const char *dbname = MyProcPort->database_name;
2272 if (dbname == NULL || *dbname == '\0')
2273 dbname = _("[unknown]");
2275 appendStringInfo(buf, "%*s", padding, dbname);
2277 appendStringInfoString(buf, dbname);
2279 else if (padding != 0)
2280 appendStringInfoSpaces(buf,
2281 padding > 0 ? padding : -padding);
2287 snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2288 (long) (MyStartTime), MyProcPid);
2289 appendStringInfo(buf, "%*s", padding, strfbuf);
2292 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2296 appendStringInfo(buf, "%*d", padding, MyProcPid);
2298 appendStringInfo(buf, "%d", MyProcPid);
2302 appendStringInfo(buf, "%*ld", padding, log_line_number);
2304 appendStringInfo(buf, "%ld", log_line_number);
2307 setup_formatted_log_time();
2309 appendStringInfo(buf, "%*s", padding, formatted_log_time);
2311 appendStringInfoString(buf, formatted_log_time);
2315 pg_time_t stamp_time = (pg_time_t) time(NULL);
2318 pg_strftime(strfbuf, sizeof(strfbuf),
2319 "%Y-%m-%d %H:%M:%S %Z",
2320 pg_localtime(&stamp_time, log_timezone));
2322 appendStringInfo(buf, "%*s", padding, strfbuf);
2324 appendStringInfoString(buf, strfbuf);
2328 if (formatted_start_time[0] == '\0')
2329 setup_formatted_start_time();
2331 appendStringInfo(buf, "%*s", padding, formatted_start_time);
2333 appendStringInfoString(buf, formatted_start_time);
2341 psdisp = get_ps_display(&displen);
2343 appendStringInfo(buf, "%*s", padding, psdisp);
2345 appendBinaryStringInfo(buf, psdisp, displen);
2348 else if (padding != 0)
2349 appendStringInfoSpaces(buf,
2350 padding > 0 ? padding : -padding);
2353 if (MyProcPort && MyProcPort->remote_host)
2357 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2360 * This option is slightly special as the port number
2361 * may be appended onto the end. Here we need to build
2362 * 1 string which contains the remote_host and optionally
2363 * the remote_port (if set) so we can properly align the
2368 hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2369 appendStringInfo(buf, "%*s", padding, hostport);
2373 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2377 /* padding is 0, so we don't need a temp buffer */
2378 appendStringInfoString(buf, MyProcPort->remote_host);
2379 if (MyProcPort->remote_port &&
2380 MyProcPort->remote_port[0] != '\0')
2381 appendStringInfo(buf, "(%s)",
2382 MyProcPort->remote_port);
2386 else if (padding != 0)
2387 appendStringInfoSpaces(buf,
2388 padding > 0 ? padding : -padding);
2391 if (MyProcPort && MyProcPort->remote_host)
2394 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2396 appendStringInfoString(buf, MyProcPort->remote_host);
2398 else if (padding != 0)
2399 appendStringInfoSpaces(buf,
2400 padding > 0 ? padding : -padding);
2403 /* in postmaster and friends, stop if %q is seen */
2404 /* in a backend, just ignore */
2405 if (MyProcPort == NULL)
2409 /* keep VXID format in sync with lockfuncs.c */
2410 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2415 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2416 MyProc->backendId, MyProc->lxid);
2417 appendStringInfo(buf, "%*s", padding, strfbuf);
2420 appendStringInfo(buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2422 else if (padding != 0)
2423 appendStringInfoSpaces(buf,
2424 padding > 0 ? padding : -padding);
2428 appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2430 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2434 appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2436 appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2439 /* format error - ignore it */
2446 * append a CSV'd version of a string to a StringInfo
2447 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2448 * If it's NULL, append nothing.
2451 appendCSVLiteral(StringInfo buf, const char *data)
2453 const char *p = data;
2456 /* avoid confusing an empty string with NULL */
2460 appendStringInfoCharMacro(buf, '"');
2461 while ((c = *p++) != '\0')
2464 appendStringInfoCharMacro(buf, '"');
2465 appendStringInfoCharMacro(buf, c);
2467 appendStringInfoCharMacro(buf, '"');
2471 * Constructs the error message, depending on the Errordata it gets, in a CSV
2472 * format which is described in doc/src/sgml/config.sgml.
2475 write_csvlog(ErrorData *edata)
2478 bool print_stmt = false;
2480 /* static counter for line numbers */
2481 static long log_line_number = 0;
2483 /* has counter been reset in current process? */
2484 static int log_my_pid = 0;
2487 * This is one of the few places where we'd rather not inherit a static
2488 * variable's value from the postmaster. But since we will, reset it when
2489 * MyProcPid changes.
2491 if (log_my_pid != MyProcPid)
2493 log_line_number = 0;
2494 log_my_pid = MyProcPid;
2495 formatted_start_time[0] = '\0';
2499 initStringInfo(&buf);
2502 * timestamp with milliseconds
2504 * Check if the timestamp is already calculated for the syslog message,
2505 * and use it if so. Otherwise, get the current timestamp. This is done
2506 * to put same timestamp in both syslog and csvlog messages.
2508 if (formatted_log_time[0] == '\0')
2509 setup_formatted_log_time();
2511 appendStringInfoString(&buf, formatted_log_time);
2512 appendStringInfoChar(&buf, ',');
2516 appendCSVLiteral(&buf, MyProcPort->user_name);
2517 appendStringInfoChar(&buf, ',');
2521 appendCSVLiteral(&buf, MyProcPort->database_name);
2522 appendStringInfoChar(&buf, ',');
2526 appendStringInfo(&buf, "%d", MyProcPid);
2527 appendStringInfoChar(&buf, ',');
2529 /* Remote host and port */
2530 if (MyProcPort && MyProcPort->remote_host)
2532 appendStringInfoChar(&buf, '"');
2533 appendStringInfoString(&buf, MyProcPort->remote_host);
2534 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2536 appendStringInfoChar(&buf, ':');
2537 appendStringInfoString(&buf, MyProcPort->remote_port);
2539 appendStringInfoChar(&buf, '"');
2541 appendStringInfoChar(&buf, ',');
2544 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2545 appendStringInfoChar(&buf, ',');
2548 appendStringInfo(&buf, "%ld", log_line_number);
2549 appendStringInfoChar(&buf, ',');
2554 StringInfoData msgbuf;
2558 initStringInfo(&msgbuf);
2560 psdisp = get_ps_display(&displen);
2561 appendBinaryStringInfo(&msgbuf, psdisp, displen);
2562 appendCSVLiteral(&buf, msgbuf.data);
2566 appendStringInfoChar(&buf, ',');
2568 /* session start timestamp */
2569 if (formatted_start_time[0] == '\0')
2570 setup_formatted_start_time();
2571 appendStringInfoString(&buf, formatted_start_time);
2572 appendStringInfoChar(&buf, ',');
2574 /* Virtual transaction id */
2575 /* keep VXID format in sync with lockfuncs.c */
2576 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2577 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2578 appendStringInfoChar(&buf, ',');
2580 /* Transaction id */
2581 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2582 appendStringInfoChar(&buf, ',');
2584 /* Error severity */
2585 appendStringInfoString(&buf, error_severity(edata->elevel));
2586 appendStringInfoChar(&buf, ',');
2588 /* SQL state code */
2589 appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2590 appendStringInfoChar(&buf, ',');
2593 appendCSVLiteral(&buf, edata->message);
2594 appendStringInfoChar(&buf, ',');
2596 /* errdetail or errdetail_log */
2597 if (edata->detail_log)
2598 appendCSVLiteral(&buf, edata->detail_log);
2600 appendCSVLiteral(&buf, edata->detail);
2601 appendStringInfoChar(&buf, ',');
2604 appendCSVLiteral(&buf, edata->hint);
2605 appendStringInfoChar(&buf, ',');
2607 /* internal query */
2608 appendCSVLiteral(&buf, edata->internalquery);
2609 appendStringInfoChar(&buf, ',');
2611 /* if printed internal query, print internal pos too */
2612 if (edata->internalpos > 0 && edata->internalquery != NULL)
2613 appendStringInfo(&buf, "%d", edata->internalpos);
2614 appendStringInfoChar(&buf, ',');
2617 appendCSVLiteral(&buf, edata->context);
2618 appendStringInfoChar(&buf, ',');
2620 /* user query --- only reported if not disabled by the caller */
2621 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2622 debug_query_string != NULL &&
2626 appendCSVLiteral(&buf, debug_query_string);
2627 appendStringInfoChar(&buf, ',');
2628 if (print_stmt && edata->cursorpos > 0)
2629 appendStringInfo(&buf, "%d", edata->cursorpos);
2630 appendStringInfoChar(&buf, ',');
2632 /* file error location */
2633 if (Log_error_verbosity >= PGERROR_VERBOSE)
2635 StringInfoData msgbuf;
2637 initStringInfo(&msgbuf);
2639 if (edata->funcname && edata->filename)
2640 appendStringInfo(&msgbuf, "%s, %s:%d",
2641 edata->funcname, edata->filename,
2643 else if (edata->filename)
2644 appendStringInfo(&msgbuf, "%s:%d",
2645 edata->filename, edata->lineno);
2646 appendCSVLiteral(&buf, msgbuf.data);
2649 appendStringInfoChar(&buf, ',');
2651 /* application name */
2652 if (application_name)
2653 appendCSVLiteral(&buf, application_name);
2655 appendStringInfoChar(&buf, '\n');
2657 /* If in the syslogger process, try to write messages direct to file */
2659 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2661 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2667 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2671 unpack_sql_state(int sql_state)
2673 static char buf[12];
2676 for (i = 0; i < 5; i++)
2678 buf[i] = PGUNSIXBIT(sql_state);
2688 * Write error report to server's log
2691 send_message_to_server_log(ErrorData *edata)
2695 initStringInfo(&buf);
2697 formatted_log_time[0] = '\0';
2699 log_line_prefix(&buf, edata);
2700 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2702 if (Log_error_verbosity >= PGERROR_VERBOSE)
2703 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2706 append_with_tabs(&buf, edata->message);
2708 append_with_tabs(&buf, _("missing error text"));
2710 if (edata->cursorpos > 0)
2711 appendStringInfo(&buf, _(" at character %d"),
2713 else if (edata->internalpos > 0)
2714 appendStringInfo(&buf, _(" at character %d"),
2715 edata->internalpos);
2717 appendStringInfoChar(&buf, '\n');
2719 if (Log_error_verbosity >= PGERROR_DEFAULT)
2721 if (edata->detail_log)
2723 log_line_prefix(&buf, edata);
2724 appendStringInfoString(&buf, _("DETAIL: "));
2725 append_with_tabs(&buf, edata->detail_log);
2726 appendStringInfoChar(&buf, '\n');
2728 else if (edata->detail)
2730 log_line_prefix(&buf, edata);
2731 appendStringInfoString(&buf, _("DETAIL: "));
2732 append_with_tabs(&buf, edata->detail);
2733 appendStringInfoChar(&buf, '\n');
2737 log_line_prefix(&buf, edata);
2738 appendStringInfoString(&buf, _("HINT: "));
2739 append_with_tabs(&buf, edata->hint);
2740 appendStringInfoChar(&buf, '\n');
2742 if (edata->internalquery)
2744 log_line_prefix(&buf, edata);
2745 appendStringInfoString(&buf, _("QUERY: "));
2746 append_with_tabs(&buf, edata->internalquery);
2747 appendStringInfoChar(&buf, '\n');
2751 log_line_prefix(&buf, edata);
2752 appendStringInfoString(&buf, _("CONTEXT: "));
2753 append_with_tabs(&buf, edata->context);
2754 appendStringInfoChar(&buf, '\n');
2756 if (Log_error_verbosity >= PGERROR_VERBOSE)
2758 /* assume no newlines in funcname or filename... */
2759 if (edata->funcname && edata->filename)
2761 log_line_prefix(&buf, edata);
2762 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2763 edata->funcname, edata->filename,
2766 else if (edata->filename)
2768 log_line_prefix(&buf, edata);
2769 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2770 edata->filename, edata->lineno);
2776 * If the user wants the query that generated this error logged, do it.
2778 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2779 debug_query_string != NULL &&
2782 log_line_prefix(&buf, edata);
2783 appendStringInfoString(&buf, _("STATEMENT: "));
2784 append_with_tabs(&buf, debug_query_string);
2785 appendStringInfoChar(&buf, '\n');
2789 /* Write to syslog, if enabled */
2790 if (Log_destination & LOG_DESTINATION_SYSLOG)
2794 switch (edata->elevel)
2801 syslog_level = LOG_DEBUG;
2806 syslog_level = LOG_INFO;
2810 syslog_level = LOG_NOTICE;
2813 syslog_level = LOG_WARNING;
2816 syslog_level = LOG_ERR;
2820 syslog_level = LOG_CRIT;
2824 write_syslog(syslog_level, buf.data);
2826 #endif /* HAVE_SYSLOG */
2829 /* Write to eventlog, if enabled */
2830 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2832 write_eventlog(edata->elevel, buf.data, buf.len);
2836 /* Write to stderr, if enabled */
2837 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2840 * Use the chunking protocol if we know the syslogger should be
2841 * catching stderr output, and we are not ourselves the syslogger.
2842 * Otherwise, just do a vanilla write to stderr.
2844 if (redirection_done && !am_syslogger)
2845 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2849 * In a win32 service environment, there is no usable stderr. Capture
2850 * anything going there and write it to the eventlog instead.
2852 * If stderr redirection is active, it was OK to write to stderr above
2853 * because that's really a pipe to the syslogger process.
2855 else if (pgwin32_is_service())
2856 write_eventlog(edata->elevel, buf.data, buf.len);
2859 write_console(buf.data, buf.len);
2862 /* If in the syslogger process, try to write messages direct to file */
2864 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2866 /* Write to CSV log if enabled */
2867 if (Log_destination & LOG_DESTINATION_CSVLOG)
2869 if (redirection_done || am_syslogger)
2872 * send CSV data if it's safe to do so (syslogger doesn't need the
2873 * pipe). First get back the space in the message buffer.
2876 write_csvlog(edata);
2881 * syslogger not up (yet), so just dump the message to stderr,
2882 * unless we already did so above.
2884 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2885 whereToSendOutput != DestDebug)
2886 write_console(buf.data, buf.len);
2897 * Send data to the syslogger using the chunked protocol
2899 * Note: when there are multiple backends writing into the syslogger pipe,
2900 * it's critical that each write go into the pipe indivisibly, and not
2901 * get interleaved with data from other processes. Fortunately, the POSIX
2902 * spec requires that writes to pipes be atomic so long as they are not
2903 * more than PIPE_BUF bytes long. So we divide long messages into chunks
2904 * that are no more than that length, and send one chunk per write() call.
2905 * The collector process knows how to reassemble the chunks.
2907 * Because of the atomic write requirement, there are only two possible
2908 * results from write() here: -1 for failure, or the requested number of
2909 * bytes. There is not really anything we can do about a failure; retry would
2910 * probably be an infinite loop, and we can't even report the error usefully.
2911 * (There is noplace else we could send it!) So we might as well just ignore
2912 * the result from write(). However, on some platforms you get a compiler
2913 * warning from ignoring write()'s result, so do a little dance with casting
2914 * rc to void to shut up the compiler.
2917 write_pipe_chunks(char *data, int len, int dest)
2920 int fd = fileno(stderr);
2925 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2926 p.proto.pid = MyProcPid;
2928 /* write all but the last chunk */
2929 while (len > PIPE_MAX_PAYLOAD)
2931 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2932 p.proto.len = PIPE_MAX_PAYLOAD;
2933 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2934 rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2936 data += PIPE_MAX_PAYLOAD;
2937 len -= PIPE_MAX_PAYLOAD;
2940 /* write the last chunk */
2941 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2943 memcpy(p.proto.data, data, len);
2944 rc = write(fd, &p, PIPE_HEADER_SIZE + len);
2950 * Append a text string to the error report being built for the client.
2952 * This is ordinarily identical to pq_sendstring(), but if we are in
2953 * error recursion trouble we skip encoding conversion, because of the
2954 * possibility that the problem is a failure in the encoding conversion
2955 * subsystem itself. Code elsewhere should ensure that the passed-in
2956 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2957 * in such cases. (In particular, we disable localization of error messages
2958 * to help ensure that's true.)
2961 err_sendstring(StringInfo buf, const char *str)
2963 if (in_error_recursion_trouble())
2964 pq_send_ascii_string(buf, str);
2966 pq_sendstring(buf, str);
2970 * Write error report to client
2973 send_message_to_frontend(ErrorData *edata)
2975 StringInfoData msgbuf;
2977 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2978 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2980 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2982 /* New style with separate fields */
2987 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2988 err_sendstring(&msgbuf, error_severity(edata->elevel));
2990 /* unpack MAKE_SQLSTATE code */
2991 ssval = edata->sqlerrcode;
2992 for (i = 0; i < 5; i++)
2994 tbuf[i] = PGUNSIXBIT(ssval);
2999 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3000 err_sendstring(&msgbuf, tbuf);
3002 /* M field is required per protocol, so always send something */
3003 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
3005 err_sendstring(&msgbuf, edata->message);
3007 err_sendstring(&msgbuf, _("missing error text"));
3011 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
3012 err_sendstring(&msgbuf, edata->detail);
3015 /* detail_log is intentionally not used here */
3019 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
3020 err_sendstring(&msgbuf, edata->hint);
3025 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3026 err_sendstring(&msgbuf, edata->context);
3029 if (edata->schema_name)
3031 pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3032 err_sendstring(&msgbuf, edata->schema_name);
3035 if (edata->table_name)
3037 pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3038 err_sendstring(&msgbuf, edata->table_name);
3041 if (edata->column_name)
3043 pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3044 err_sendstring(&msgbuf, edata->column_name);
3047 if (edata->datatype_name)
3049 pq_sendbyte(&msgbuf, PG_DIAG_DATATYPE_NAME);
3050 err_sendstring(&msgbuf, edata->datatype_name);
3053 if (edata->constraint_name)
3055 pq_sendbyte(&msgbuf, PG_DIAG_CONSTRAINT_NAME);
3056 err_sendstring(&msgbuf, edata->constraint_name);
3059 if (edata->cursorpos > 0)
3061 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3062 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
3063 err_sendstring(&msgbuf, tbuf);
3066 if (edata->internalpos > 0)
3068 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3069 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
3070 err_sendstring(&msgbuf, tbuf);
3073 if (edata->internalquery)
3075 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
3076 err_sendstring(&msgbuf, edata->internalquery);
3079 if (edata->filename)
3081 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3082 err_sendstring(&msgbuf, edata->filename);
3085 if (edata->lineno > 0)
3087 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3088 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3089 err_sendstring(&msgbuf, tbuf);
3092 if (edata->funcname)
3094 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
3095 err_sendstring(&msgbuf, edata->funcname);
3098 pq_sendbyte(&msgbuf, '\0'); /* terminator */
3102 /* Old style --- gin up a backwards-compatible message */
3105 initStringInfo(&buf);
3107 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
3109 if (edata->show_funcname && edata->funcname)
3110 appendStringInfo(&buf, "%s: ", edata->funcname);
3113 appendStringInfoString(&buf, edata->message);
3115 appendStringInfoString(&buf, _("missing error text"));
3117 if (edata->cursorpos > 0)
3118 appendStringInfo(&buf, _(" at character %d"),
3120 else if (edata->internalpos > 0)
3121 appendStringInfo(&buf, _(" at character %d"),
3122 edata->internalpos);
3124 appendStringInfoChar(&buf, '\n');
3126 err_sendstring(&msgbuf, buf.data);
3131 pq_endmessage(&msgbuf);
3134 * This flush is normally not necessary, since postgres.c will flush out
3135 * waiting data when control returns to the main loop. But it seems best
3136 * to leave it here, so that the client has some clue what happened if the
3137 * backend dies before getting back to the main loop ... error/notice
3138 * messages should not be a performance-critical path anyway, so an extra
3139 * flush won't hurt much ...
3146 * Support routines for formatting error messages.
3151 * expand_fmt_string --- process special format codes in a format string
3153 * We must replace %m with the appropriate strerror string, since vsnprintf
3154 * won't know what to do with it.
3156 * The result is a palloc'd string.
3159 expand_fmt_string(const char *fmt, ErrorData *edata)
3164 initStringInfo(&buf);
3166 for (cp = fmt; *cp; cp++)
3168 if (cp[0] == '%' && cp[1] != '\0')
3174 * Replace %m by system error string. If there are any %'s in
3175 * the string, we'd better double them so that vsnprintf won't
3180 cp2 = useful_strerror(edata->saved_errno);
3184 appendStringInfoCharMacro(&buf, '%');
3185 appendStringInfoCharMacro(&buf, *cp2);
3190 /* copy % and next char --- this avoids trouble with %%m */
3191 appendStringInfoCharMacro(&buf, '%');
3192 appendStringInfoCharMacro(&buf, *cp);
3196 appendStringInfoCharMacro(&buf, *cp);
3204 * A slightly cleaned-up version of strerror()
3207 useful_strerror(int errnum)
3209 /* this buffer is only used if strerror() and get_errno_symbol() fail */
3210 static char errorstr_buf[48];
3214 /* Winsock error code range, per WinError.h */
3215 if (errnum >= 10000 && errnum <= 11999)
3216 return pgwin32_socket_strerror(errnum);
3218 str = strerror(errnum);
3221 * Some strerror()s return an empty string for out-of-range errno. This
3222 * is ANSI C spec compliant, but not exactly useful. Also, we may get
3223 * back strings of question marks if libc cannot transcode the message to
3224 * the codeset specified by LC_CTYPE. If we get nothing useful, first try
3225 * get_errno_symbol(), and if that fails, print the numeric errno.
3227 if (str == NULL || *str == '\0' || *str == '?')
3228 str = get_errno_symbol(errnum);
3232 snprintf(errorstr_buf, sizeof(errorstr_buf),
3234 translator: This string will be truncated at 47
3235 characters expanded. */
3236 _("operating system error %d"), errnum);
3244 * Returns a symbol (e.g. "ENOENT") for an errno code.
3245 * Returns NULL if the code is unrecognized.
3248 get_errno_symbol(int errnum)
3258 return "EADDRINUSE";
3260 #ifdef EADDRNOTAVAIL
3262 return "EADDRNOTAVAIL";
3265 return "EAFNOSUPPORT";
3286 return "ECONNABORTED";
3289 return "ECONNREFUSED";
3292 return "ECONNRESET";
3306 return "EHOSTUNREACH";
3311 return "EINPROGRESS";
3335 return "ENAMETOOLONG";
3358 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
3374 #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP))
3376 return "EOPNOTSUPP";
3386 case EPROTONOSUPPORT:
3387 return "EPROTONOSUPPORT";
3404 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
3406 return "EWOULDBLOCK";
3417 * error_severity --- get localized string representing elevel
3420 error_severity(int elevel)
3431 prefix = _("DEBUG");
3441 prefix = _("NOTICE");
3444 prefix = _("WARNING");
3447 prefix = _("ERROR");
3450 prefix = _("FATAL");
3453 prefix = _("PANIC");
3467 * Append the string to the StringInfo buffer, inserting a tab after any
3471 append_with_tabs(StringInfo buf, const char *str)
3475 while ((ch = *str++) != '\0')
3477 appendStringInfoCharMacro(buf, ch);
3479 appendStringInfoCharMacro(buf, '\t');
3485 * Write errors to stderr (or by equal means when stderr is
3486 * not available). Used before ereport/elog can be used
3487 * safely (memory context, GUC load etc)
3490 write_stderr(const char *fmt,...)
3495 char errbuf[2048]; /* Arbitrary size? */
3502 /* On Unix, we just fprintf to stderr */
3503 vfprintf(stderr, fmt, ap);
3506 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3509 * On Win32, we print to stderr if running on a console, or write to
3510 * eventlog if running as a service
3512 if (pgwin32_is_service()) /* Running as a service */
3514 write_eventlog(ERROR, errbuf, strlen(errbuf));
3518 /* Not running as service, write to stderr */
3519 write_console(errbuf, strlen(errbuf));
3528 * is_log_level_output -- is elevel logically >= log_min_level?
3530 * We use this for tests that should consider LOG to sort out-of-order,
3531 * between ERROR and FATAL. Generally this is the right thing for testing
3532 * whether a message should go to the postmaster log, whereas a simple >=
3533 * test is correct for testing whether the message should go to the client.
3536 is_log_level_output(int elevel, int log_min_level)
3538 if (elevel == LOG || elevel == COMMERROR)
3540 if (log_min_level == LOG || log_min_level <= ERROR)
3543 else if (log_min_level == LOG)
3546 if (elevel >= FATAL)
3549 /* Neither is LOG */
3550 else if (elevel >= log_min_level)
3557 * Adjust the level of a recovery-related message per trace_recovery_messages.
3559 * The argument is the default log level of the message, eg, DEBUG2. (This
3560 * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3561 * If the level is >= trace_recovery_messages, we return LOG, causing the
3562 * message to be logged unconditionally (for most settings of
3563 * log_min_messages). Otherwise, we return the argument unchanged.
3564 * The message will then be shown based on the setting of log_min_messages.
3566 * Intention is to keep this for at least the whole of the 9.0 production
3567 * release, so we can more easily diagnose production problems in the field.
3568 * It should go away eventually, though, because it's an ugly and
3569 * hard-to-explain kluge.
3572 trace_recovery(int trace_level)
3574 if (trace_level < LOG &&
3575 trace_level >= trace_recovery_messages)