1 /*-------------------------------------------------------------------------
4 * error logging and reporting
6 * Some notes about recursion and errors during error processing:
8 * We need to be robust about recursive-error scenarios --- for example,
9 * if we run out of memory, it's important to be able to report that fact.
10 * There are a number of considerations that go into this.
12 * First, distinguish between re-entrant use and actual recursion. It
13 * is possible for an error or warning message to be emitted while the
14 * parameters for an error message are being computed. In this case
15 * errstart has been called for the outer message, and some field values
16 * may have already been saved, but we are not actually recursing. We handle
17 * this by providing a (small) stack of ErrorData records. The inner message
18 * can be computed and sent without disturbing the state of the outer message.
19 * (If the inner message is actually an error, this isn't very interesting
20 * because control won't come back to the outer message generator ... but
21 * if the inner message is only debug or log data, this is critical.)
23 * Second, actual recursion will occur if an error is reported by one of
24 * the elog.c routines or something they call. By far the most probable
25 * scenario of this sort is "out of memory"; and it's also the nastiest
26 * to handle because we'd likely also run out of memory while trying to
27 * report this error! Our escape hatch for this case is to reset the
28 * ErrorContext to empty before trying to process the inner error. Since
29 * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
30 * we should be able to process an "out of memory" message successfully.
31 * Since we lose the prior error state due to the reset, we won't be able
32 * to return to processing the original error, but we wouldn't have anyway.
33 * (NOTE: the escape hatch is not used for recursive situations where the
34 * inner message is of less than ERROR severity; in that case we just
35 * try to process it and return normally. Usually this will work, but if
36 * it ends up in infinite recursion, we will PANIC due to error stack
40 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
41 * Portions Copyright (c) 1994, Regents of the University of California
45 * $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.213 2009/03/02 21:18:43 tgl Exp $
47 *-------------------------------------------------------------------------
60 #include "access/transam.h"
61 #include "access/xact.h"
62 #include "libpq/libpq.h"
63 #include "libpq/pqformat.h"
64 #include "mb/pg_wchar.h"
65 #include "miscadmin.h"
66 #include "postmaster/postmaster.h"
67 #include "postmaster/syslogger.h"
68 #include "storage/ipc.h"
69 #include "storage/proc.h"
70 #include "tcop/tcopprot.h"
71 #include "utils/memutils.h"
72 #include "utils/ps_status.h"
76 #define _(x) err_gettext(x)
78 /* Global variables */
79 ErrorContextCallback *error_context_stack = NULL;
81 sigjmp_buf *PG_exception_stack = NULL;
83 extern bool redirection_done;
86 int Log_error_verbosity = PGERROR_VERBOSE;
87 char *Log_line_prefix = NULL; /* format for extra log line info */
88 int Log_destination = LOG_DESTINATION_STDERR;
93 * Max string length to send to syslog(). Note that this doesn't count the
94 * sequence-number prefix we add, and of course it doesn't count the prefix
95 * added by syslog itself. On many implementations it seems that the hard
96 * limit is approximately 2K bytes including both those prefixes.
98 #ifndef PG_SYSLOG_LIMIT
99 #define PG_SYSLOG_LIMIT 1024
102 static bool openlog_done = false;
103 static char *syslog_ident = NULL;
104 static int syslog_facility = LOG_LOCAL0;
106 static void write_syslog(int level, const char *line);
110 static void write_eventlog(int level, const char *line);
113 /* We provide a small stack of ErrorData records for re-entrant cases */
114 #define ERRORDATA_STACK_SIZE 5
116 static ErrorData errordata[ERRORDATA_STACK_SIZE];
118 static int errordata_stack_depth = -1; /* index of topmost active frame */
120 static int recursion_depth = 0; /* to detect actual recursion */
122 /* buffers for formatted timestamps that might be used by both
123 * log_line_prefix and csv logs.
126 #define FORMATTED_TS_LEN 128
127 static char formatted_start_time[FORMATTED_TS_LEN];
128 static char formatted_log_time[FORMATTED_TS_LEN];
131 /* Macro for checking errordata_stack_depth is reasonable */
132 #define CHECK_STACK_DEPTH() \
134 if (errordata_stack_depth < 0) \
136 errordata_stack_depth = -1; \
137 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
142 static void log_line_prefix(StringInfo buf);
143 static void send_message_to_server_log(ErrorData *edata);
144 static void send_message_to_frontend(ErrorData *edata);
145 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
146 static const char *useful_strerror(int errnum);
147 static const char *error_severity(int elevel);
148 static void append_with_tabs(StringInfo buf, const char *str);
149 static bool is_log_level_output(int elevel, int log_min_level);
150 static void write_pipe_chunks(char *data, int len, int dest);
151 static void write_csvlog(ErrorData *edata);
152 static void setup_formatted_log_time(void);
153 static void setup_formatted_start_time(void);
157 * in_error_recursion_trouble --- are we at risk of infinite error recursion?
159 * This function exists to provide common control of various fallback steps
160 * that we take if we think we are facing infinite error recursion. See the
161 * callers for details.
164 in_error_recursion_trouble(void)
166 /* Pull the plug if recurse more than once */
167 return (recursion_depth > 2);
171 * One of those fallback steps is to stop trying to localize the error
172 * message, since there's a significant probability that that's exactly
173 * what's causing the recursion.
175 static inline const char *
176 err_gettext(const char *str)
179 if (in_error_recursion_trouble())
190 * errstart --- begin an error-reporting cycle
192 * Create a stack entry and store the given parameters in it. Subsequently,
193 * errmsg() and perhaps other routines will be called to further populate
194 * the stack entry. Finally, errfinish() will be called to actually process
197 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
198 * report (if it's a warning or lower and not to be reported anywhere).
201 errstart(int elevel, const char *filename, int lineno,
202 const char *funcname, const char *domain)
205 bool output_to_server;
206 bool output_to_client = false;
210 * Check some cases in which we want to promote an error into a more
211 * severe error. None of this logic applies for non-error messages.
216 * If we are inside a critical section, all errors become PANIC
217 * errors. See miscadmin.h.
219 if (CritSectionCount > 0)
223 * Check reasons for treating ERROR as FATAL:
225 * 1. we have no handler to pass the error to (implies we are in the
226 * postmaster or in backend startup).
228 * 2. ExitOnAnyError mode switch is set (initdb uses this).
230 * 3. the error occurred after proc_exit has begun to run. (It's
231 * proc_exit's responsibility to see that this doesn't turn into
232 * infinite recursion!)
236 if (PG_exception_stack == NULL ||
238 proc_exit_inprogress)
243 * If the error level is ERROR or more, errfinish is not going to
244 * return to caller; therefore, if there is any stacked error already
245 * in progress it will be lost. This is more or less okay, except we
246 * do not want to have a FATAL or PANIC error downgraded because the
247 * reporting process was interrupted by a lower-grade error. So check
248 * the stack and make sure we panic if panic is warranted.
250 for (i = 0; i <= errordata_stack_depth; i++)
251 elevel = Max(elevel, errordata[i].elevel);
255 * Now decide whether we need to process this report at all; if it's
256 * warning or less and not enabled for logging, just return FALSE without
257 * starting up any error logging machinery.
260 /* Determine whether message is enabled for server log output */
261 if (IsPostmasterEnvironment)
262 output_to_server = is_log_level_output(elevel, log_min_messages);
264 /* In bootstrap/standalone case, do not sort LOG out-of-order */
265 output_to_server = (elevel >= log_min_messages);
267 /* Determine whether message is enabled for client output */
268 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
271 * client_min_messages is honored only after we complete the
272 * authentication handshake. This is required both for security
273 * reasons and because many clients can't handle NOTICE messages
274 * during authentication.
276 if (ClientAuthInProgress)
277 output_to_client = (elevel >= ERROR);
279 output_to_client = (elevel >= client_min_messages ||
283 /* Skip processing effort if non-error message will not be output */
284 if (elevel < ERROR && !output_to_server && !output_to_client)
288 * Okay, crank up a stack entry to store the info in.
291 if (recursion_depth++ > 0 && elevel >= ERROR)
294 * Ooops, error during error processing. Clear ErrorContext as
295 * discussed at top of file. We will not return to the original
296 * error's reporter or handler, so we don't need it.
298 MemoryContextReset(ErrorContext);
301 * Infinite error recursion might be due to something broken
302 * in a context traceback routine. Abandon them too. We also abandon
303 * attempting to print the error statement (which, if long, could
304 * itself be the source of the recursive failure).
306 if (in_error_recursion_trouble())
308 error_context_stack = NULL;
309 debug_query_string = NULL;
312 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
315 * Wups, stack not big enough. We treat this as a PANIC condition
316 * because it suggests an infinite loop of errors during error
319 errordata_stack_depth = -1; /* make room on stack */
320 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
323 /* Initialize data for this error frame */
324 edata = &errordata[errordata_stack_depth];
325 MemSet(edata, 0, sizeof(ErrorData));
326 edata->elevel = elevel;
327 edata->output_to_server = output_to_server;
328 edata->output_to_client = output_to_client;
329 edata->filename = filename;
330 edata->lineno = lineno;
331 edata->funcname = funcname;
332 /* the default text domain is the backend's */
333 edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
334 /* Select default errcode based on elevel */
336 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
337 else if (elevel == WARNING)
338 edata->sqlerrcode = ERRCODE_WARNING;
340 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
341 /* errno is saved here so that error parameter eval can't change it */
342 edata->saved_errno = errno;
349 * errfinish --- end an error-reporting cycle
351 * Produce the appropriate error report(s) and pop the error stack.
353 * If elevel is ERROR or worse, control does not return to the caller.
354 * See elog.h for the error level definitions.
357 errfinish(int dummy,...)
359 ErrorData *edata = &errordata[errordata_stack_depth];
360 int elevel = edata->elevel;
361 MemoryContext oldcontext;
362 ErrorContextCallback *econtext;
368 * Do processing in ErrorContext, which we hope has enough reserved space
369 * to report an error.
371 oldcontext = MemoryContextSwitchTo(ErrorContext);
374 * Call any context callback functions. Errors occurring in callback
375 * functions will be treated as recursive errors --- this ensures we will
376 * avoid infinite recursion (see errstart).
378 for (econtext = error_context_stack;
380 econtext = econtext->previous)
381 (*econtext->callback) (econtext->arg);
384 * If ERROR (not more nor less) we pass it off to the current handler.
385 * Printing it and popping the stack is the responsibility of the handler.
390 * We do some minimal cleanup before longjmp'ing so that handlers can
391 * execute in a reasonably sane state.
394 /* This is just in case the error came while waiting for input */
395 ImmediateInterruptOK = false;
398 * Reset InterruptHoldoffCount in case we ereport'd from inside an
399 * interrupt holdoff section. (We assume here that no handler will
400 * itself be inside a holdoff section. If necessary, such a handler
401 * could save and restore InterruptHoldoffCount for itself, but this
402 * should make life easier for most.)
404 InterruptHoldoffCount = 0;
406 CritSectionCount = 0; /* should be unnecessary, but... */
409 * Note that we leave CurrentMemoryContext set to ErrorContext. The
410 * handler should reset it to something else soon.
418 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
419 * progress, so that we can report the message before dying. (Without
420 * this, pq_putmessage will refuse to send the message at all, which is
421 * what we want for NOTICE messages, but not for fatal exits.) This hack
422 * is necessary because of poor design of old-style copy protocol. Note
423 * we must do this even if client is fool enough to have set
424 * client_min_messages above FATAL, so don't look at output_to_client.
426 if (elevel >= FATAL && whereToSendOutput == DestRemote)
429 /* Emit the message to the right places */
432 /* Now free up subsidiary data attached to stack entry, and release it */
434 pfree(edata->message);
436 pfree(edata->detail);
437 if (edata->detail_log)
438 pfree(edata->detail_log);
442 pfree(edata->context);
443 if (edata->internalquery)
444 pfree(edata->internalquery);
446 errordata_stack_depth--;
448 /* Exit error-handling context */
449 MemoryContextSwitchTo(oldcontext);
453 * Perform error recovery action as specified by elevel.
458 * For a FATAL error, we let proc_exit clean up and exit.
460 ImmediateInterruptOK = false;
463 * If we just reported a startup failure, the client will disconnect
464 * on receiving it, so don't send any more to the client.
466 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
467 whereToSendOutput = DestNone;
470 * fflush here is just to improve the odds that we get to see the
471 * error message, in case things are so hosed that proc_exit crashes.
472 * Any other code you might be tempted to add here should probably be
473 * in an on_proc_exit or on_shmem_exit callback instead.
479 * Do normal process-exit cleanup, then return exit code 1 to indicate
480 * FATAL termination. The postmaster may or may not consider this
481 * worthy of panic, depending on which subprocess returns it.
489 * Serious crash time. Postmaster will observe SIGABRT process exit
490 * status and kill the other backends too.
492 * XXX: what if we are *in* the postmaster? abort() won't kill our
495 ImmediateInterruptOK = false;
502 * We reach here if elevel <= WARNING. OK to return to caller.
504 * But check for cancel/die interrupt first --- this is so that the user
505 * can stop a query emitting tons of notice or warning messages, even if
506 * it's in a loop that otherwise fails to check for interrupts.
508 CHECK_FOR_INTERRUPTS();
513 * errcode --- add SQLSTATE error code to the current error
515 * The code is expected to be represented as per MAKE_SQLSTATE().
518 errcode(int sqlerrcode)
520 ErrorData *edata = &errordata[errordata_stack_depth];
522 /* we don't bother incrementing recursion_depth */
525 edata->sqlerrcode = sqlerrcode;
527 return 0; /* return value does not matter */
532 * errcode_for_file_access --- add SQLSTATE error code to the current error
534 * The SQLSTATE code is chosen based on the saved errno value. We assume
535 * that the failing operation was some type of disk file access.
537 * NOTE: the primary error message string should generally include %m
541 errcode_for_file_access(void)
543 ErrorData *edata = &errordata[errordata_stack_depth];
545 /* we don't bother incrementing recursion_depth */
548 switch (edata->saved_errno)
550 /* Permission-denied failures */
551 case EPERM: /* Not super-user */
552 case EACCES: /* Permission denied */
554 case EROFS: /* Read only file system */
556 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
560 case ENOENT: /* No such file or directory */
561 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
565 case EEXIST: /* File exists */
566 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
569 /* Wrong object type or state */
570 case ENOTDIR: /* Not a directory */
571 case EISDIR: /* Is a directory */
572 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
573 case ENOTEMPTY: /* Directory not empty */
575 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
578 /* Insufficient resources */
579 case ENOSPC: /* No space left on device */
580 edata->sqlerrcode = ERRCODE_DISK_FULL;
583 case ENFILE: /* File table overflow */
584 case EMFILE: /* Too many open files */
585 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
588 /* Hardware failure */
589 case EIO: /* I/O error */
590 edata->sqlerrcode = ERRCODE_IO_ERROR;
593 /* All else is classified as internal errors */
595 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
599 return 0; /* return value does not matter */
603 * errcode_for_socket_access --- add SQLSTATE error code to the current error
605 * The SQLSTATE code is chosen based on the saved errno value. We assume
606 * that the failing operation was some type of socket access.
608 * NOTE: the primary error message string should generally include %m
612 errcode_for_socket_access(void)
614 ErrorData *edata = &errordata[errordata_stack_depth];
616 /* we don't bother incrementing recursion_depth */
619 switch (edata->saved_errno)
621 /* Loss of connection */
626 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
629 /* All else is classified as internal errors */
631 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
635 return 0; /* return value does not matter */
640 * This macro handles expansion of a format string and associated parameters;
641 * it's common code for errmsg(), errdetail(), etc. Must be called inside
642 * a routine that is declared like "const char *fmt, ..." and has an edata
643 * pointer set up. The message is assigned to edata->targetfield, or
644 * appended to it if appendval is true. The message is subject to translation
645 * if translateit is true.
647 * Note: we pstrdup the buffer rather than just transferring its storage
648 * to the edata field because the buffer might be considerably larger than
651 #define EVALUATE_MESSAGE(targetfield, appendval, translateit) \
654 StringInfoData buf; \
655 /* Internationalize the error format string */ \
656 if (translateit && !in_error_recursion_trouble()) \
657 fmt = dgettext(edata->domain, fmt); \
658 /* Expand %m in format string */ \
659 fmtbuf = expand_fmt_string(fmt, edata); \
660 initStringInfo(&buf); \
661 if ((appendval) && edata->targetfield) \
662 appendStringInfo(&buf, "%s\n", edata->targetfield); \
663 /* Generate actual output --- have to use appendStringInfoVA */ \
668 va_start(args, fmt); \
669 success = appendStringInfoVA(&buf, fmtbuf, args); \
673 enlargeStringInfo(&buf, buf.maxlen); \
675 /* Done with expanded fmt */ \
677 /* Save the completed message into the stack item */ \
678 if (edata->targetfield) \
679 pfree(edata->targetfield); \
680 edata->targetfield = pstrdup(buf.data); \
686 * errmsg --- add a primary error message text to the current error
688 * In addition to the usual %-escapes recognized by printf, "%m" in
689 * fmt is replaced by the error message for the caller's value of errno.
691 * Note: no newline is needed at the end of the fmt string, since
692 * ereport will provide one for the output methods that need it.
695 errmsg(const char *fmt,...)
697 ErrorData *edata = &errordata[errordata_stack_depth];
698 MemoryContext oldcontext;
702 oldcontext = MemoryContextSwitchTo(ErrorContext);
704 EVALUATE_MESSAGE(message, false, true);
706 MemoryContextSwitchTo(oldcontext);
708 return 0; /* return value does not matter */
713 * errmsg_internal --- add a primary error message text to the current error
715 * This is exactly like errmsg() except that strings passed to errmsg_internal
716 * are not translated, and are customarily left out of the
717 * internationalization message dictionary. This should be used for "can't
718 * happen" cases that are probably not worth spending translation effort on.
719 * We also use this for certain cases where we *must* not try to translate
720 * the message because the translation would fail and result in infinite
724 errmsg_internal(const char *fmt,...)
726 ErrorData *edata = &errordata[errordata_stack_depth];
727 MemoryContext oldcontext;
731 oldcontext = MemoryContextSwitchTo(ErrorContext);
733 EVALUATE_MESSAGE(message, false, false);
735 MemoryContextSwitchTo(oldcontext);
737 return 0; /* return value does not matter */
742 * errdetail --- add a detail error message text to the current error
745 errdetail(const char *fmt,...)
747 ErrorData *edata = &errordata[errordata_stack_depth];
748 MemoryContext oldcontext;
752 oldcontext = MemoryContextSwitchTo(ErrorContext);
754 EVALUATE_MESSAGE(detail, false, true);
756 MemoryContextSwitchTo(oldcontext);
758 return 0; /* return value does not matter */
763 * errdetail_log --- add a detail_log error message text to the current error
766 errdetail_log(const char *fmt,...)
768 ErrorData *edata = &errordata[errordata_stack_depth];
769 MemoryContext oldcontext;
773 oldcontext = MemoryContextSwitchTo(ErrorContext);
775 EVALUATE_MESSAGE(detail_log, false, true);
777 MemoryContextSwitchTo(oldcontext);
779 return 0; /* return value does not matter */
784 * errhint --- add a hint error message text to the current error
787 errhint(const char *fmt,...)
789 ErrorData *edata = &errordata[errordata_stack_depth];
790 MemoryContext oldcontext;
794 oldcontext = MemoryContextSwitchTo(ErrorContext);
796 EVALUATE_MESSAGE(hint, false, true);
798 MemoryContextSwitchTo(oldcontext);
800 return 0; /* return value does not matter */
805 * errcontext --- add a context error message text to the current error
807 * Unlike other cases, multiple calls are allowed to build up a stack of
808 * context information. We assume earlier calls represent more-closely-nested
812 errcontext(const char *fmt,...)
814 ErrorData *edata = &errordata[errordata_stack_depth];
815 MemoryContext oldcontext;
819 oldcontext = MemoryContextSwitchTo(ErrorContext);
821 EVALUATE_MESSAGE(context, true, true);
823 MemoryContextSwitchTo(oldcontext);
825 return 0; /* return value does not matter */
830 * errhidestmt --- optionally suppress STATEMENT: field of log entry
832 * This should be called if the message text already includes the statement.
835 errhidestmt(bool hide_stmt)
837 ErrorData *edata = &errordata[errordata_stack_depth];
839 /* we don't bother incrementing recursion_depth */
842 edata->hide_stmt = hide_stmt;
844 return 0; /* return value does not matter */
849 * errfunction --- add reporting function name to the current error
851 * This is used when backwards compatibility demands that the function
852 * name appear in messages sent to old-protocol clients. Note that the
853 * passed string is expected to be a non-freeable constant string.
856 errfunction(const char *funcname)
858 ErrorData *edata = &errordata[errordata_stack_depth];
860 /* we don't bother incrementing recursion_depth */
863 edata->funcname = funcname;
864 edata->show_funcname = true;
866 return 0; /* return value does not matter */
870 * errposition --- add cursor position to the current error
873 errposition(int cursorpos)
875 ErrorData *edata = &errordata[errordata_stack_depth];
877 /* we don't bother incrementing recursion_depth */
880 edata->cursorpos = cursorpos;
882 return 0; /* return value does not matter */
886 * internalerrposition --- add internal cursor position to the current error
889 internalerrposition(int cursorpos)
891 ErrorData *edata = &errordata[errordata_stack_depth];
893 /* we don't bother incrementing recursion_depth */
896 edata->internalpos = cursorpos;
898 return 0; /* return value does not matter */
902 * internalerrquery --- add internal query text to the current error
904 * Can also pass NULL to drop the internal query text entry. This case
905 * is intended for use in error callback subroutines that are editorializing
906 * on the layout of the error report.
909 internalerrquery(const char *query)
911 ErrorData *edata = &errordata[errordata_stack_depth];
913 /* we don't bother incrementing recursion_depth */
916 if (edata->internalquery)
918 pfree(edata->internalquery);
919 edata->internalquery = NULL;
923 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
925 return 0; /* return value does not matter */
929 * geterrcode --- return the currently set SQLSTATE error code
931 * This is only intended for use in error callback subroutines, since there
932 * is no other place outside elog.c where the concept is meaningful.
937 ErrorData *edata = &errordata[errordata_stack_depth];
939 /* we don't bother incrementing recursion_depth */
942 return edata->sqlerrcode;
946 * geterrposition --- return the currently set error position (0 if none)
948 * This is only intended for use in error callback subroutines, since there
949 * is no other place outside elog.c where the concept is meaningful.
954 ErrorData *edata = &errordata[errordata_stack_depth];
956 /* we don't bother incrementing recursion_depth */
959 return edata->cursorpos;
963 * getinternalerrposition --- same for internal error position
965 * This is only intended for use in error callback subroutines, since there
966 * is no other place outside elog.c where the concept is meaningful.
969 getinternalerrposition(void)
971 ErrorData *edata = &errordata[errordata_stack_depth];
973 /* we don't bother incrementing recursion_depth */
976 return edata->internalpos;
981 * elog_start --- startup for old-style API
983 * All that we do here is stash the hidden filename/lineno/funcname
984 * arguments into a stack entry.
986 * We need this to be separate from elog_finish because there's no other
987 * portable way to deal with inserting extra arguments into the elog call.
988 * (If macros with variable numbers of arguments were portable, it'd be
989 * easy, but they aren't.)
992 elog_start(const char *filename, int lineno, const char *funcname)
996 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
999 * Wups, stack not big enough. We treat this as a PANIC condition
1000 * because it suggests an infinite loop of errors during error
1001 * recovery. Note that the message is intentionally not localized,
1002 * else failure to convert it to client encoding could cause further
1005 errordata_stack_depth = -1; /* make room on stack */
1006 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1009 edata = &errordata[errordata_stack_depth];
1010 edata->filename = filename;
1011 edata->lineno = lineno;
1012 edata->funcname = funcname;
1013 /* errno is saved now so that error parameter eval can't change it */
1014 edata->saved_errno = errno;
1018 * elog_finish --- finish up for old-style API
1021 elog_finish(int elevel, const char *fmt,...)
1023 ErrorData *edata = &errordata[errordata_stack_depth];
1024 MemoryContext oldcontext;
1026 CHECK_STACK_DEPTH();
1029 * Do errstart() to see if we actually want to report the message.
1031 errordata_stack_depth--;
1032 errno = edata->saved_errno;
1033 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1034 return; /* nothing to do */
1037 * Format error message just like errmsg_internal().
1040 oldcontext = MemoryContextSwitchTo(ErrorContext);
1042 EVALUATE_MESSAGE(message, false, false);
1044 MemoryContextSwitchTo(oldcontext);
1048 * And let errfinish() finish up.
1054 * Actual output of the top-of-stack error message
1056 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1057 * if the error is caught by somebody). For all other severity levels this
1058 * is called by errfinish.
1061 EmitErrorReport(void)
1063 ErrorData *edata = &errordata[errordata_stack_depth];
1064 MemoryContext oldcontext;
1067 CHECK_STACK_DEPTH();
1068 oldcontext = MemoryContextSwitchTo(ErrorContext);
1070 /* Send to server log, if enabled */
1071 if (edata->output_to_server)
1072 send_message_to_server_log(edata);
1074 /* Send to client, if enabled */
1075 if (edata->output_to_client)
1076 send_message_to_frontend(edata);
1078 MemoryContextSwitchTo(oldcontext);
1083 * CopyErrorData --- obtain a copy of the topmost error stack entry
1085 * This is only for use in error handler code. The data is copied into the
1086 * current memory context, so callers should always switch away from
1087 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1092 ErrorData *edata = &errordata[errordata_stack_depth];
1093 ErrorData *newedata;
1096 * we don't increment recursion_depth because out-of-memory here does not
1097 * indicate a problem within the error subsystem.
1099 CHECK_STACK_DEPTH();
1101 Assert(CurrentMemoryContext != ErrorContext);
1103 /* Copy the struct itself */
1104 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1105 memcpy(newedata, edata, sizeof(ErrorData));
1107 /* Make copies of separately-allocated fields */
1108 if (newedata->message)
1109 newedata->message = pstrdup(newedata->message);
1110 if (newedata->detail)
1111 newedata->detail = pstrdup(newedata->detail);
1112 if (newedata->detail_log)
1113 newedata->detail_log = pstrdup(newedata->detail_log);
1115 newedata->hint = pstrdup(newedata->hint);
1116 if (newedata->context)
1117 newedata->context = pstrdup(newedata->context);
1118 if (newedata->internalquery)
1119 newedata->internalquery = pstrdup(newedata->internalquery);
1125 * FreeErrorData --- free the structure returned by CopyErrorData.
1127 * Error handlers should use this in preference to assuming they know all
1128 * the separately-allocated fields.
1131 FreeErrorData(ErrorData *edata)
1134 pfree(edata->message);
1136 pfree(edata->detail);
1137 if (edata->detail_log)
1138 pfree(edata->detail_log);
1142 pfree(edata->context);
1143 if (edata->internalquery)
1144 pfree(edata->internalquery);
1149 * FlushErrorState --- flush the error state after error recovery
1151 * This should be called by an error handler after it's done processing
1152 * the error; or as soon as it's done CopyErrorData, if it intends to
1153 * do stuff that is likely to provoke another error. You are not "out" of
1154 * the error subsystem until you have done this.
1157 FlushErrorState(void)
1160 * Reset stack to empty. The only case where it would be more than one
1161 * deep is if we serviced an error that interrupted construction of
1162 * another message. We assume control escaped out of that message
1163 * construction and won't ever go back.
1165 errordata_stack_depth = -1;
1166 recursion_depth = 0;
1167 /* Delete all data in ErrorContext */
1168 MemoryContextResetAndDeleteChildren(ErrorContext);
1172 * ReThrowError --- re-throw a previously copied error
1174 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1175 * subsystem, then do some processing, and finally ReThrowError to re-throw
1176 * the original error. This is slower than just PG_RE_THROW() but should
1177 * be used if the "some processing" is likely to incur another error.
1180 ReThrowError(ErrorData *edata)
1182 ErrorData *newedata;
1184 Assert(edata->elevel == ERROR);
1186 /* Push the data back into the error context */
1188 MemoryContextSwitchTo(ErrorContext);
1190 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1193 * Wups, stack not big enough. We treat this as a PANIC condition
1194 * because it suggests an infinite loop of errors during error
1197 errordata_stack_depth = -1; /* make room on stack */
1198 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1201 newedata = &errordata[errordata_stack_depth];
1202 memcpy(newedata, edata, sizeof(ErrorData));
1204 /* Make copies of separately-allocated fields */
1205 if (newedata->message)
1206 newedata->message = pstrdup(newedata->message);
1207 if (newedata->detail)
1208 newedata->detail = pstrdup(newedata->detail);
1209 if (newedata->detail_log)
1210 newedata->detail_log = pstrdup(newedata->detail_log);
1212 newedata->hint = pstrdup(newedata->hint);
1213 if (newedata->context)
1214 newedata->context = pstrdup(newedata->context);
1215 if (newedata->internalquery)
1216 newedata->internalquery = pstrdup(newedata->internalquery);
1223 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1228 /* If possible, throw the error to the next outer setjmp handler */
1229 if (PG_exception_stack != NULL)
1230 siglongjmp(*PG_exception_stack, 1);
1234 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1235 * we have now exited only to discover that there is no outer setjmp
1236 * handler to pass the error to. Had the error been thrown outside
1237 * the block to begin with, we'd have promoted the error to FATAL, so
1238 * the correct behavior is to make it FATAL now; that is, emit it and
1239 * then call proc_exit.
1241 ErrorData *edata = &errordata[errordata_stack_depth];
1243 Assert(errordata_stack_depth >= 0);
1244 Assert(edata->elevel == ERROR);
1245 edata->elevel = FATAL;
1248 * At least in principle, the increase in severity could have changed
1249 * where-to-output decisions, so recalculate. This should stay in
1250 * sync with errstart(), which see for comments.
1252 if (IsPostmasterEnvironment)
1253 edata->output_to_server = is_log_level_output(FATAL,
1256 edata->output_to_server = (FATAL >= log_min_messages);
1257 if (whereToSendOutput == DestRemote)
1259 if (ClientAuthInProgress)
1260 edata->output_to_client = true;
1262 edata->output_to_client = (FATAL >= client_min_messages);
1266 * We can use errfinish() for the rest, but we don't want it to call
1267 * any error context routines a second time. Since we know we are
1268 * about to exit, it should be OK to just clear the context stack.
1270 error_context_stack = NULL;
1275 /* We mustn't return... */
1276 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1277 __FILE__, __LINE__);
1280 * Since ExceptionalCondition isn't declared noreturn because of
1281 * TrapMacro(), we need this to keep gcc from complaining.
1288 * Initialization of error output file
1296 if (OutputFileName[0])
1299 * A debug-output file name was given.
1301 * Make sure we can write the file, and find out if it's a tty.
1303 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1306 (errcode_for_file_access(),
1307 errmsg("could not open file \"%s\": %m", OutputFileName)));
1312 * Redirect our stderr to the debug output file.
1314 if (!freopen(OutputFileName, "a", stderr))
1316 (errcode_for_file_access(),
1317 errmsg("could not reopen file \"%s\" as stderr: %m",
1321 * If the file is a tty and we're running under the postmaster, try to
1322 * send stdout there as well (if it isn't a tty then stderr will block
1323 * out stdout, so we may as well let stdout go wherever it was going
1326 if (istty && IsUnderPostmaster)
1327 if (!freopen(OutputFileName, "a", stdout))
1329 (errcode_for_file_access(),
1330 errmsg("could not reopen file \"%s\" as stdout: %m",
1339 * Set or update the parameters for syslog logging
1342 set_syslog_parameters(const char *ident, int facility)
1345 * guc.c is likely to call us repeatedly with same parameters, so don't
1346 * thrash the syslog connection unnecessarily. Also, we do not re-open
1347 * the connection until needed, since this routine will get called whether
1348 * or not Log_destination actually mentions syslog.
1350 * Note that we make our own copy of the ident string rather than relying
1351 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1352 * accidentally free a string that syslog is still using.
1354 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1355 syslog_facility != facility)
1360 openlog_done = false;
1364 syslog_ident = strdup(ident);
1365 /* if the strdup fails, we will cope in write_syslog() */
1366 syslog_facility = facility;
1372 * Write a message line to syslog
1375 write_syslog(int level, const char *line)
1377 static unsigned long seq = 0;
1382 /* Open syslog connection if not done yet */
1385 openlog(syslog_ident ? syslog_ident : "postgres",
1386 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1388 openlog_done = true;
1392 * We add a sequence number to each log message to suppress "same"
1398 * Our problem here is that many syslog implementations don't handle long
1399 * messages in an acceptable manner. While this function doesn't help that
1400 * fact, it does work around by splitting up messages into smaller pieces.
1402 * We divide into multiple syslog() calls if message is too long or if the
1403 * message contains embedded newline(s).
1406 nlpos = strchr(line, '\n');
1407 if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1413 char buf[PG_SYSLOG_LIMIT + 1];
1417 /* if we start at a newline, move ahead one char */
1418 if (line[0] == '\n')
1422 /* we need to recompute the next newline's position, too */
1423 nlpos = strchr(line, '\n');
1427 /* copy one line, or as much as will fit, to buf */
1429 buflen = nlpos - line;
1432 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1433 memcpy(buf, line, buflen);
1436 /* trim to multibyte letter boundary */
1437 buflen = pg_mbcliplen(buf, buflen, buflen);
1442 /* already word boundary? */
1443 if (line[buflen] != '\0' &&
1444 !isspace((unsigned char) line[buflen]))
1446 /* try to divide at word boundary */
1448 while (i > 0 && !isspace((unsigned char) buf[i]))
1451 if (i > 0) /* else couldn't divide word boundary */
1460 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1467 /* message short enough */
1468 syslog(level, "[%lu] %s", seq, line);
1471 #endif /* HAVE_SYSLOG */
1475 * Write a message line to the windows event log
1478 write_eventlog(int level, const char *line)
1480 int eventlevel = EVENTLOG_ERROR_TYPE;
1481 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1483 if (evtHandle == INVALID_HANDLE_VALUE)
1485 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1486 if (evtHandle == NULL)
1488 evtHandle = INVALID_HANDLE_VALUE;
1504 eventlevel = EVENTLOG_INFORMATION_TYPE;
1507 eventlevel = EVENTLOG_WARNING_TYPE;
1513 eventlevel = EVENTLOG_ERROR_TYPE;
1518 ReportEvent(evtHandle,
1521 0, /* All events are Id 0 */
1531 * setup formatted_log_time, for consistent times between CSV and regular logs
1534 setup_formatted_log_time(void)
1537 pg_time_t stamp_time;
1541 gettimeofday(&tv, NULL);
1542 stamp_time = (pg_time_t) tv.tv_sec;
1545 * Normally we print log timestamps in log_timezone, but during startup we
1546 * could get here before that's set. If so, fall back to gmt_timezone
1547 * (which guc.c ensures is set up before Log_line_prefix can become
1550 tz = log_timezone ? log_timezone : gmt_timezone;
1552 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1553 /* leave room for milliseconds... */
1554 "%Y-%m-%d %H:%M:%S %Z",
1555 pg_localtime(&stamp_time, tz));
1557 /* 'paste' milliseconds into place... */
1558 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1559 strncpy(formatted_log_time + 19, msbuf, 4);
1563 * setup formatted_start_time
1566 setup_formatted_start_time(void)
1568 pg_time_t stamp_time = (pg_time_t) MyStartTime;
1572 * Normally we print log timestamps in log_timezone, but during startup we
1573 * could get here before that's set. If so, fall back to gmt_timezone
1574 * (which guc.c ensures is set up before Log_line_prefix can become
1577 tz = log_timezone ? log_timezone : gmt_timezone;
1579 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1580 "%Y-%m-%d %H:%M:%S %Z",
1581 pg_localtime(&stamp_time, tz));
1585 * Format tag info for log lines; append to the provided buffer.
1588 log_line_prefix(StringInfo buf)
1590 /* static counter for line numbers */
1591 static long log_line_number = 0;
1593 /* has counter been reset in current process? */
1594 static int log_my_pid = 0;
1600 * This is one of the few places where we'd rather not inherit a static
1601 * variable's value from the postmaster. But since we will, reset it when
1602 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1603 * reset the formatted start timestamp too.
1605 if (log_my_pid != MyProcPid)
1607 log_line_number = 0;
1608 log_my_pid = MyProcPid;
1609 formatted_start_time[0] = '\0';
1613 if (Log_line_prefix == NULL)
1614 return; /* in case guc hasn't run yet */
1616 format_len = strlen(Log_line_prefix);
1618 for (i = 0; i < format_len; i++)
1620 if (Log_line_prefix[i] != '%')
1622 /* literal char, just copy */
1623 appendStringInfoChar(buf, Log_line_prefix[i]);
1626 /* go to char after '%' */
1628 if (i >= format_len)
1629 break; /* format error - ignore it */
1631 /* process the option */
1632 switch (Log_line_prefix[i])
1637 const char *username = MyProcPort->user_name;
1639 if (username == NULL || *username == '\0')
1640 username = _("[unknown]");
1641 appendStringInfo(buf, "%s", username);
1647 const char *dbname = MyProcPort->database_name;
1649 if (dbname == NULL || *dbname == '\0')
1650 dbname = _("[unknown]");
1651 appendStringInfo(buf, "%s", dbname);
1655 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1658 appendStringInfo(buf, "%d", MyProcPid);
1661 appendStringInfo(buf, "%ld", log_line_number);
1664 setup_formatted_log_time();
1665 appendStringInfoString(buf, formatted_log_time);
1669 pg_time_t stamp_time = (pg_time_t) time(NULL);
1673 tz = log_timezone ? log_timezone : gmt_timezone;
1675 pg_strftime(strfbuf, sizeof(strfbuf),
1676 "%Y-%m-%d %H:%M:%S %Z",
1677 pg_localtime(&stamp_time, tz));
1678 appendStringInfoString(buf, strfbuf);
1682 if (formatted_start_time[0] == '\0')
1683 setup_formatted_start_time();
1684 appendStringInfoString(buf, formatted_start_time);
1692 psdisp = get_ps_display(&displen);
1693 appendStringInfo(buf, "%.*s", displen, psdisp);
1697 if (MyProcPort && MyProcPort->remote_host)
1699 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1700 if (MyProcPort->remote_port &&
1701 MyProcPort->remote_port[0] != '\0')
1702 appendStringInfo(buf, "(%s)",
1703 MyProcPort->remote_port);
1707 if (MyProcPort && MyProcPort->remote_host)
1708 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1711 /* in postmaster and friends, stop if %q is seen */
1712 /* in a backend, just ignore */
1713 if (MyProcPort == NULL)
1717 /* keep VXID format in sync with lockfuncs.c */
1718 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1719 appendStringInfo(buf, "%d/%u",
1720 MyProc->backendId, MyProc->lxid);
1723 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1726 appendStringInfoChar(buf, '%');
1729 /* format error - ignore it */
1736 * append a CSV'd version of a string to a StringInfo
1737 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1738 * If it's NULL, append nothing.
1741 appendCSVLiteral(StringInfo buf, const char *data)
1743 const char *p = data;
1746 /* avoid confusing an empty string with NULL */
1750 appendStringInfoCharMacro(buf, '"');
1751 while ((c = *p++) != '\0')
1754 appendStringInfoCharMacro(buf, '"');
1755 appendStringInfoCharMacro(buf, c);
1757 appendStringInfoCharMacro(buf, '"');
1761 * Constructs the error message, depending on the Errordata it gets, in a CSV
1762 * format which is described in doc/src/sgml/config.sgml.
1765 write_csvlog(ErrorData *edata)
1768 bool print_stmt = false;
1770 /* static counter for line numbers */
1771 static long log_line_number = 0;
1773 /* has counter been reset in current process? */
1774 static int log_my_pid = 0;
1777 * This is one of the few places where we'd rather not inherit a static
1778 * variable's value from the postmaster. But since we will, reset it when
1779 * MyProcPid changes.
1781 if (log_my_pid != MyProcPid)
1783 log_line_number = 0;
1784 log_my_pid = MyProcPid;
1785 formatted_start_time[0] = '\0';
1789 initStringInfo(&buf);
1792 * timestamp with milliseconds
1794 * Check if the timestamp is already calculated for the syslog message,
1795 * and use it if so. Otherwise, get the current timestamp. This is done
1796 * to put same timestamp in both syslog and csvlog messages.
1798 if (formatted_log_time[0] == '\0')
1799 setup_formatted_log_time();
1801 appendStringInfoString(&buf, formatted_log_time);
1802 appendStringInfoChar(&buf, ',');
1806 appendCSVLiteral(&buf, MyProcPort->user_name);
1807 appendStringInfoChar(&buf, ',');
1811 appendCSVLiteral(&buf, MyProcPort->database_name);
1812 appendStringInfoChar(&buf, ',');
1816 appendStringInfo(&buf, "%d", MyProcPid);
1817 appendStringInfoChar(&buf, ',');
1819 /* Remote host and port */
1820 if (MyProcPort && MyProcPort->remote_host)
1822 appendStringInfoChar(&buf, '"');
1823 appendStringInfo(&buf, "%s", MyProcPort->remote_host);
1824 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
1825 appendStringInfo(&buf, ":%s", MyProcPort->remote_port);
1826 appendStringInfoChar(&buf, '"');
1828 appendStringInfoChar(&buf, ',');
1831 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
1832 appendStringInfoChar(&buf, ',');
1835 appendStringInfo(&buf, "%ld", log_line_number);
1836 appendStringInfoChar(&buf, ',');
1841 StringInfoData msgbuf;
1845 initStringInfo(&msgbuf);
1847 psdisp = get_ps_display(&displen);
1848 appendStringInfo(&msgbuf, "%.*s", displen, psdisp);
1849 appendCSVLiteral(&buf, msgbuf.data);
1853 appendStringInfoChar(&buf, ',');
1855 /* session start timestamp */
1856 if (formatted_start_time[0] == '\0')
1857 setup_formatted_start_time();
1858 appendStringInfoString(&buf, formatted_start_time);
1859 appendStringInfoChar(&buf, ',');
1861 /* Virtual transaction id */
1862 /* keep VXID format in sync with lockfuncs.c */
1863 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1864 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
1865 appendStringInfoChar(&buf, ',');
1867 /* Transaction id */
1868 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
1869 appendStringInfoChar(&buf, ',');
1871 /* Error severity */
1872 appendStringInfo(&buf, "%s", error_severity(edata->elevel));
1873 appendStringInfoChar(&buf, ',');
1875 /* SQL state code */
1876 appendStringInfo(&buf, "%s", unpack_sql_state(edata->sqlerrcode));
1877 appendStringInfoChar(&buf, ',');
1880 appendCSVLiteral(&buf, edata->message);
1881 appendStringInfoCharMacro(&buf, ',');
1883 /* errdetail or errdetail_log */
1884 if (edata->detail_log)
1885 appendCSVLiteral(&buf, edata->detail_log);
1887 appendCSVLiteral(&buf, edata->detail);
1888 appendStringInfoCharMacro(&buf, ',');
1891 appendCSVLiteral(&buf, edata->hint);
1892 appendStringInfoCharMacro(&buf, ',');
1894 /* internal query */
1895 appendCSVLiteral(&buf, edata->internalquery);
1896 appendStringInfoCharMacro(&buf, ',');
1898 /* if printed internal query, print internal pos too */
1899 if (edata->internalpos > 0 && edata->internalquery != NULL)
1900 appendStringInfo(&buf, "%d", edata->internalpos);
1901 appendStringInfoCharMacro(&buf, ',');
1904 appendCSVLiteral(&buf, edata->context);
1905 appendStringInfoCharMacro(&buf, ',');
1907 /* user query --- only reported if not disabled by the caller */
1908 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1909 debug_query_string != NULL &&
1913 appendCSVLiteral(&buf, debug_query_string);
1914 appendStringInfoCharMacro(&buf, ',');
1915 if (print_stmt && edata->cursorpos > 0)
1916 appendStringInfo(&buf, "%d", edata->cursorpos);
1917 appendStringInfoCharMacro(&buf, ',');
1919 /* file error location */
1920 if (Log_error_verbosity >= PGERROR_VERBOSE)
1922 StringInfoData msgbuf;
1924 initStringInfo(&msgbuf);
1926 if (edata->funcname && edata->filename)
1927 appendStringInfo(&msgbuf, "%s, %s:%d",
1928 edata->funcname, edata->filename,
1930 else if (edata->filename)
1931 appendStringInfo(&msgbuf, "%s:%d",
1932 edata->filename, edata->lineno);
1933 appendCSVLiteral(&buf, msgbuf.data);
1937 appendStringInfoChar(&buf, '\n');
1939 /* If in the syslogger process, try to write messages direct to file */
1941 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1943 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1949 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
1953 unpack_sql_state(int sql_state)
1955 static char buf[12];
1958 for (i = 0; i < 5; i++)
1960 buf[i] = PGUNSIXBIT(sql_state);
1970 * Write error report to server's log
1973 send_message_to_server_log(ErrorData *edata)
1977 initStringInfo(&buf);
1979 formatted_log_time[0] = '\0';
1981 log_line_prefix(&buf);
1982 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1984 if (Log_error_verbosity >= PGERROR_VERBOSE)
1985 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
1988 append_with_tabs(&buf, edata->message);
1990 append_with_tabs(&buf, _("missing error text"));
1992 if (edata->cursorpos > 0)
1993 appendStringInfo(&buf, _(" at character %d"),
1995 else if (edata->internalpos > 0)
1996 appendStringInfo(&buf, _(" at character %d"),
1997 edata->internalpos);
1999 appendStringInfoChar(&buf, '\n');
2001 if (Log_error_verbosity >= PGERROR_DEFAULT)
2003 if (edata->detail_log)
2005 log_line_prefix(&buf);
2006 appendStringInfoString(&buf, _("DETAIL: "));
2007 append_with_tabs(&buf, edata->detail_log);
2008 appendStringInfoChar(&buf, '\n');
2010 else if (edata->detail)
2012 log_line_prefix(&buf);
2013 appendStringInfoString(&buf, _("DETAIL: "));
2014 append_with_tabs(&buf, edata->detail);
2015 appendStringInfoChar(&buf, '\n');
2019 log_line_prefix(&buf);
2020 appendStringInfoString(&buf, _("HINT: "));
2021 append_with_tabs(&buf, edata->hint);
2022 appendStringInfoChar(&buf, '\n');
2024 if (edata->internalquery)
2026 log_line_prefix(&buf);
2027 appendStringInfoString(&buf, _("QUERY: "));
2028 append_with_tabs(&buf, edata->internalquery);
2029 appendStringInfoChar(&buf, '\n');
2033 log_line_prefix(&buf);
2034 appendStringInfoString(&buf, _("CONTEXT: "));
2035 append_with_tabs(&buf, edata->context);
2036 appendStringInfoChar(&buf, '\n');
2038 if (Log_error_verbosity >= PGERROR_VERBOSE)
2040 /* assume no newlines in funcname or filename... */
2041 if (edata->funcname && edata->filename)
2043 log_line_prefix(&buf);
2044 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2045 edata->funcname, edata->filename,
2048 else if (edata->filename)
2050 log_line_prefix(&buf);
2051 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2052 edata->filename, edata->lineno);
2058 * If the user wants the query that generated this error logged, do it.
2060 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2061 debug_query_string != NULL &&
2064 log_line_prefix(&buf);
2065 appendStringInfoString(&buf, _("STATEMENT: "));
2066 append_with_tabs(&buf, debug_query_string);
2067 appendStringInfoChar(&buf, '\n');
2071 /* Write to syslog, if enabled */
2072 if (Log_destination & LOG_DESTINATION_SYSLOG)
2076 switch (edata->elevel)
2083 syslog_level = LOG_DEBUG;
2088 syslog_level = LOG_INFO;
2092 syslog_level = LOG_NOTICE;
2095 syslog_level = LOG_WARNING;
2098 syslog_level = LOG_ERR;
2102 syslog_level = LOG_CRIT;
2106 write_syslog(syslog_level, buf.data);
2108 #endif /* HAVE_SYSLOG */
2111 /* Write to eventlog, if enabled */
2112 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2114 write_eventlog(edata->elevel, buf.data);
2118 /* Write to stderr, if enabled */
2119 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2122 * Use the chunking protocol if we know the syslogger should be
2123 * catching stderr output, and we are not ourselves the syslogger.
2124 * Otherwise, just do a vanilla write to stderr.
2126 if (redirection_done && !am_syslogger)
2127 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2131 * In a win32 service environment, there is no usable stderr. Capture
2132 * anything going there and write it to the eventlog instead.
2134 * If stderr redirection is active, it was OK to write to stderr above
2135 * because that's really a pipe to the syslogger process.
2137 else if (pgwin32_is_service())
2138 write_eventlog(edata->elevel, buf.data);
2141 write(fileno(stderr), buf.data, buf.len);
2144 /* If in the syslogger process, try to write messages direct to file */
2146 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2148 /* Write to CSV log if enabled */
2149 if (Log_destination & LOG_DESTINATION_CSVLOG)
2151 if (redirection_done || am_syslogger)
2154 * send CSV data if it's safe to do so (syslogger doesn't need the
2155 * pipe). First get back the space in the message buffer.
2158 write_csvlog(edata);
2162 const char *msg = _("Not safe to send CSV data\n");
2164 write(fileno(stderr), msg, strlen(msg));
2165 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2166 whereToSendOutput != DestDebug)
2168 /* write message to stderr unless we just sent it above */
2169 write(fileno(stderr), buf.data, buf.len);
2181 * Send data to the syslogger using the chunked protocol
2184 write_pipe_chunks(char *data, int len, int dest)
2188 int fd = fileno(stderr);
2192 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2193 p.proto.pid = MyProcPid;
2195 /* write all but the last chunk */
2196 while (len > PIPE_MAX_PAYLOAD)
2198 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2199 p.proto.len = PIPE_MAX_PAYLOAD;
2200 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2201 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2202 data += PIPE_MAX_PAYLOAD;
2203 len -= PIPE_MAX_PAYLOAD;
2206 /* write the last chunk */
2207 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2209 memcpy(p.proto.data, data, len);
2210 write(fd, &p, PIPE_HEADER_SIZE + len);
2215 * Append a text string to the error report being built for the client.
2217 * This is ordinarily identical to pq_sendstring(), but if we are in
2218 * error recursion trouble we skip encoding conversion, because of the
2219 * possibility that the problem is a failure in the encoding conversion
2220 * subsystem itself. Code elsewhere should ensure that the passed-in
2221 * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2222 * in such cases. (In particular, we disable localization of error messages
2223 * to help ensure that's true.)
2226 err_sendstring(StringInfo buf, const char *str)
2228 if (in_error_recursion_trouble())
2229 pq_send_ascii_string(buf, str);
2231 pq_sendstring(buf, str);
2235 * Write error report to client
2238 send_message_to_frontend(ErrorData *edata)
2240 StringInfoData msgbuf;
2242 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2243 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2245 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2247 /* New style with separate fields */
2252 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2253 err_sendstring(&msgbuf, error_severity(edata->elevel));
2255 /* unpack MAKE_SQLSTATE code */
2256 ssval = edata->sqlerrcode;
2257 for (i = 0; i < 5; i++)
2259 tbuf[i] = PGUNSIXBIT(ssval);
2264 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2265 err_sendstring(&msgbuf, tbuf);
2267 /* M field is required per protocol, so always send something */
2268 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2270 err_sendstring(&msgbuf, edata->message);
2272 err_sendstring(&msgbuf, _("missing error text"));
2276 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2277 err_sendstring(&msgbuf, edata->detail);
2280 /* detail_log is intentionally not used here */
2284 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2285 err_sendstring(&msgbuf, edata->hint);
2290 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2291 err_sendstring(&msgbuf, edata->context);
2294 if (edata->cursorpos > 0)
2296 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2297 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2298 err_sendstring(&msgbuf, tbuf);
2301 if (edata->internalpos > 0)
2303 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2304 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2305 err_sendstring(&msgbuf, tbuf);
2308 if (edata->internalquery)
2310 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2311 err_sendstring(&msgbuf, edata->internalquery);
2314 if (edata->filename)
2316 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2317 err_sendstring(&msgbuf, edata->filename);
2320 if (edata->lineno > 0)
2322 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2323 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2324 err_sendstring(&msgbuf, tbuf);
2327 if (edata->funcname)
2329 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2330 err_sendstring(&msgbuf, edata->funcname);
2333 pq_sendbyte(&msgbuf, '\0'); /* terminator */
2337 /* Old style --- gin up a backwards-compatible message */
2340 initStringInfo(&buf);
2342 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2344 if (edata->show_funcname && edata->funcname)
2345 appendStringInfo(&buf, "%s: ", edata->funcname);
2348 appendStringInfoString(&buf, edata->message);
2350 appendStringInfoString(&buf, _("missing error text"));
2352 if (edata->cursorpos > 0)
2353 appendStringInfo(&buf, _(" at character %d"),
2355 else if (edata->internalpos > 0)
2356 appendStringInfo(&buf, _(" at character %d"),
2357 edata->internalpos);
2359 appendStringInfoChar(&buf, '\n');
2361 err_sendstring(&msgbuf, buf.data);
2366 pq_endmessage(&msgbuf);
2369 * This flush is normally not necessary, since postgres.c will flush out
2370 * waiting data when control returns to the main loop. But it seems best
2371 * to leave it here, so that the client has some clue what happened if the
2372 * backend dies before getting back to the main loop ... error/notice
2373 * messages should not be a performance-critical path anyway, so an extra
2374 * flush won't hurt much ...
2381 * Support routines for formatting error messages.
2386 * expand_fmt_string --- process special format codes in a format string
2388 * We must replace %m with the appropriate strerror string, since vsnprintf
2389 * won't know what to do with it.
2391 * The result is a palloc'd string.
2394 expand_fmt_string(const char *fmt, ErrorData *edata)
2399 initStringInfo(&buf);
2401 for (cp = fmt; *cp; cp++)
2403 if (cp[0] == '%' && cp[1] != '\0')
2409 * Replace %m by system error string. If there are any %'s in
2410 * the string, we'd better double them so that vsnprintf won't
2415 cp2 = useful_strerror(edata->saved_errno);
2419 appendStringInfoCharMacro(&buf, '%');
2420 appendStringInfoCharMacro(&buf, *cp2);
2425 /* copy % and next char --- this avoids trouble with %%m */
2426 appendStringInfoCharMacro(&buf, '%');
2427 appendStringInfoCharMacro(&buf, *cp);
2431 appendStringInfoCharMacro(&buf, *cp);
2439 * A slightly cleaned-up version of strerror()
2442 useful_strerror(int errnum)
2444 /* this buffer is only used if errno has a bogus value */
2445 static char errorstr_buf[48];
2449 /* Winsock error code range, per WinError.h */
2450 if (errnum >= 10000 && errnum <= 11999)
2451 return pgwin32_socket_strerror(errnum);
2453 str = strerror(errnum);
2456 * Some strerror()s return an empty string for out-of-range errno. This is
2457 * ANSI C spec compliant, but not exactly useful.
2459 if (str == NULL || *str == '\0')
2461 snprintf(errorstr_buf, sizeof(errorstr_buf),
2463 translator: This string will be truncated at 47
2464 characters expanded. */
2465 _("operating system error %d"), errnum);
2474 * error_severity --- get localized string representing elevel
2477 error_severity(int elevel)
2488 prefix = _("DEBUG");
2498 prefix = _("NOTICE");
2501 prefix = _("WARNING");
2504 prefix = _("ERROR");
2507 prefix = _("FATAL");
2510 prefix = _("PANIC");
2524 * Append the string to the StringInfo buffer, inserting a tab after any
2528 append_with_tabs(StringInfo buf, const char *str)
2532 while ((ch = *str++) != '\0')
2534 appendStringInfoCharMacro(buf, ch);
2536 appendStringInfoCharMacro(buf, '\t');
2542 * Write errors to stderr (or by equal means when stderr is
2543 * not available). Used before ereport/elog can be used
2544 * safely (memory context, GUC load etc)
2547 write_stderr(const char *fmt,...)
2555 /* On Unix, we just fprintf to stderr */
2556 vfprintf(stderr, fmt, ap);
2561 * On Win32, we print to stderr if running on a console, or write to
2562 * eventlog if running as a service
2564 if (pgwin32_is_service()) /* Running as a service */
2566 char errbuf[2048]; /* Arbitrary size? */
2568 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2570 write_eventlog(ERROR, errbuf);
2574 /* Not running as service, write to stderr */
2575 vfprintf(stderr, fmt, ap);
2584 * is_log_level_output -- is elevel logically >= log_min_level?
2586 * We use this for tests that should consider LOG to sort out-of-order,
2587 * between ERROR and FATAL. Generally this is the right thing for testing
2588 * whether a message should go to the postmaster log, whereas a simple >=
2589 * test is correct for testing whether the message should go to the client.
2592 is_log_level_output(int elevel, int log_min_level)
2594 if (elevel == LOG || elevel == COMMERROR)
2596 if (log_min_level == LOG || log_min_level <= ERROR)
2599 else if (log_min_level == LOG)
2602 if (elevel >= FATAL)
2605 /* Neither is LOG */
2606 else if (elevel >= log_min_level)