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-2007, 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.198 2007/11/15 21:14:40 momjian 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"
75 /* Global variables */
76 ErrorContextCallback *error_context_stack = NULL;
78 sigjmp_buf *PG_exception_stack = NULL;
80 extern bool redirection_done;
83 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
84 char *Log_line_prefix = NULL; /* format for extra log line info */
85 int Log_destination = LOG_DESTINATION_STDERR;
88 static bool openlog_done = false;
89 static char *syslog_ident = NULL;
90 static int syslog_facility = LOG_LOCAL0;
92 static void write_syslog(int level, const char *line);
96 static void write_eventlog(int level, const char *line);
99 /* We provide a small stack of ErrorData records for re-entrant cases */
100 #define ERRORDATA_STACK_SIZE 5
102 static ErrorData errordata[ERRORDATA_STACK_SIZE];
104 static int errordata_stack_depth = -1; /* index of topmost active frame */
106 static int recursion_depth = 0; /* to detect actual recursion */
108 /* buffers for formatted timestamps that might be used by both
109 * log_line_prefix and csv logs.
112 #define FORMATTED_TS_LEN 128
113 static char formatted_start_time[FORMATTED_TS_LEN];
114 static char formatted_log_time[FORMATTED_TS_LEN];
117 /* Macro for checking errordata_stack_depth is reasonable */
118 #define CHECK_STACK_DEPTH() \
120 if (errordata_stack_depth < 0) \
122 errordata_stack_depth = -1; \
123 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
128 static void log_line_prefix(StringInfo buf);
129 static void send_message_to_server_log(ErrorData *edata);
130 static void send_message_to_frontend(ErrorData *edata);
131 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
132 static const char *useful_strerror(int errnum);
133 static const char *error_severity(int elevel);
134 static void append_with_tabs(StringInfo buf, const char *str);
135 static bool is_log_level_output(int elevel, int log_min_level);
136 static void write_pipe_chunks(char *data, int len, int dest);
137 static void get_csv_error_message(StringInfo buf, ErrorData *edata);
138 static void write_csvlog(ErrorData *edata);
141 * errstart --- begin an error-reporting cycle
143 * Create a stack entry and store the given parameters in it. Subsequently,
144 * errmsg() and perhaps other routines will be called to further populate
145 * the stack entry. Finally, errfinish() will be called to actually process
148 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
149 * report (if it's a warning or lower and not to be reported anywhere).
152 errstart(int elevel, const char *filename, int lineno,
153 const char *funcname)
156 bool output_to_server;
157 bool output_to_client = false;
161 * Check some cases in which we want to promote an error into a more
162 * severe error. None of this logic applies for non-error messages.
167 * If we are inside a critical section, all errors become PANIC
168 * errors. See miscadmin.h.
170 if (CritSectionCount > 0)
174 * Check reasons for treating ERROR as FATAL:
176 * 1. we have no handler to pass the error to (implies we are in the
177 * postmaster or in backend startup).
179 * 2. ExitOnAnyError mode switch is set (initdb uses this).
181 * 3. the error occurred after proc_exit has begun to run. (It's
182 * proc_exit's responsibility to see that this doesn't turn into
183 * infinite recursion!)
187 if (PG_exception_stack == NULL ||
189 proc_exit_inprogress)
194 * If the error level is ERROR or more, errfinish is not going to
195 * return to caller; therefore, if there is any stacked error already
196 * in progress it will be lost. This is more or less okay, except we
197 * do not want to have a FATAL or PANIC error downgraded because the
198 * reporting process was interrupted by a lower-grade error. So check
199 * the stack and make sure we panic if panic is warranted.
201 for (i = 0; i <= errordata_stack_depth; i++)
202 elevel = Max(elevel, errordata[i].elevel);
206 * Now decide whether we need to process this report at all; if it's
207 * warning or less and not enabled for logging, just return FALSE without
208 * starting up any error logging machinery.
211 /* Determine whether message is enabled for server log output */
212 if (IsPostmasterEnvironment)
213 output_to_server = is_log_level_output(elevel, log_min_messages);
215 /* In bootstrap/standalone case, do not sort LOG out-of-order */
216 output_to_server = (elevel >= log_min_messages);
218 /* Determine whether message is enabled for client output */
219 if (whereToSendOutput == DestRemote && elevel != COMMERROR)
222 * client_min_messages is honored only after we complete the
223 * authentication handshake. This is required both for security
224 * reasons and because many clients can't handle NOTICE messages
225 * during authentication.
227 if (ClientAuthInProgress)
228 output_to_client = (elevel >= ERROR);
230 output_to_client = (elevel >= client_min_messages ||
234 /* Skip processing effort if non-error message will not be output */
235 if (elevel < ERROR && !output_to_server && !output_to_client)
239 * Okay, crank up a stack entry to store the info in.
242 if (recursion_depth++ > 0 && elevel >= ERROR)
245 * Ooops, error during error processing. Clear ErrorContext as
246 * discussed at top of file. We will not return to the original
247 * error's reporter or handler, so we don't need it.
249 MemoryContextReset(ErrorContext);
252 * If we recurse more than once, the problem might be something broken
253 * in a context traceback routine. Abandon them too. We also abandon
254 * attempting to print the error statement (which, if long, could
255 * itself be the source of the recursive failure).
257 if (recursion_depth > 2)
259 error_context_stack = NULL;
260 debug_query_string = NULL;
263 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
266 * Wups, stack not big enough. We treat this as a PANIC condition
267 * because it suggests an infinite loop of errors during error
270 errordata_stack_depth = -1; /* make room on stack */
271 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
274 /* Initialize data for this error frame */
275 edata = &errordata[errordata_stack_depth];
276 MemSet(edata, 0, sizeof(ErrorData));
277 edata->elevel = elevel;
278 edata->output_to_server = output_to_server;
279 edata->output_to_client = output_to_client;
280 edata->filename = filename;
281 edata->lineno = lineno;
282 edata->funcname = funcname;
283 /* Select default errcode based on elevel */
285 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
286 else if (elevel == WARNING)
287 edata->sqlerrcode = ERRCODE_WARNING;
289 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
290 /* errno is saved here so that error parameter eval can't change it */
291 edata->saved_errno = errno;
298 * errfinish --- end an error-reporting cycle
300 * Produce the appropriate error report(s) and pop the error stack.
302 * If elevel is ERROR or worse, control does not return to the caller.
303 * See elog.h for the error level definitions.
306 errfinish(int dummy,...)
308 ErrorData *edata = &errordata[errordata_stack_depth];
309 int elevel = edata->elevel;
310 MemoryContext oldcontext;
311 ErrorContextCallback *econtext;
317 * Do processing in ErrorContext, which we hope has enough reserved space
318 * to report an error.
320 oldcontext = MemoryContextSwitchTo(ErrorContext);
323 * Call any context callback functions. Errors occurring in callback
324 * functions will be treated as recursive errors --- this ensures we will
325 * avoid infinite recursion (see errstart).
327 for (econtext = error_context_stack;
329 econtext = econtext->previous)
330 (*econtext->callback) (econtext->arg);
333 * If ERROR (not more nor less) we pass it off to the current handler.
334 * Printing it and popping the stack is the responsibility of the handler.
339 * We do some minimal cleanup before longjmp'ing so that handlers can
340 * execute in a reasonably sane state.
343 /* This is just in case the error came while waiting for input */
344 ImmediateInterruptOK = false;
347 * Reset InterruptHoldoffCount in case we ereport'd from inside an
348 * interrupt holdoff section. (We assume here that no handler will
349 * itself be inside a holdoff section. If necessary, such a handler
350 * could save and restore InterruptHoldoffCount for itself, but this
351 * should make life easier for most.)
353 InterruptHoldoffCount = 0;
355 CritSectionCount = 0; /* should be unnecessary, but... */
358 * Note that we leave CurrentMemoryContext set to ErrorContext. The
359 * handler should reset it to something else soon.
367 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
368 * progress, so that we can report the message before dying. (Without
369 * this, pq_putmessage will refuse to send the message at all, which is
370 * what we want for NOTICE messages, but not for fatal exits.) This hack
371 * is necessary because of poor design of old-style copy protocol. Note
372 * we must do this even if client is fool enough to have set
373 * client_min_messages above FATAL, so don't look at output_to_client.
375 if (elevel >= FATAL && whereToSendOutput == DestRemote)
378 /* Emit the message to the right places */
381 /* Now free up subsidiary data attached to stack entry, and release it */
383 pfree(edata->message);
385 pfree(edata->detail);
389 pfree(edata->context);
390 if (edata->internalquery)
391 pfree(edata->internalquery);
393 errordata_stack_depth--;
395 /* Exit error-handling context */
396 MemoryContextSwitchTo(oldcontext);
400 * Perform error recovery action as specified by elevel.
405 * For a FATAL error, we let proc_exit clean up and exit.
407 ImmediateInterruptOK = false;
410 * If we just reported a startup failure, the client will disconnect
411 * on receiving it, so don't send any more to the client.
413 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
414 whereToSendOutput = DestNone;
417 * fflush here is just to improve the odds that we get to see the
418 * error message, in case things are so hosed that proc_exit crashes.
419 * Any other code you might be tempted to add here should probably be
420 * in an on_proc_exit or on_shmem_exit callback instead.
426 * Do normal process-exit cleanup, then return exit code 1 to indicate
427 * FATAL termination. The postmaster may or may not consider this
428 * worthy of panic, depending on which subprocess returns it.
436 * Serious crash time. Postmaster will observe SIGABRT process exit
437 * status and kill the other backends too.
439 * XXX: what if we are *in* the postmaster? abort() won't kill our
442 ImmediateInterruptOK = false;
449 * We reach here if elevel <= WARNING. OK to return to caller.
451 * But check for cancel/die interrupt first --- this is so that the user
452 * can stop a query emitting tons of notice or warning messages, even if
453 * it's in a loop that otherwise fails to check for interrupts.
455 CHECK_FOR_INTERRUPTS();
460 * errcode --- add SQLSTATE error code to the current error
462 * The code is expected to be represented as per MAKE_SQLSTATE().
465 errcode(int sqlerrcode)
467 ErrorData *edata = &errordata[errordata_stack_depth];
469 /* we don't bother incrementing recursion_depth */
472 edata->sqlerrcode = sqlerrcode;
474 return 0; /* return value does not matter */
479 * errcode_for_file_access --- add SQLSTATE error code to the current error
481 * The SQLSTATE code is chosen based on the saved errno value. We assume
482 * that the failing operation was some type of disk file access.
484 * NOTE: the primary error message string should generally include %m
488 errcode_for_file_access(void)
490 ErrorData *edata = &errordata[errordata_stack_depth];
492 /* we don't bother incrementing recursion_depth */
495 switch (edata->saved_errno)
497 /* Permission-denied failures */
498 case EPERM: /* Not super-user */
499 case EACCES: /* Permission denied */
501 case EROFS: /* Read only file system */
503 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
507 case ENOENT: /* No such file or directory */
508 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
512 case EEXIST: /* File exists */
513 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
516 /* Wrong object type or state */
517 case ENOTDIR: /* Not a directory */
518 case EISDIR: /* Is a directory */
519 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
520 case ENOTEMPTY: /* Directory not empty */
522 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
525 /* Insufficient resources */
526 case ENOSPC: /* No space left on device */
527 edata->sqlerrcode = ERRCODE_DISK_FULL;
530 case ENFILE: /* File table overflow */
531 case EMFILE: /* Too many open files */
532 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
535 /* Hardware failure */
536 case EIO: /* I/O error */
537 edata->sqlerrcode = ERRCODE_IO_ERROR;
540 /* All else is classified as internal errors */
542 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
546 return 0; /* return value does not matter */
550 * errcode_for_socket_access --- add SQLSTATE error code to the current error
552 * The SQLSTATE code is chosen based on the saved errno value. We assume
553 * that the failing operation was some type of socket access.
555 * NOTE: the primary error message string should generally include %m
559 errcode_for_socket_access(void)
561 ErrorData *edata = &errordata[errordata_stack_depth];
563 /* we don't bother incrementing recursion_depth */
566 switch (edata->saved_errno)
568 /* Loss of connection */
573 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
576 /* All else is classified as internal errors */
578 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
582 return 0; /* return value does not matter */
587 * This macro handles expansion of a format string and associated parameters;
588 * it's common code for errmsg(), errdetail(), etc. Must be called inside
589 * a routine that is declared like "const char *fmt, ..." and has an edata
590 * pointer set up. The message is assigned to edata->targetfield, or
591 * appended to it if appendval is true.
593 * Note: we pstrdup the buffer rather than just transferring its storage
594 * to the edata field because the buffer might be considerably larger than
597 #define EVALUATE_MESSAGE(targetfield, appendval) \
600 StringInfoData buf; \
601 /* Internationalize the error format string */ \
603 /* Expand %m in format string */ \
604 fmtbuf = expand_fmt_string(fmt, edata); \
605 initStringInfo(&buf); \
606 if ((appendval) && edata->targetfield) \
607 appendStringInfo(&buf, "%s\n", edata->targetfield); \
608 /* Generate actual output --- have to use appendStringInfoVA */ \
613 va_start(args, fmt); \
614 success = appendStringInfoVA(&buf, fmtbuf, args); \
618 enlargeStringInfo(&buf, buf.maxlen); \
620 /* Done with expanded fmt */ \
622 /* Save the completed message into the stack item */ \
623 if (edata->targetfield) \
624 pfree(edata->targetfield); \
625 edata->targetfield = pstrdup(buf.data); \
631 * errmsg --- add a primary error message text to the current error
633 * In addition to the usual %-escapes recognized by printf, "%m" in
634 * fmt is replaced by the error message for the caller's value of errno.
636 * Note: no newline is needed at the end of the fmt string, since
637 * ereport will provide one for the output methods that need it.
640 errmsg(const char *fmt,...)
642 ErrorData *edata = &errordata[errordata_stack_depth];
643 MemoryContext oldcontext;
647 oldcontext = MemoryContextSwitchTo(ErrorContext);
649 EVALUATE_MESSAGE(message, false);
651 MemoryContextSwitchTo(oldcontext);
653 return 0; /* return value does not matter */
658 * errmsg_internal --- add a primary error message text to the current error
660 * This is exactly like errmsg() except that strings passed to errmsg_internal
661 * are customarily left out of the internationalization message dictionary.
662 * This should be used for "can't happen" cases that are probably not worth
663 * spending translation effort on.
666 errmsg_internal(const char *fmt,...)
668 ErrorData *edata = &errordata[errordata_stack_depth];
669 MemoryContext oldcontext;
673 oldcontext = MemoryContextSwitchTo(ErrorContext);
675 EVALUATE_MESSAGE(message, false);
677 MemoryContextSwitchTo(oldcontext);
679 return 0; /* return value does not matter */
684 * errdetail --- add a detail error message text to the current error
687 errdetail(const char *fmt,...)
689 ErrorData *edata = &errordata[errordata_stack_depth];
690 MemoryContext oldcontext;
694 oldcontext = MemoryContextSwitchTo(ErrorContext);
696 EVALUATE_MESSAGE(detail, false);
698 MemoryContextSwitchTo(oldcontext);
700 return 0; /* return value does not matter */
705 * errhint --- add a hint error message text to the current error
708 errhint(const char *fmt,...)
710 ErrorData *edata = &errordata[errordata_stack_depth];
711 MemoryContext oldcontext;
715 oldcontext = MemoryContextSwitchTo(ErrorContext);
717 EVALUATE_MESSAGE(hint, false);
719 MemoryContextSwitchTo(oldcontext);
721 return 0; /* return value does not matter */
726 * errcontext --- add a context error message text to the current error
728 * Unlike other cases, multiple calls are allowed to build up a stack of
729 * context information. We assume earlier calls represent more-closely-nested
733 errcontext(const char *fmt,...)
735 ErrorData *edata = &errordata[errordata_stack_depth];
736 MemoryContext oldcontext;
740 oldcontext = MemoryContextSwitchTo(ErrorContext);
742 EVALUATE_MESSAGE(context, true);
744 MemoryContextSwitchTo(oldcontext);
746 return 0; /* return value does not matter */
751 * errhidestmt --- optionally suppress STATEMENT: field of log entry
753 * This should be called if the message text already includes the statement.
756 errhidestmt(bool hide_stmt)
758 ErrorData *edata = &errordata[errordata_stack_depth];
760 /* we don't bother incrementing recursion_depth */
763 edata->hide_stmt = hide_stmt;
765 return 0; /* return value does not matter */
770 * errfunction --- add reporting function name to the current error
772 * This is used when backwards compatibility demands that the function
773 * name appear in messages sent to old-protocol clients. Note that the
774 * passed string is expected to be a non-freeable constant string.
777 errfunction(const char *funcname)
779 ErrorData *edata = &errordata[errordata_stack_depth];
781 /* we don't bother incrementing recursion_depth */
784 edata->funcname = funcname;
785 edata->show_funcname = true;
787 return 0; /* return value does not matter */
791 * errposition --- add cursor position to the current error
794 errposition(int cursorpos)
796 ErrorData *edata = &errordata[errordata_stack_depth];
798 /* we don't bother incrementing recursion_depth */
801 edata->cursorpos = cursorpos;
803 return 0; /* return value does not matter */
807 * internalerrposition --- add internal cursor position to the current error
810 internalerrposition(int cursorpos)
812 ErrorData *edata = &errordata[errordata_stack_depth];
814 /* we don't bother incrementing recursion_depth */
817 edata->internalpos = cursorpos;
819 return 0; /* return value does not matter */
823 * internalerrquery --- add internal query text to the current error
825 * Can also pass NULL to drop the internal query text entry. This case
826 * is intended for use in error callback subroutines that are editorializing
827 * on the layout of the error report.
830 internalerrquery(const char *query)
832 ErrorData *edata = &errordata[errordata_stack_depth];
834 /* we don't bother incrementing recursion_depth */
837 if (edata->internalquery)
839 pfree(edata->internalquery);
840 edata->internalquery = NULL;
844 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
846 return 0; /* return value does not matter */
850 * geterrposition --- return the currently set error position (0 if none)
852 * This is only intended for use in error callback subroutines, since there
853 * is no other place outside elog.c where the concept is meaningful.
858 ErrorData *edata = &errordata[errordata_stack_depth];
860 /* we don't bother incrementing recursion_depth */
863 return edata->cursorpos;
867 * getinternalerrposition --- same for internal error position
869 * This is only intended for use in error callback subroutines, since there
870 * is no other place outside elog.c where the concept is meaningful.
873 getinternalerrposition(void)
875 ErrorData *edata = &errordata[errordata_stack_depth];
877 /* we don't bother incrementing recursion_depth */
880 return edata->internalpos;
885 * elog_start --- startup for old-style API
887 * All that we do here is stash the hidden filename/lineno/funcname
888 * arguments into a stack entry.
890 * We need this to be separate from elog_finish because there's no other
891 * portable way to deal with inserting extra arguments into the elog call.
892 * (If macros with variable numbers of arguments were portable, it'd be
893 * easy, but they aren't.)
896 elog_start(const char *filename, int lineno, const char *funcname)
900 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
903 * Wups, stack not big enough. We treat this as a PANIC condition
904 * because it suggests an infinite loop of errors during error
907 errordata_stack_depth = -1; /* make room on stack */
908 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
911 edata = &errordata[errordata_stack_depth];
912 edata->filename = filename;
913 edata->lineno = lineno;
914 edata->funcname = funcname;
915 /* errno is saved now so that error parameter eval can't change it */
916 edata->saved_errno = errno;
920 * elog_finish --- finish up for old-style API
923 elog_finish(int elevel, const char *fmt,...)
925 ErrorData *edata = &errordata[errordata_stack_depth];
926 MemoryContext oldcontext;
931 * Do errstart() to see if we actually want to report the message.
933 errordata_stack_depth--;
934 errno = edata->saved_errno;
935 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
936 return; /* nothing to do */
939 * Format error message just like errmsg().
942 oldcontext = MemoryContextSwitchTo(ErrorContext);
944 EVALUATE_MESSAGE(message, false);
946 MemoryContextSwitchTo(oldcontext);
950 * And let errfinish() finish up.
956 * Actual output of the top-of-stack error message
958 * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
959 * if the error is caught by somebody). For all other severity levels this
960 * is called by errfinish.
963 EmitErrorReport(void)
965 ErrorData *edata = &errordata[errordata_stack_depth];
966 MemoryContext oldcontext;
970 oldcontext = MemoryContextSwitchTo(ErrorContext);
972 /* Send to server log, if enabled */
973 if (edata->output_to_server)
974 send_message_to_server_log(edata);
976 /* Send to client, if enabled */
977 if (edata->output_to_client)
978 send_message_to_frontend(edata);
980 MemoryContextSwitchTo(oldcontext);
985 * CopyErrorData --- obtain a copy of the topmost error stack entry
987 * This is only for use in error handler code. The data is copied into the
988 * current memory context, so callers should always switch away from
989 * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
994 ErrorData *edata = &errordata[errordata_stack_depth];
998 * we don't increment recursion_depth because out-of-memory here does not
999 * indicate a problem within the error subsystem.
1001 CHECK_STACK_DEPTH();
1003 Assert(CurrentMemoryContext != ErrorContext);
1005 /* Copy the struct itself */
1006 newedata = (ErrorData *) palloc(sizeof(ErrorData));
1007 memcpy(newedata, edata, sizeof(ErrorData));
1009 /* Make copies of separately-allocated fields */
1010 if (newedata->message)
1011 newedata->message = pstrdup(newedata->message);
1012 if (newedata->detail)
1013 newedata->detail = pstrdup(newedata->detail);
1015 newedata->hint = pstrdup(newedata->hint);
1016 if (newedata->context)
1017 newedata->context = pstrdup(newedata->context);
1018 if (newedata->internalquery)
1019 newedata->internalquery = pstrdup(newedata->internalquery);
1025 * FreeErrorData --- free the structure returned by CopyErrorData.
1027 * Error handlers should use this in preference to assuming they know all
1028 * the separately-allocated fields.
1031 FreeErrorData(ErrorData *edata)
1034 pfree(edata->message);
1036 pfree(edata->detail);
1040 pfree(edata->context);
1041 if (edata->internalquery)
1042 pfree(edata->internalquery);
1047 * FlushErrorState --- flush the error state after error recovery
1049 * This should be called by an error handler after it's done processing
1050 * the error; or as soon as it's done CopyErrorData, if it intends to
1051 * do stuff that is likely to provoke another error. You are not "out" of
1052 * the error subsystem until you have done this.
1055 FlushErrorState(void)
1058 * Reset stack to empty. The only case where it would be more than one
1059 * deep is if we serviced an error that interrupted construction of
1060 * another message. We assume control escaped out of that message
1061 * construction and won't ever go back.
1063 errordata_stack_depth = -1;
1064 recursion_depth = 0;
1065 /* Delete all data in ErrorContext */
1066 MemoryContextResetAndDeleteChildren(ErrorContext);
1070 * ReThrowError --- re-throw a previously copied error
1072 * A handler can do CopyErrorData/FlushErrorState to get out of the error
1073 * subsystem, then do some processing, and finally ReThrowError to re-throw
1074 * the original error. This is slower than just PG_RE_THROW() but should
1075 * be used if the "some processing" is likely to incur another error.
1078 ReThrowError(ErrorData *edata)
1080 ErrorData *newedata;
1082 Assert(edata->elevel == ERROR);
1084 /* Push the data back into the error context */
1086 MemoryContextSwitchTo(ErrorContext);
1088 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1091 * Wups, stack not big enough. We treat this as a PANIC condition
1092 * because it suggests an infinite loop of errors during error
1095 errordata_stack_depth = -1; /* make room on stack */
1096 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1099 newedata = &errordata[errordata_stack_depth];
1100 memcpy(newedata, edata, sizeof(ErrorData));
1102 /* Make copies of separately-allocated fields */
1103 if (newedata->message)
1104 newedata->message = pstrdup(newedata->message);
1105 if (newedata->detail)
1106 newedata->detail = pstrdup(newedata->detail);
1108 newedata->hint = pstrdup(newedata->hint);
1109 if (newedata->context)
1110 newedata->context = pstrdup(newedata->context);
1111 if (newedata->internalquery)
1112 newedata->internalquery = pstrdup(newedata->internalquery);
1119 * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1124 /* If possible, throw the error to the next outer setjmp handler */
1125 if (PG_exception_stack != NULL)
1126 siglongjmp(*PG_exception_stack, 1);
1130 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1131 * we have now exited only to discover that there is no outer setjmp
1132 * handler to pass the error to. Had the error been thrown outside
1133 * the block to begin with, we'd have promoted the error to FATAL, so
1134 * the correct behavior is to make it FATAL now; that is, emit it and
1135 * then call proc_exit.
1137 ErrorData *edata = &errordata[errordata_stack_depth];
1139 Assert(errordata_stack_depth >= 0);
1140 Assert(edata->elevel == ERROR);
1141 edata->elevel = FATAL;
1144 * At least in principle, the increase in severity could have changed
1145 * where-to-output decisions, so recalculate. This should stay in
1146 * sync with errstart(), which see for comments.
1148 if (IsPostmasterEnvironment)
1149 edata->output_to_server = is_log_level_output(FATAL,
1152 edata->output_to_server = (FATAL >= log_min_messages);
1153 if (whereToSendOutput == DestRemote)
1155 if (ClientAuthInProgress)
1156 edata->output_to_client = true;
1158 edata->output_to_client = (FATAL >= client_min_messages);
1162 * We can use errfinish() for the rest, but we don't want it to call
1163 * any error context routines a second time. Since we know we are
1164 * about to exit, it should be OK to just clear the context stack.
1166 error_context_stack = NULL;
1171 /* We mustn't return... */
1172 ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1173 __FILE__, __LINE__);
1176 * Since ExceptionalCondition isn't declared noreturn because of
1177 * TrapMacro(), we need this to keep gcc from complaining.
1184 * Initialization of error output file
1192 if (OutputFileName[0])
1195 * A debug-output file name was given.
1197 * Make sure we can write the file, and find out if it's a tty.
1199 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1202 (errcode_for_file_access(),
1203 errmsg("could not open file \"%s\": %m", OutputFileName)));
1208 * Redirect our stderr to the debug output file.
1210 if (!freopen(OutputFileName, "a", stderr))
1212 (errcode_for_file_access(),
1213 errmsg("could not reopen file \"%s\" as stderr: %m",
1217 * If the file is a tty and we're running under the postmaster, try to
1218 * send stdout there as well (if it isn't a tty then stderr will block
1219 * out stdout, so we may as well let stdout go wherever it was going
1222 if (istty && IsUnderPostmaster)
1223 if (!freopen(OutputFileName, "a", stdout))
1225 (errcode_for_file_access(),
1226 errmsg("could not reopen file \"%s\" as stdout: %m",
1236 * Set or update the parameters for syslog logging
1239 set_syslog_parameters(const char *ident, int facility)
1242 * guc.c is likely to call us repeatedly with same parameters, so don't
1243 * thrash the syslog connection unnecessarily. Also, we do not re-open
1244 * the connection until needed, since this routine will get called whether
1245 * or not Log_destination actually mentions syslog.
1247 * Note that we make our own copy of the ident string rather than relying
1248 * on guc.c's. This may be overly paranoid, but it ensures that we cannot
1249 * accidentally free a string that syslog is still using.
1251 if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1252 syslog_facility != facility)
1257 openlog_done = false;
1261 syslog_ident = strdup(ident);
1262 /* if the strdup fails, we will cope in write_syslog() */
1263 syslog_facility = facility;
1268 #ifndef PG_SYSLOG_LIMIT
1269 #define PG_SYSLOG_LIMIT 128
1273 * Write a message line to syslog
1276 write_syslog(int level, const char *line)
1278 static unsigned long seq = 0;
1282 /* Open syslog connection if not done yet */
1285 openlog(syslog_ident ? syslog_ident : "postgres",
1286 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1288 openlog_done = true;
1292 * We add a sequence number to each log message to suppress "same"
1298 * Our problem here is that many syslog implementations don't handle long
1299 * messages in an acceptable manner. While this function doesn't help that
1300 * fact, it does work around by splitting up messages into smaller pieces.
1302 * We divide into multiple syslog() calls if message is too long or if the
1303 * message contains embedded NewLine(s) '\n'.
1306 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1312 char buf[PG_SYSLOG_LIMIT + 1];
1317 /* if we start at a newline, move ahead one char */
1318 if (line[0] == '\n')
1325 /* copy one line, or as much as will fit, to buf */
1326 nlpos = strchr(line, '\n');
1328 buflen = nlpos - line;
1331 buflen = Min(buflen, PG_SYSLOG_LIMIT);
1332 memcpy(buf, line, buflen);
1335 /* trim to multibyte letter boundary */
1336 buflen = pg_mbcliplen(buf, buflen, buflen);
1341 /* already word boundary? */
1342 if (line[buflen] != '\0' &&
1343 !isspace((unsigned char) line[buflen]))
1345 /* try to divide at word boundary */
1347 while (i > 0 && !isspace((unsigned char) buf[i]))
1350 if (i > 0) /* else couldn't divide word boundary */
1359 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1366 /* message short enough */
1367 syslog(level, "[%lu] %s", seq, line);
1370 #endif /* HAVE_SYSLOG */
1374 * Write a message line to the windows event log
1377 write_eventlog(int level, const char *line)
1379 int eventlevel = EVENTLOG_ERROR_TYPE;
1380 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1382 if (evtHandle == INVALID_HANDLE_VALUE)
1384 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1385 if (evtHandle == NULL)
1387 evtHandle = INVALID_HANDLE_VALUE;
1403 eventlevel = EVENTLOG_INFORMATION_TYPE;
1406 eventlevel = EVENTLOG_WARNING_TYPE;
1412 eventlevel = EVENTLOG_ERROR_TYPE;
1417 ReportEvent(evtHandle,
1420 0, /* All events are Id 0 */
1430 * Format tag info for log lines; append to the provided buffer.
1433 log_line_prefix(StringInfo buf)
1435 /* static counter for line numbers */
1436 static long log_line_number = 0;
1438 /* has counter been reset in current process? */
1439 static int log_my_pid = 0;
1445 * This is one of the few places where we'd rather not inherit a static
1446 * variable's value from the postmaster. But since we will, reset it when
1447 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1448 * reset the formatted start timestamp too.
1450 if (log_my_pid != MyProcPid)
1452 log_line_number = 0;
1453 log_my_pid = MyProcPid;
1454 formatted_start_time[0] = '\0';
1458 if (Log_line_prefix == NULL)
1459 return; /* in case guc hasn't run yet */
1461 format_len = strlen(Log_line_prefix);
1463 for (i = 0; i < format_len; i++)
1465 if (Log_line_prefix[i] != '%')
1467 /* literal char, just copy */
1468 appendStringInfoChar(buf, Log_line_prefix[i]);
1471 /* go to char after '%' */
1473 if (i >= format_len)
1474 break; /* format error - ignore it */
1476 /* process the option */
1477 switch (Log_line_prefix[i])
1482 const char *username = MyProcPort->user_name;
1484 if (username == NULL || *username == '\0')
1485 username = _("[unknown]");
1486 appendStringInfo(buf, "%s", username);
1492 const char *dbname = MyProcPort->database_name;
1494 if (dbname == NULL || *dbname == '\0')
1495 dbname = _("[unknown]");
1496 appendStringInfo(buf, "%s", dbname);
1500 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1503 appendStringInfo(buf, "%d", MyProcPid);
1506 appendStringInfo(buf, "%ld", log_line_number);
1511 pg_time_t stamp_time;
1515 gettimeofday(&tv, NULL);
1516 stamp_time = (pg_time_t) tv.tv_sec;
1519 * Normally we print log timestamps in log_timezone, but
1520 * during startup we could get here before that's set. If
1521 * so, fall back to gmt_timezone (which guc.c ensures is
1522 * set up before Log_line_prefix can become nonempty).
1524 tz = log_timezone ? log_timezone : gmt_timezone;
1526 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1527 /* leave room for milliseconds... */
1528 "%Y-%m-%d %H:%M:%S %Z",
1529 pg_localtime(&stamp_time, tz));
1531 /* 'paste' milliseconds into place... */
1532 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1533 strncpy(formatted_log_time + 19, msbuf, 4);
1535 appendStringInfoString(buf, formatted_log_time);
1540 pg_time_t stamp_time = (pg_time_t) time(NULL);
1544 tz = log_timezone ? log_timezone : gmt_timezone;
1546 pg_strftime(strfbuf, sizeof(strfbuf),
1547 "%Y-%m-%d %H:%M:%S %Z",
1548 pg_localtime(&stamp_time, tz));
1549 appendStringInfoString(buf, strfbuf);
1553 if (formatted_start_time[0] == '\0')
1555 pg_time_t stamp_time = (pg_time_t) MyStartTime;
1558 tz = log_timezone ? log_timezone : gmt_timezone;
1560 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1561 "%Y-%m-%d %H:%M:%S %Z",
1562 pg_localtime(&stamp_time, tz));
1564 appendStringInfoString(buf, formatted_start_time);
1572 psdisp = get_ps_display(&displen);
1573 appendStringInfo(buf, "%.*s", displen, psdisp);
1577 if (MyProcPort && MyProcPort->remote_host)
1579 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1580 if (MyProcPort->remote_port &&
1581 MyProcPort->remote_port[0] != '\0')
1582 appendStringInfo(buf, "(%s)",
1583 MyProcPort->remote_port);
1587 if (MyProcPort && MyProcPort->remote_host)
1588 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1591 /* in postmaster and friends, stop if %q is seen */
1592 /* in a backend, just ignore */
1593 if (MyProcPort == NULL)
1597 /* keep VXID format in sync with lockfuncs.c */
1599 appendStringInfo(buf, "%d/%u",
1600 MyProc->backendId, MyProc->lxid);
1603 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1606 appendStringInfoChar(buf, '%');
1609 /* format error - ignore it */
1617 * append a CSV'd version of a string to a StringInfo
1618 * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1622 appendCSVLiteral(StringInfo buf, const char *data)
1624 const char *p = data;
1627 appendStringInfoCharMacro(buf, '"');
1628 while ((c = *p++) != '\0')
1631 appendStringInfoCharMacro(buf, '"');
1632 appendStringInfoCharMacro(buf, c);
1634 appendStringInfoCharMacro(buf, '"');
1638 * Constructs the error message, depending on the Errordata it gets,
1639 * in CSV (comma separated values) format. The COPY command
1640 * can then be used to load the messages into a table.
1643 write_csvlog(ErrorData *edata)
1645 StringInfoData msgbuf;
1648 /* static counter for line numbers */
1649 static long log_line_number = 0;
1651 /* has counter been reset in current process? */
1652 static int log_my_pid = 0;
1655 * This is one of the few places where we'd rather not inherit a static
1656 * variable's value from the postmaster. But since we will, reset it when
1657 * MyProcPid changes.
1659 if (log_my_pid != MyProcPid)
1661 log_line_number = 0;
1662 log_my_pid = MyProcPid;
1663 formatted_start_time[0] = '\0';
1667 initStringInfo(&msgbuf);
1668 initStringInfo(&buf);
1671 * The format of the log output in CSV format: timestamp with
1672 * milliseconds, username, databasename, session id, host and port number,
1673 * process id, process line number, command tag, session start time,
1674 * virtual transaction id, regular transaction id, error severity, sql
1675 * state code, error message.
1678 /* timestamp_with_milliseconds */
1681 * Check if the timestamp is already calculated for the syslog message, if
1682 * it is, then no need to calculate it again, will use the same, else get
1683 * the current timestamp. This is done to put same timestamp in both
1684 * syslog and csvlog messages.
1686 if (formatted_log_time[0] == '\0')
1689 pg_time_t stamp_time;
1693 gettimeofday(&tv, NULL);
1694 stamp_time = (pg_time_t) tv.tv_sec;
1697 * Normally we print log timestamps in log_timezone, but during
1698 * startup we could get here before that's set. If so, fall back to
1699 * gmt_timezone (which guc.c ensures is set up before Log_line_prefix
1700 * can become nonempty).
1702 tz = log_timezone ? log_timezone : gmt_timezone;
1704 pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1705 /* leave room for milliseconds... */
1706 "%Y-%m-%d %H:%M:%S %Z",
1707 pg_localtime(&stamp_time, tz));
1709 /* 'paste' milliseconds into place... */
1710 sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1711 strncpy(formatted_log_time + 19, msbuf, 4);
1713 appendStringInfoString(&buf, formatted_log_time);
1714 appendStringInfoChar(&buf, ',');
1719 const char *username = MyProcPort->user_name;
1721 if (username == NULL || *username == '\0')
1722 username = _("[unknown]");
1724 appendCSVLiteral(&buf, username);
1726 appendStringInfoChar(&buf, ',');
1731 const char *dbname = MyProcPort->database_name;
1733 if (dbname == NULL || *dbname == '\0')
1734 dbname = _("[unknown]");
1736 appendCSVLiteral(&buf, dbname);
1738 appendStringInfoChar(&buf, ',');
1741 appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
1742 appendStringInfoChar(&buf, ',');
1744 /* Remote host and port (is it safe to not quote this?) */
1745 if (MyProcPort && MyProcPort->remote_host)
1747 appendStringInfo(&buf, "%s", MyProcPort->remote_host);
1748 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
1749 appendStringInfo(&buf, ":%s", MyProcPort->remote_port);
1751 appendStringInfoChar(&buf, ',');
1755 appendStringInfo(&buf, "%d", MyProcPid);
1756 appendStringInfoChar(&buf, ',');
1759 appendStringInfo(&buf, "%ld", log_line_number);
1760 appendStringInfoChar(&buf, ',');
1768 psdisp = get_ps_display(&displen);
1769 appendStringInfo(&msgbuf, "%.*s", displen, psdisp);
1770 appendCSVLiteral(&buf, msgbuf.data);
1771 resetStringInfo(&msgbuf);
1773 appendStringInfoChar(&buf, ',');
1775 /* session start timestamp */
1776 if (formatted_start_time[0] == '\0')
1778 pg_time_t stamp_time = (pg_time_t) MyStartTime;
1779 pg_tz *tz = log_timezone ? log_timezone : gmt_timezone;
1781 pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1782 "%Y-%m-%d %H:%M:%S %Z",
1783 pg_localtime(&stamp_time, tz));
1785 appendStringInfoString(&buf, formatted_start_time);
1786 appendStringInfoChar(&buf, ',');
1788 /* Virtual transaction id */
1789 /* keep VXID format in sync with lockfuncs.c */
1791 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
1792 appendStringInfoChar(&buf, ',');
1794 /* Transaction id */
1795 appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
1796 appendStringInfoChar(&buf, ',');
1798 /* Error severity */
1799 appendStringInfo(&buf, "%s,", error_severity(edata->elevel));
1801 /* SQL state code */
1802 appendStringInfo(&buf, "%s,", unpack_sql_state(edata->sqlerrcode));
1804 /* Error message and cursor position if any */
1805 get_csv_error_message(&buf, edata);
1807 appendStringInfoChar(&buf, '\n');
1809 /* If in the syslogger process, try to write messages direct to file */
1811 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1813 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1820 * Appends the buffer with the error message and the cursor position, all
1824 get_csv_error_message(StringInfo buf, ErrorData *edata)
1826 char *msg = edata->message ? edata->message : _("missing error text");
1829 appendStringInfoCharMacro(buf, '"');
1831 while ((c = *msg++) != '\0')
1834 appendStringInfoCharMacro(buf, '"');
1835 appendStringInfoCharMacro(buf, c);
1838 if (edata->cursorpos > 0)
1839 appendStringInfo(buf, _(" at character %d"),
1841 else if (edata->internalpos > 0)
1842 appendStringInfo(buf, _(" at character %d"),
1843 edata->internalpos);
1845 appendStringInfoCharMacro(buf, '"');
1849 * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
1853 unpack_sql_state(int sql_state)
1855 static char buf[12];
1858 for (i = 0; i < 5; i++)
1860 buf[i] = PGUNSIXBIT(sql_state);
1870 * Write error report to server's log
1873 send_message_to_server_log(ErrorData *edata)
1877 initStringInfo(&buf);
1879 formatted_log_time[0] = '\0';
1881 log_line_prefix(&buf);
1882 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1884 if (Log_error_verbosity >= PGERROR_VERBOSE)
1885 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
1888 append_with_tabs(&buf, edata->message);
1890 append_with_tabs(&buf, _("missing error text"));
1892 if (edata->cursorpos > 0)
1893 appendStringInfo(&buf, _(" at character %d"),
1895 else if (edata->internalpos > 0)
1896 appendStringInfo(&buf, _(" at character %d"),
1897 edata->internalpos);
1899 appendStringInfoChar(&buf, '\n');
1901 if (Log_error_verbosity >= PGERROR_DEFAULT)
1905 log_line_prefix(&buf);
1906 appendStringInfoString(&buf, _("DETAIL: "));
1907 append_with_tabs(&buf, edata->detail);
1908 appendStringInfoChar(&buf, '\n');
1912 log_line_prefix(&buf);
1913 appendStringInfoString(&buf, _("HINT: "));
1914 append_with_tabs(&buf, edata->hint);
1915 appendStringInfoChar(&buf, '\n');
1917 if (edata->internalquery)
1919 log_line_prefix(&buf);
1920 appendStringInfoString(&buf, _("QUERY: "));
1921 append_with_tabs(&buf, edata->internalquery);
1922 appendStringInfoChar(&buf, '\n');
1926 log_line_prefix(&buf);
1927 appendStringInfoString(&buf, _("CONTEXT: "));
1928 append_with_tabs(&buf, edata->context);
1929 appendStringInfoChar(&buf, '\n');
1931 if (Log_error_verbosity >= PGERROR_VERBOSE)
1933 /* assume no newlines in funcname or filename... */
1934 if (edata->funcname && edata->filename)
1936 log_line_prefix(&buf);
1937 appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
1938 edata->funcname, edata->filename,
1941 else if (edata->filename)
1943 log_line_prefix(&buf);
1944 appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
1945 edata->filename, edata->lineno);
1951 * If the user wants the query that generated this error logged, do it.
1953 if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1954 debug_query_string != NULL &&
1957 log_line_prefix(&buf);
1958 appendStringInfoString(&buf, _("STATEMENT: "));
1959 append_with_tabs(&buf, debug_query_string);
1960 appendStringInfoChar(&buf, '\n');
1964 /* Write to syslog, if enabled */
1965 if (Log_destination & LOG_DESTINATION_SYSLOG)
1969 switch (edata->elevel)
1976 syslog_level = LOG_DEBUG;
1981 syslog_level = LOG_INFO;
1985 syslog_level = LOG_NOTICE;
1988 syslog_level = LOG_WARNING;
1991 syslog_level = LOG_ERR;
1995 syslog_level = LOG_CRIT;
1999 write_syslog(syslog_level, buf.data);
2001 #endif /* HAVE_SYSLOG */
2004 /* Write to eventlog, if enabled */
2005 if (Log_destination & LOG_DESTINATION_EVENTLOG)
2007 write_eventlog(edata->elevel, buf.data);
2011 /* Write to stderr, if enabled */
2012 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2015 * Use the chunking protocol if we know the syslogger should be
2016 * catching stderr output, and we are not ourselves the syslogger.
2017 * Otherwise, just do a vanilla write to stderr.
2019 if (redirection_done && !am_syslogger)
2020 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2024 * In a win32 service environment, there is no usable stderr. Capture
2025 * anything going there and write it to the eventlog instead.
2027 * If stderr redirection is active, it was OK to write to stderr above
2028 * because that's really a pipe to the syslogger process.
2030 else if (pgwin32_is_service())
2031 write_eventlog(edata->elevel, buf.data);
2034 write(fileno(stderr), buf.data, buf.len);
2037 /* If in the syslogger process, try to write messages direct to file */
2039 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2041 /* Write to CSV log if enabled */
2042 if (Log_destination & LOG_DESTINATION_CSVLOG)
2044 if (redirection_done || am_syslogger)
2047 * send CSV data if it's safe to do so (syslogger doesn't need the
2048 * pipe). First get back the space in the message buffer.
2051 write_csvlog(edata);
2055 char *msg = _("Not safe to send CSV data\n");
2057 write(fileno(stderr), msg, strlen(msg));
2058 if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2059 whereToSendOutput != DestDebug)
2061 /* write message to stderr unless we just sent it above */
2062 write(fileno(stderr), buf.data, buf.len);
2074 * Send data to the syslogger using the chunked protocol
2077 write_pipe_chunks(char *data, int len, int dest)
2081 int fd = fileno(stderr);
2085 p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2086 p.proto.pid = MyProcPid;
2088 /* write all but the last chunk */
2089 while (len > PIPE_MAX_PAYLOAD)
2091 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2092 p.proto.len = PIPE_MAX_PAYLOAD;
2093 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2094 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2095 data += PIPE_MAX_PAYLOAD;
2096 len -= PIPE_MAX_PAYLOAD;
2099 /* write the last chunk */
2100 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2102 memcpy(p.proto.data, data, len);
2103 write(fd, &p, PIPE_HEADER_SIZE + len);
2108 * Write error report to client
2111 send_message_to_frontend(ErrorData *edata)
2113 StringInfoData msgbuf;
2115 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2116 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2118 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2120 /* New style with separate fields */
2125 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2126 pq_sendstring(&msgbuf, error_severity(edata->elevel));
2128 /* unpack MAKE_SQLSTATE code */
2129 ssval = edata->sqlerrcode;
2130 for (i = 0; i < 5; i++)
2132 tbuf[i] = PGUNSIXBIT(ssval);
2137 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2138 pq_sendstring(&msgbuf, tbuf);
2140 /* M field is required per protocol, so always send something */
2141 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2143 pq_sendstring(&msgbuf, edata->message);
2145 pq_sendstring(&msgbuf, _("missing error text"));
2149 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2150 pq_sendstring(&msgbuf, edata->detail);
2155 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2156 pq_sendstring(&msgbuf, edata->hint);
2161 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2162 pq_sendstring(&msgbuf, edata->context);
2165 if (edata->cursorpos > 0)
2167 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2168 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2169 pq_sendstring(&msgbuf, tbuf);
2172 if (edata->internalpos > 0)
2174 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2175 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2176 pq_sendstring(&msgbuf, tbuf);
2179 if (edata->internalquery)
2181 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2182 pq_sendstring(&msgbuf, edata->internalquery);
2185 if (edata->filename)
2187 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2188 pq_sendstring(&msgbuf, edata->filename);
2191 if (edata->lineno > 0)
2193 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2194 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2195 pq_sendstring(&msgbuf, tbuf);
2198 if (edata->funcname)
2200 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2201 pq_sendstring(&msgbuf, edata->funcname);
2204 pq_sendbyte(&msgbuf, '\0'); /* terminator */
2208 /* Old style --- gin up a backwards-compatible message */
2211 initStringInfo(&buf);
2213 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2215 if (edata->show_funcname && edata->funcname)
2216 appendStringInfo(&buf, "%s: ", edata->funcname);
2219 appendStringInfoString(&buf, edata->message);
2221 appendStringInfoString(&buf, _("missing error text"));
2223 if (edata->cursorpos > 0)
2224 appendStringInfo(&buf, _(" at character %d"),
2226 else if (edata->internalpos > 0)
2227 appendStringInfo(&buf, _(" at character %d"),
2228 edata->internalpos);
2230 appendStringInfoChar(&buf, '\n');
2232 pq_sendstring(&msgbuf, buf.data);
2237 pq_endmessage(&msgbuf);
2240 * This flush is normally not necessary, since postgres.c will flush out
2241 * waiting data when control returns to the main loop. But it seems best
2242 * to leave it here, so that the client has some clue what happened if the
2243 * backend dies before getting back to the main loop ... error/notice
2244 * messages should not be a performance-critical path anyway, so an extra
2245 * flush won't hurt much ...
2252 * Support routines for formatting error messages.
2257 * expand_fmt_string --- process special format codes in a format string
2259 * We must replace %m with the appropriate strerror string, since vsnprintf
2260 * won't know what to do with it.
2262 * The result is a palloc'd string.
2265 expand_fmt_string(const char *fmt, ErrorData *edata)
2270 initStringInfo(&buf);
2272 for (cp = fmt; *cp; cp++)
2274 if (cp[0] == '%' && cp[1] != '\0')
2280 * Replace %m by system error string. If there are any %'s in
2281 * the string, we'd better double them so that vsnprintf won't
2286 cp2 = useful_strerror(edata->saved_errno);
2290 appendStringInfoCharMacro(&buf, '%');
2291 appendStringInfoCharMacro(&buf, *cp2);
2296 /* copy % and next char --- this avoids trouble with %%m */
2297 appendStringInfoCharMacro(&buf, '%');
2298 appendStringInfoCharMacro(&buf, *cp);
2302 appendStringInfoCharMacro(&buf, *cp);
2310 * A slightly cleaned-up version of strerror()
2313 useful_strerror(int errnum)
2315 /* this buffer is only used if errno has a bogus value */
2316 static char errorstr_buf[48];
2320 /* Winsock error code range, per WinError.h */
2321 if (errnum >= 10000 && errnum <= 11999)
2322 return pgwin32_socket_strerror(errnum);
2324 str = strerror(errnum);
2327 * Some strerror()s return an empty string for out-of-range errno. This is
2328 * ANSI C spec compliant, but not exactly useful.
2330 if (str == NULL || *str == '\0')
2332 snprintf(errorstr_buf, sizeof(errorstr_buf),
2334 translator: This string will be truncated at 47
2335 characters expanded. */
2336 _("operating system error %d"), errnum);
2345 * error_severity --- get localized string representing elevel
2348 error_severity(int elevel)
2359 prefix = _("DEBUG");
2369 prefix = _("NOTICE");
2372 prefix = _("WARNING");
2375 prefix = _("ERROR");
2378 prefix = _("FATAL");
2381 prefix = _("PANIC");
2395 * Append the string to the StringInfo buffer, inserting a tab after any
2399 append_with_tabs(StringInfo buf, const char *str)
2403 while ((ch = *str++) != '\0')
2405 appendStringInfoCharMacro(buf, ch);
2407 appendStringInfoCharMacro(buf, '\t');
2413 * Write errors to stderr (or by equal means when stderr is
2414 * not available). Used before ereport/elog can be used
2415 * safely (memory context, GUC load etc)
2418 write_stderr(const char *fmt,...)
2426 /* On Unix, we just fprintf to stderr */
2427 vfprintf(stderr, fmt, ap);
2432 * On Win32, we print to stderr if running on a console, or write to
2433 * eventlog if running as a service
2435 if (pgwin32_is_service()) /* Running as a service */
2437 char errbuf[2048]; /* Arbitrary size? */
2439 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2441 write_eventlog(ERROR, errbuf);
2445 /* Not running as service, write to stderr */
2446 vfprintf(stderr, fmt, ap);
2455 * is_log_level_output -- is elevel logically >= log_min_level?
2457 * We use this for tests that should consider LOG to sort out-of-order,
2458 * between ERROR and FATAL. Generally this is the right thing for testing
2459 * whether a message should go to the postmaster log, whereas a simple >=
2460 * test is correct for testing whether the message should go to the client.
2463 is_log_level_output(int elevel, int log_min_level)
2465 if (elevel == LOG || elevel == COMMERROR)
2467 if (log_min_level == LOG || log_min_level <= ERROR)
2470 else if (log_min_level == LOG)
2473 if (elevel >= FATAL)
2476 /* Neither is LOG */
2477 else if (elevel >= log_min_level)