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 condition is to force any
28 * such messages up to ERROR level if they aren't already (so that we will
29 * not need to return to the outer elog.c call), and to reset the ErrorContext
30 * to empty before trying to process the inner message. Since ErrorContext
31 * is guaranteed to have at least 8K of space in it (see mcxt.c), we should
32 * be able to process an "out of memory" message successfully.
35 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
36 * Portions Copyright (c) 1994, Regents of the University of California
40 * $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.128 2004/03/15 15:56:23 momjian Exp $
42 *-------------------------------------------------------------------------
57 #include "libpq/libpq.h"
58 #include "libpq/pqformat.h"
59 #include "mb/pg_wchar.h"
60 #include "miscadmin.h"
61 #include "storage/ipc.h"
62 #include "tcop/tcopprot.h"
63 #include "utils/memutils.h"
64 #include "utils/guc.h"
67 /* Global variables */
68 ErrorContextCallback *error_context_stack = NULL;
71 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
72 char *Log_line_prefix = ""; /* format for extra log line info */
76 * 0 = only stdout/stderr
77 * 1 = stdout+stderr and syslog
79 * ... in theory anyway
82 char *Syslog_facility; /* openlog() parameters */
85 static void write_syslog(int level, const char *line);
90 #endif /* HAVE_SYSLOG */
94 * ErrorData holds the data accumulated during any one ereport() cycle.
95 * Any non-NULL pointers must point to palloc'd data in ErrorContext.
96 * (The const pointers are an exception; we assume they point at non-freeable
100 typedef struct ErrorData
102 int elevel; /* error level */
103 bool output_to_server; /* will report to server log? */
104 bool output_to_client; /* will report to client? */
105 bool show_funcname; /* true to force funcname inclusion */
106 const char *filename; /* __FILE__ of ereport() call */
107 int lineno; /* __LINE__ of ereport() call */
108 const char *funcname; /* __func__ of ereport() call */
109 int sqlerrcode; /* encoded ERRSTATE */
110 char *message; /* primary error message */
111 char *detail; /* detail error message */
112 char *hint; /* hint message */
113 char *context; /* context message */
114 int cursorpos; /* cursor index into query string */
115 int saved_errno; /* errno at entry */
118 /* We provide a small stack of ErrorData records for re-entrant cases */
119 #define ERRORDATA_STACK_SIZE 5
121 static ErrorData errordata[ERRORDATA_STACK_SIZE];
123 static int errordata_stack_depth = -1; /* index of topmost active frame */
125 static int recursion_depth = 0; /* to detect actual recursion */
128 /* Macro for checking errordata_stack_depth is reasonable */
129 #define CHECK_STACK_DEPTH() \
131 if (errordata_stack_depth < 0) \
133 errordata_stack_depth = -1; \
134 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
139 static void send_message_to_server_log(ErrorData *edata);
140 static void send_message_to_frontend(ErrorData *edata);
141 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
142 static const char *useful_strerror(int errnum);
143 static const char *error_severity(int elevel);
144 static void append_with_tabs(StringInfo buf, const char *str);
145 static const char *log_line_prefix(void);
148 * errstart --- begin an error-reporting cycle
150 * Create a stack entry and store the given parameters in it. Subsequently,
151 * errmsg() and perhaps other routines will be called to further populate
152 * the stack entry. Finally, errfinish() will be called to actually process
155 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
156 * report (if it's a warning or lower and not to be reported anywhere).
159 errstart(int elevel, const char *filename, int lineno,
160 const char *funcname)
163 bool output_to_server = false;
164 bool output_to_client = false;
167 * First decide whether we need to process this report at all; if it's
168 * warning or less and not enabled for logging, just return FALSE
169 * without starting up any error logging machinery.
173 * Convert initialization errors into fatal errors. This is probably
174 * redundant, because Warn_restart_ready won't be set anyway.
176 if (elevel == ERROR && IsInitProcessingMode())
180 * If we are inside a critical section, all errors become PANIC
181 * errors. See miscadmin.h.
185 if (CritSectionCount > 0)
189 /* Determine whether message is enabled for server log output */
190 if (IsPostmasterEnvironment)
192 /* Complicated because LOG is sorted out-of-order for this purpose */
193 if (elevel == LOG || elevel == COMMERROR)
195 if (log_min_messages == LOG)
196 output_to_server = true;
197 else if (log_min_messages < FATAL)
198 output_to_server = true;
203 if (log_min_messages == LOG)
206 output_to_server = true;
209 else if (elevel >= log_min_messages)
210 output_to_server = true;
215 /* In bootstrap/standalone case, do not sort LOG out-of-order */
216 output_to_server = (elevel >= log_min_messages);
219 /* Determine whether message is enabled for client output */
220 if (whereToSendOutput == Remote && elevel != COMMERROR)
223 * client_min_messages is honored only after we complete the
224 * authentication handshake. This is required both for security
225 * reasons and because many clients can't handle NOTICE messages
226 * during authentication.
228 if (ClientAuthInProgress)
229 output_to_client = (elevel >= ERROR);
231 output_to_client = (elevel >= client_min_messages ||
235 /* Skip processing effort if non-error message will not be output */
236 if (elevel < ERROR && !output_to_server && !output_to_client)
240 * Okay, crank up a stack entry to store the info in.
243 if (recursion_depth++ > 0)
246 * Ooops, error during error processing. Clear ErrorContext and
247 * force level up to ERROR or greater, as discussed at top of
248 * file. Adjust output decisions too.
250 MemoryContextReset(ErrorContext);
251 output_to_server = true;
252 if (whereToSendOutput == Remote && elevel != COMMERROR)
253 output_to_client = true;
254 elevel = Max(elevel, ERROR);
257 * If we recurse more than once, the problem might be something
258 * broken in a context traceback routine. Abandon them too.
260 if (recursion_depth > 2)
261 error_context_stack = NULL;
263 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
265 /* Wups, stack not big enough */
268 elevel = Max(elevel, ERROR);
271 * Don't forget any FATAL/PANIC status on the stack (see comments
274 for (i = 0; i < errordata_stack_depth; i++)
275 elevel = Max(elevel, errordata[i].elevel);
276 /* Clear the stack and try again */
277 errordata_stack_depth = -1;
278 ereport(elevel, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
281 /* Initialize data for this error frame */
282 edata = &errordata[errordata_stack_depth];
283 MemSet(edata, 0, sizeof(ErrorData));
284 edata->elevel = elevel;
285 edata->output_to_server = output_to_server;
286 edata->output_to_client = output_to_client;
287 edata->filename = filename;
288 edata->lineno = lineno;
289 edata->funcname = funcname;
290 /* Select default errcode based on elevel */
292 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
293 else if (elevel == WARNING)
294 edata->sqlerrcode = ERRCODE_WARNING;
296 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
297 /* errno is saved here so that error parameter eval can't change it */
298 edata->saved_errno = errno;
305 * errfinish --- end an error-reporting cycle
307 * Produce the appropriate error report(s) and pop the error stack.
309 * If elevel is ERROR or worse, control does not return to the caller.
310 * See elog.h for the error level definitions.
313 errfinish(int dummy,...)
315 ErrorData *edata = &errordata[errordata_stack_depth];
316 int elevel = edata->elevel;
317 MemoryContext oldcontext;
318 ErrorContextCallback *econtext;
324 * Do processing in ErrorContext, which we hope has enough reserved
325 * space to report an error.
327 oldcontext = MemoryContextSwitchTo(ErrorContext);
330 * Call any context callback functions. Errors occurring in callback
331 * functions will be treated as recursive errors --- this ensures we
332 * will avoid infinite recursion (see errstart).
334 for (econtext = error_context_stack;
336 econtext = econtext->previous)
337 (*econtext->callback) (econtext->arg);
339 /* Send to server log, if enabled */
340 if (edata->output_to_server)
341 send_message_to_server_log(edata);
344 * Abort any old-style COPY OUT in progress when an error is detected.
345 * This hack is necessary because of poor design of old-style copy
346 * protocol. Note we must do this even if client is fool enough to
347 * have set client_min_messages above ERROR, so don't look at
350 if (elevel >= ERROR && whereToSendOutput == Remote)
353 /* Send to client, if enabled */
354 if (edata->output_to_client)
355 send_message_to_frontend(edata);
357 /* Now free up subsidiary data attached to stack entry, and release it */
359 pfree(edata->message);
361 pfree(edata->detail);
365 pfree(edata->context);
367 MemoryContextSwitchTo(oldcontext);
369 errordata_stack_depth--;
373 * If the error level is ERROR or more, we are not going to return to
374 * caller; therefore, if there is any stacked error already in
375 * progress it will be lost. This is more or less okay, except we do
376 * not want to have a FATAL or PANIC error downgraded because the
377 * reporting process was interrupted by a lower-grade error. So check
378 * the stack and make sure we panic if panic is warranted.
384 for (i = 0; i <= errordata_stack_depth; i++)
385 elevel = Max(elevel, errordata[i].elevel);
388 * Also, be sure to reset the stack to empty. We do not clear
389 * ErrorContext here, though; PostgresMain does that later on.
391 errordata_stack_depth = -1;
393 error_context_stack = NULL;
397 * Perform error recovery action as specified by elevel.
399 if (elevel == ERROR || elevel == FATAL)
401 /* Prevent immediate interrupt while entering error recovery */
402 ImmediateInterruptOK = false;
405 * If we just reported a startup failure, the client will
406 * disconnect on receiving it, so don't send any more to the
409 if (!Warn_restart_ready && whereToSendOutput == Remote)
410 whereToSendOutput = None;
413 * For a FATAL error, we let proc_exit clean up and exit.
415 * There are several other cases in which we treat ERROR as FATAL and
416 * go directly to proc_exit:
418 * 1. ExitOnAnyError mode switch is set (initdb uses this).
420 * 2. we have not yet entered the main backend loop (ie, we are in
421 * the postmaster or in backend startup); we have noplace to
424 * 3. the error occurred after proc_exit has begun to run. (It's
425 * proc_exit's responsibility to see that this doesn't turn into
426 * infinite recursion!)
428 * In the last case, we exit with nonzero exit code to indicate that
429 * something's pretty wrong. We also want to exit with nonzero
430 * exit code if not running under the postmaster (for example, if
431 * we are being run from the initdb script, we'd better return an
434 if (elevel == FATAL ||
436 !Warn_restart_ready ||
437 proc_exit_inprogress)
440 * fflush here is just to improve the odds that we get to see
441 * the error message, in case things are so hosed that
442 * proc_exit crashes. Any other code you might be tempted to
443 * add here should probably be in an on_proc_exit callback
448 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
452 * Guard against infinite loop from errors during error recovery.
455 ereport(PANIC, (errmsg("error during error recovery, giving up")));
459 * Otherwise we can return to the main loop in postgres.c.
461 siglongjmp(Warn_restart, 1);
467 * Serious crash time. Postmaster will observe nonzero process
468 * exit status and kill the other backends too.
470 * XXX: what if we are *in* the postmaster? abort() won't kill our
473 ImmediateInterruptOK = false;
479 /* We reach here if elevel <= WARNING. OK to return to caller. */
484 * errcode --- add SQLSTATE error code to the current error
486 * The code is expected to be represented as per MAKE_SQLSTATE().
489 errcode(int sqlerrcode)
491 ErrorData *edata = &errordata[errordata_stack_depth];
493 /* we don't bother incrementing recursion_depth */
496 edata->sqlerrcode = sqlerrcode;
498 return 0; /* return value does not matter */
503 * errcode_for_file_access --- add SQLSTATE error code to the current error
505 * The SQLSTATE code is chosen based on the saved errno value. We assume
506 * that the failing operation was some type of disk file access.
508 * NOTE: the primary error message string should generally include %m
512 errcode_for_file_access(void)
514 ErrorData *edata = &errordata[errordata_stack_depth];
516 /* we don't bother incrementing recursion_depth */
519 switch (edata->saved_errno)
521 /* Permission-denied failures */
522 case EPERM: /* Not super-user */
523 case EACCES: /* Permission denied */
525 case EROFS: /* Read only file system */
527 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
531 case ENOENT: /* No such file or directory */
532 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
536 case EEXIST: /* File exists */
537 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
540 /* Wrong object type or state */
541 case ENOTDIR: /* Not a directory */
542 case EISDIR: /* Is a directory */
543 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
544 case ENOTEMPTY: /* Directory not empty */
546 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
549 /* Insufficient resources */
550 case ENOSPC: /* No space left on device */
551 edata->sqlerrcode = ERRCODE_DISK_FULL;
554 case ENFILE: /* File table overflow */
555 case EMFILE: /* Too many open files */
556 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
559 /* Hardware failure */
560 case EIO: /* I/O error */
561 edata->sqlerrcode = ERRCODE_IO_ERROR;
564 /* All else is classified as internal errors */
566 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
570 return 0; /* return value does not matter */
574 * errcode_for_socket_access --- add SQLSTATE error code to the current error
576 * The SQLSTATE code is chosen based on the saved errno value. We assume
577 * that the failing operation was some type of socket access.
579 * NOTE: the primary error message string should generally include %m
583 errcode_for_socket_access(void)
585 ErrorData *edata = &errordata[errordata_stack_depth];
587 /* we don't bother incrementing recursion_depth */
590 switch (edata->saved_errno)
592 /* Loss of connection */
597 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
600 /* All else is classified as internal errors */
602 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
606 return 0; /* return value does not matter */
611 * This macro handles expansion of a format string and associated parameters;
612 * it's common code for errmsg(), errdetail(), etc. Must be called inside
613 * a routine that is declared like "const char *fmt, ..." and has an edata
614 * pointer set up. The message is assigned to edata->targetfield, or
615 * appended to it if appendval is true.
617 * Note: we pstrdup the buffer rather than just transferring its storage
618 * to the edata field because the buffer might be considerably larger than
621 #define EVALUATE_MESSAGE(targetfield, appendval) \
624 StringInfoData buf; \
625 /* Internationalize the error format string */ \
626 fmt = gettext(fmt); \
627 /* Expand %m in format string */ \
628 fmtbuf = expand_fmt_string(fmt, edata); \
629 initStringInfo(&buf); \
630 if ((appendval) && edata->targetfield) \
631 appendStringInfo(&buf, "%s\n", edata->targetfield); \
632 /* Generate actual output --- have to use appendStringInfoVA */ \
637 va_start(args, fmt); \
638 success = appendStringInfoVA(&buf, fmtbuf, args); \
642 enlargeStringInfo(&buf, buf.maxlen); \
644 /* Done with expanded fmt */ \
646 /* Save the completed message into the stack item */ \
647 if (edata->targetfield) \
648 pfree(edata->targetfield); \
649 edata->targetfield = pstrdup(buf.data); \
655 * errmsg --- add a primary error message text to the current error
657 * In addition to the usual %-escapes recognized by printf, "%m" in
658 * fmt is replaced by the error message for the caller's value of errno.
660 * Note: no newline is needed at the end of the fmt string, since
661 * ereport will provide one for the output methods that need it.
664 errmsg(const char *fmt,...)
666 ErrorData *edata = &errordata[errordata_stack_depth];
667 MemoryContext oldcontext;
671 oldcontext = MemoryContextSwitchTo(ErrorContext);
673 EVALUATE_MESSAGE(message, false);
675 MemoryContextSwitchTo(oldcontext);
677 return 0; /* return value does not matter */
682 * errmsg_internal --- add a primary error message text to the current error
684 * This is exactly like errmsg() except that strings passed to errmsg_internal
685 * are customarily left out of the internationalization message dictionary.
686 * This should be used for "can't happen" cases that are probably not worth
687 * spending translation effort on.
690 errmsg_internal(const char *fmt,...)
692 ErrorData *edata = &errordata[errordata_stack_depth];
693 MemoryContext oldcontext;
697 oldcontext = MemoryContextSwitchTo(ErrorContext);
699 EVALUATE_MESSAGE(message, false);
701 MemoryContextSwitchTo(oldcontext);
703 return 0; /* return value does not matter */
708 * errdetail --- add a detail error message text to the current error
711 errdetail(const char *fmt,...)
713 ErrorData *edata = &errordata[errordata_stack_depth];
714 MemoryContext oldcontext;
718 oldcontext = MemoryContextSwitchTo(ErrorContext);
720 EVALUATE_MESSAGE(detail, false);
722 MemoryContextSwitchTo(oldcontext);
724 return 0; /* return value does not matter */
729 * errhint --- add a hint error message text to the current error
732 errhint(const char *fmt,...)
734 ErrorData *edata = &errordata[errordata_stack_depth];
735 MemoryContext oldcontext;
739 oldcontext = MemoryContextSwitchTo(ErrorContext);
741 EVALUATE_MESSAGE(hint, false);
743 MemoryContextSwitchTo(oldcontext);
745 return 0; /* return value does not matter */
750 * errcontext --- add a context error message text to the current error
752 * Unlike other cases, multiple calls are allowed to build up a stack of
753 * context information. We assume earlier calls represent more-closely-nested
757 errcontext(const char *fmt,...)
759 ErrorData *edata = &errordata[errordata_stack_depth];
760 MemoryContext oldcontext;
764 oldcontext = MemoryContextSwitchTo(ErrorContext);
766 EVALUATE_MESSAGE(context, true);
768 MemoryContextSwitchTo(oldcontext);
770 return 0; /* return value does not matter */
775 * errfunction --- add reporting function name to the current error
777 * This is used when backwards compatibility demands that the function
778 * name appear in messages sent to old-protocol clients. Note that the
779 * passed string is expected to be a non-freeable constant string.
782 errfunction(const char *funcname)
784 ErrorData *edata = &errordata[errordata_stack_depth];
786 /* we don't bother incrementing recursion_depth */
789 edata->funcname = funcname;
790 edata->show_funcname = true;
792 return 0; /* return value does not matter */
796 * errposition --- add cursor position to the current error
799 errposition(int cursorpos)
801 ErrorData *edata = &errordata[errordata_stack_depth];
803 /* we don't bother incrementing recursion_depth */
806 edata->cursorpos = cursorpos;
808 return 0; /* return value does not matter */
813 * elog_finish --- finish up for old-style API
815 * The elog() macro already called errstart, but with ERROR rather than
819 elog_finish(int elevel, const char *fmt,...)
821 ErrorData *edata = &errordata[errordata_stack_depth];
822 MemoryContext oldcontext;
827 * We need to redo errstart() because the elog macro had to call it
830 errordata_stack_depth--;
831 errno = edata->saved_errno;
832 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
833 return; /* nothing to do */
836 * Format error message just like errmsg().
839 oldcontext = MemoryContextSwitchTo(ErrorContext);
841 EVALUATE_MESSAGE(message, false);
843 MemoryContextSwitchTo(oldcontext);
847 * And let errfinish() finish up.
854 * Initialization of error output file
862 if (OutputFileName[0])
865 * A debug-output file name was given.
867 * Make sure we can write the file, and find out if it's a tty.
869 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
872 (errcode_for_file_access(),
873 errmsg("could not open file \"%s\": %m", OutputFileName)));
878 * Redirect our stderr to the debug output file.
880 if (!freopen(OutputFileName, "a", stderr))
882 (errcode_for_file_access(),
883 errmsg("could not reopen file \"%s\" as stderr: %m",
887 * If the file is a tty and we're running under the postmaster,
888 * try to send stdout there as well (if it isn't a tty then stderr
889 * will block out stdout, so we may as well let stdout go wherever
890 * it was going before).
892 if (istty && IsUnderPostmaster)
893 if (!freopen(OutputFileName, "a", stdout))
895 (errcode_for_file_access(),
896 errmsg("could not reopen file \"%s\" as stdout: %m",
905 #ifndef PG_SYSLOG_LIMIT
906 #define PG_SYSLOG_LIMIT 128
910 * Write a message line to syslog if the syslog option is set.
912 * Our problem here is that many syslog implementations don't handle
913 * long messages in an acceptable manner. While this function doesn't
914 * help that fact, it does work around by splitting up messages into
918 write_syslog(int level, const char *line)
920 static bool openlog_done = false;
921 static unsigned long seq = 0;
922 static int syslog_fac = LOG_LOCAL0;
924 int len = strlen(line);
931 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
932 syslog_fac = LOG_LOCAL0;
933 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
934 syslog_fac = LOG_LOCAL1;
935 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
936 syslog_fac = LOG_LOCAL2;
937 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
938 syslog_fac = LOG_LOCAL3;
939 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
940 syslog_fac = LOG_LOCAL4;
941 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
942 syslog_fac = LOG_LOCAL5;
943 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
944 syslog_fac = LOG_LOCAL6;
945 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
946 syslog_fac = LOG_LOCAL7;
947 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
952 * We add a sequence number to each log message to suppress "same"
957 /* divide into multiple syslog() calls if message is too long */
958 /* or if the message contains embedded NewLine(s) '\n' */
959 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
965 char buf[PG_SYSLOG_LIMIT + 1];
969 /* if we start at a newline, move ahead one char */
977 strncpy(buf, line, PG_SYSLOG_LIMIT);
978 buf[PG_SYSLOG_LIMIT] = '\0';
979 if (strchr(buf, '\n') != NULL)
980 *strchr(buf, '\n') = '\0';
982 buflen = strlen(buf);
984 /* trim to multibyte letter boundary */
985 buflen = pg_mbcliplen(buf, buflen, buflen);
990 /* already word boundary? */
991 if (!isspace((unsigned char) line[buflen]) &&
992 line[buflen] != '\0')
994 /* try to divide at word boundary */
996 while (i > 0 && !isspace((unsigned char) buf[i]))
999 if (i > 0) /* else couldn't divide word boundary */
1008 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1015 /* message short enough */
1016 syslog(level, "[%lu] %s", seq, line);
1019 #endif /* HAVE_SYSLOG */
1022 * Format tag info for log lines
1025 log_line_prefix(void)
1028 /* static accumulator for line numbers */
1029 static int log_line_number = 0;
1031 /* space for option string + one of each option, plus some room to spare */
1032 /* Note: if more identifiers are built in this will have to increase */
1033 static char *result = NULL;
1034 int format_len = strlen(Log_line_prefix);
1035 int result_len = 2*NAMEDATALEN + format_len +120 ;
1038 result = malloc(result_len);
1044 char * dbname = NULL;
1045 char * username = NULL;
1048 if (MyProcPort != NULL)
1050 dbname = MyProcPort->database_name;
1051 username = MyProcPort->user_name;
1052 if (dbname == NULL || *dbname == '\0')
1053 dbname = gettext("[unknown]");
1054 if (username == NULL || *username == '\0')
1055 username = gettext("[unknown]");
1059 * invariant through each iteration of this loop:
1060 * . j is the index of the trailing null on result
1061 * . result_len - j is the number of chars we have room for
1062 * including the trailing null
1063 * . there is room to write at least one more non-null char plus the
1066 for (i = 0, j=0; i < format_len && j < result_len-1; i++)
1068 if(Log_line_prefix[i] != '%')
1070 /* literal char, just copy */
1071 result[j]=Log_line_prefix[i];
1076 else if (i == format_len - 1)
1078 /* format error - skip it */
1082 /* go to char after '%' */
1085 /* in postmaster and friends, skip non-applicable options,
1086 * stop if %x is seen
1088 if (MyProcPort == NULL)
1090 if (Log_line_prefix[i] == 'x')
1092 if (strchr("udcsir",Log_line_prefix[i]) != NULL)
1096 /* process the option */
1097 switch (Log_line_prefix[i])
1100 j += snprintf(result+j,result_len-j,"%s",username);
1103 j += snprintf(result+j,result_len-j,"%s",dbname);
1106 j += snprintf(result+j,result_len-j,"%lx.%lx",
1107 (long)(MyProcPort->session_start.tv_sec),
1111 j += snprintf(result+j,result_len-j,"%ld",(long)MyProcPid);
1114 j += snprintf(result+j,result_len-j,"%d",log_line_number);
1117 stamp_time = time(NULL);
1118 j += strftime(result+j, result_len-j, "%Y-%m-%d %H:%M:%S",
1119 localtime(&stamp_time));
1122 j += strftime(result+j, result_len-j, "%Y-%m-%d %H:%M:%S",
1123 localtime(&(MyProcPort->session_start.tv_sec)));
1126 j += snprintf(result+j,result_len-j,"%s",
1127 MyProcPort->commandTag);
1130 j += snprintf(result+j,result_len-j,"%s",
1131 MyProcPort->remote_host);
1132 if (strlen(MyProcPort->remote_port) > 0)
1133 j += snprintf(result+j,result_len-j,"(%s)",
1134 MyProcPort->remote_port);
1137 /* non-postmaster case - just ignore */
1145 /* format error - skip it */
1155 * Write error report to server's log
1158 send_message_to_server_log(ErrorData *edata)
1162 initStringInfo(&buf);
1164 appendStringInfo(&buf, "%s%s: ",
1165 log_line_prefix(), error_severity(edata->elevel));
1167 if (Log_error_verbosity >= PGERROR_VERBOSE)
1169 /* unpack MAKE_SQLSTATE code */
1174 ssval = edata->sqlerrcode;
1175 for (i = 0; i < 5; i++)
1177 tbuf[i] = PGUNSIXBIT(ssval);
1181 appendStringInfo(&buf, "%s: ", tbuf);
1185 append_with_tabs(&buf, edata->message);
1187 append_with_tabs(&buf, gettext("missing error text"));
1189 if (edata->cursorpos > 0)
1190 appendStringInfo(&buf, gettext(" at character %d"), edata->cursorpos);
1192 appendStringInfoChar(&buf, '\n');
1194 if (Log_error_verbosity >= PGERROR_DEFAULT)
1198 appendStringInfoString(&buf, log_line_prefix() );
1199 appendStringInfoString(&buf, gettext("DETAIL: "));
1200 append_with_tabs(&buf, edata->detail);
1201 appendStringInfoChar(&buf, '\n');
1205 appendStringInfoString(&buf, log_line_prefix() );
1206 appendStringInfoString(&buf, gettext("HINT: "));
1207 append_with_tabs(&buf, edata->hint);
1208 appendStringInfoChar(&buf, '\n');
1212 appendStringInfoString(&buf, log_line_prefix() );
1213 appendStringInfoString(&buf, gettext("CONTEXT: "));
1214 append_with_tabs(&buf, edata->context);
1215 appendStringInfoChar(&buf, '\n');
1217 if (Log_error_verbosity >= PGERROR_VERBOSE)
1219 /* assume no newlines in funcname or filename... */
1220 if (edata->funcname && edata->filename)
1221 appendStringInfo(&buf, gettext("%sLOCATION: %s, %s:%d\n"),
1223 edata->funcname, edata->filename,
1225 else if (edata->filename)
1226 appendStringInfo(&buf, gettext("%sLOCATION: %s:%d\n"),
1228 edata->filename, edata->lineno);
1233 * If the user wants the query that generated this error logged, do it.
1235 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1237 appendStringInfoString(&buf, log_line_prefix() );
1238 appendStringInfoString(&buf, gettext("STATEMENT: "));
1239 append_with_tabs(&buf, debug_query_string);
1240 appendStringInfoChar(&buf, '\n');
1245 /* Write to syslog, if enabled */
1246 if (Use_syslog >= 1)
1250 switch (edata->elevel)
1257 syslog_level = LOG_DEBUG;
1262 syslog_level = LOG_INFO;
1266 syslog_level = LOG_NOTICE;
1269 syslog_level = LOG_WARNING;
1272 syslog_level = LOG_ERR;
1276 syslog_level = LOG_CRIT;
1280 write_syslog(syslog_level, buf.data);
1282 #endif /* HAVE_SYSLOG */
1284 /* Write to stderr, if enabled */
1285 if (Use_syslog <= 1 || whereToSendOutput == Debug)
1288 * Timestamp and PID are only used for stderr output --- we assume
1289 * the syslog daemon will supply them for us in the other case.
1291 fprintf(stderr, "%s",buf.data);
1299 * Write error report to client
1302 send_message_to_frontend(ErrorData *edata)
1304 StringInfoData msgbuf;
1306 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1307 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1309 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1311 /* New style with separate fields */
1316 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1317 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1319 /* unpack MAKE_SQLSTATE code */
1320 ssval = edata->sqlerrcode;
1321 for (i = 0; i < 5; i++)
1323 tbuf[i] = PGUNSIXBIT(ssval);
1328 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1329 pq_sendstring(&msgbuf, tbuf);
1331 /* M field is required per protocol, so always send something */
1332 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1334 pq_sendstring(&msgbuf, edata->message);
1336 pq_sendstring(&msgbuf, gettext("missing error text"));
1340 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1341 pq_sendstring(&msgbuf, edata->detail);
1346 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1347 pq_sendstring(&msgbuf, edata->hint);
1352 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1353 pq_sendstring(&msgbuf, edata->context);
1356 if (edata->cursorpos > 0)
1358 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1359 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1360 pq_sendstring(&msgbuf, tbuf);
1363 if (edata->filename)
1365 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1366 pq_sendstring(&msgbuf, edata->filename);
1369 if (edata->lineno > 0)
1371 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1372 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1373 pq_sendstring(&msgbuf, tbuf);
1376 if (edata->funcname)
1378 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1379 pq_sendstring(&msgbuf, edata->funcname);
1382 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1386 /* Old style --- gin up a backwards-compatible message */
1389 initStringInfo(&buf);
1391 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1393 if (edata->show_funcname && edata->funcname)
1394 appendStringInfo(&buf, "%s: ", edata->funcname);
1397 appendStringInfoString(&buf, edata->message);
1399 appendStringInfoString(&buf, gettext("missing error text"));
1401 if (edata->cursorpos > 0)
1402 appendStringInfo(&buf, gettext(" at character %d"),
1405 appendStringInfoChar(&buf, '\n');
1407 pq_sendstring(&msgbuf, buf.data);
1412 pq_endmessage(&msgbuf);
1415 * This flush is normally not necessary, since postgres.c will flush
1416 * out waiting data when control returns to the main loop. But it
1417 * seems best to leave it here, so that the client has some clue what
1418 * happened if the backend dies before getting back to the main loop
1419 * ... error/notice messages should not be a performance-critical path
1420 * anyway, so an extra flush won't hurt much ...
1427 * Support routines for formatting error messages.
1432 * expand_fmt_string --- process special format codes in a format string
1434 * We must replace %m with the appropriate strerror string, since vsnprintf
1435 * won't know what to do with it.
1437 * The result is a palloc'd string.
1440 expand_fmt_string(const char *fmt, ErrorData *edata)
1445 initStringInfo(&buf);
1447 for (cp = fmt; *cp; cp++)
1449 if (cp[0] == '%' && cp[1] != '\0')
1455 * Replace %m by system error string. If there are any
1456 * %'s in the string, we'd better double them so that
1457 * vsnprintf won't misinterpret.
1461 cp2 = useful_strerror(edata->saved_errno);
1465 appendStringInfoCharMacro(&buf, '%');
1466 appendStringInfoCharMacro(&buf, *cp2);
1471 /* copy % and next char --- this avoids trouble with %%m */
1472 appendStringInfoCharMacro(&buf, '%');
1473 appendStringInfoCharMacro(&buf, *cp);
1477 appendStringInfoCharMacro(&buf, *cp);
1485 * A slightly cleaned-up version of strerror()
1488 useful_strerror(int errnum)
1490 /* this buffer is only used if errno has a bogus value */
1491 static char errorstr_buf[48];
1494 str = strerror(errnum);
1497 * Some strerror()s return an empty string for out-of-range errno.
1498 * This is ANSI C spec compliant, but not exactly useful.
1500 if (str == NULL || *str == '\0')
1503 * translator: This string will be truncated at 47 characters
1506 snprintf(errorstr_buf, sizeof(errorstr_buf),
1507 gettext("operating system error %d"), errnum);
1516 * error_severity --- get localized string representing elevel
1519 error_severity(int elevel)
1530 prefix = gettext("DEBUG");
1534 prefix = gettext("LOG");
1537 prefix = gettext("INFO");
1540 prefix = gettext("NOTICE");
1543 prefix = gettext("WARNING");
1546 prefix = gettext("ERROR");
1549 prefix = gettext("FATAL");
1552 prefix = gettext("PANIC");
1566 * Append the string to the StringInfo buffer, inserting a tab after any
1570 append_with_tabs(StringInfo buf, const char *str)
1574 while ((ch = *str++) != '\0')
1576 appendStringInfoCharMacro(buf, ch);
1578 appendStringInfoCharMacro(buf, '\t');