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.130 2004/03/21 22:29:11 tgl 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 = NULL; /* 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 internalpos; /* cursor index into internalquery */
116 char *internalquery; /* text of internally-generated query */
117 int saved_errno; /* errno at entry */
120 /* We provide a small stack of ErrorData records for re-entrant cases */
121 #define ERRORDATA_STACK_SIZE 5
123 static ErrorData errordata[ERRORDATA_STACK_SIZE];
125 static int errordata_stack_depth = -1; /* index of topmost active frame */
127 static int recursion_depth = 0; /* to detect actual recursion */
130 /* Macro for checking errordata_stack_depth is reasonable */
131 #define CHECK_STACK_DEPTH() \
133 if (errordata_stack_depth < 0) \
135 errordata_stack_depth = -1; \
136 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
141 static void log_line_prefix(StringInfo buf);
142 static void send_message_to_server_log(ErrorData *edata);
143 static void send_message_to_frontend(ErrorData *edata);
144 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
145 static const char *useful_strerror(int errnum);
146 static const char *error_severity(int elevel);
147 static void append_with_tabs(StringInfo buf, const char *str);
151 * errstart --- begin an error-reporting cycle
153 * Create a stack entry and store the given parameters in it. Subsequently,
154 * errmsg() and perhaps other routines will be called to further populate
155 * the stack entry. Finally, errfinish() will be called to actually process
158 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
159 * report (if it's a warning or lower and not to be reported anywhere).
162 errstart(int elevel, const char *filename, int lineno,
163 const char *funcname)
166 bool output_to_server = false;
167 bool output_to_client = false;
170 * First decide whether we need to process this report at all; if it's
171 * warning or less and not enabled for logging, just return FALSE
172 * without starting up any error logging machinery.
176 * Convert initialization errors into fatal errors. This is probably
177 * redundant, because Warn_restart_ready won't be set anyway.
179 if (elevel == ERROR && IsInitProcessingMode())
183 * If we are inside a critical section, all errors become PANIC
184 * errors. See miscadmin.h.
188 if (CritSectionCount > 0)
192 /* Determine whether message is enabled for server log output */
193 if (IsPostmasterEnvironment)
195 /* Complicated because LOG is sorted out-of-order for this purpose */
196 if (elevel == LOG || elevel == COMMERROR)
198 if (log_min_messages == LOG)
199 output_to_server = true;
200 else if (log_min_messages < FATAL)
201 output_to_server = true;
206 if (log_min_messages == LOG)
209 output_to_server = true;
212 else if (elevel >= log_min_messages)
213 output_to_server = true;
218 /* In bootstrap/standalone case, do not sort LOG out-of-order */
219 output_to_server = (elevel >= log_min_messages);
222 /* Determine whether message is enabled for client output */
223 if (whereToSendOutput == Remote && elevel != COMMERROR)
226 * client_min_messages is honored only after we complete the
227 * authentication handshake. This is required both for security
228 * reasons and because many clients can't handle NOTICE messages
229 * during authentication.
231 if (ClientAuthInProgress)
232 output_to_client = (elevel >= ERROR);
234 output_to_client = (elevel >= client_min_messages ||
238 /* Skip processing effort if non-error message will not be output */
239 if (elevel < ERROR && !output_to_server && !output_to_client)
243 * Okay, crank up a stack entry to store the info in.
246 if (recursion_depth++ > 0)
249 * Ooops, error during error processing. Clear ErrorContext and
250 * force level up to ERROR or greater, as discussed at top of
251 * file. Adjust output decisions too.
253 MemoryContextReset(ErrorContext);
254 output_to_server = true;
255 if (whereToSendOutput == Remote && elevel != COMMERROR)
256 output_to_client = true;
257 elevel = Max(elevel, ERROR);
260 * If we recurse more than once, the problem might be something
261 * broken in a context traceback routine. Abandon them too.
263 if (recursion_depth > 2)
264 error_context_stack = NULL;
266 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
268 /* Wups, stack not big enough */
271 elevel = Max(elevel, ERROR);
274 * Don't forget any FATAL/PANIC status on the stack (see comments
277 for (i = 0; i < errordata_stack_depth; i++)
278 elevel = Max(elevel, errordata[i].elevel);
279 /* Clear the stack and try again */
280 errordata_stack_depth = -1;
281 ereport(elevel, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
284 /* Initialize data for this error frame */
285 edata = &errordata[errordata_stack_depth];
286 MemSet(edata, 0, sizeof(ErrorData));
287 edata->elevel = elevel;
288 edata->output_to_server = output_to_server;
289 edata->output_to_client = output_to_client;
290 edata->filename = filename;
291 edata->lineno = lineno;
292 edata->funcname = funcname;
293 /* Select default errcode based on elevel */
295 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
296 else if (elevel == WARNING)
297 edata->sqlerrcode = ERRCODE_WARNING;
299 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
300 /* errno is saved here so that error parameter eval can't change it */
301 edata->saved_errno = errno;
308 * errfinish --- end an error-reporting cycle
310 * Produce the appropriate error report(s) and pop the error stack.
312 * If elevel is ERROR or worse, control does not return to the caller.
313 * See elog.h for the error level definitions.
316 errfinish(int dummy,...)
318 ErrorData *edata = &errordata[errordata_stack_depth];
319 int elevel = edata->elevel;
320 MemoryContext oldcontext;
321 ErrorContextCallback *econtext;
327 * Do processing in ErrorContext, which we hope has enough reserved
328 * space to report an error.
330 oldcontext = MemoryContextSwitchTo(ErrorContext);
333 * Call any context callback functions. Errors occurring in callback
334 * functions will be treated as recursive errors --- this ensures we
335 * will avoid infinite recursion (see errstart).
337 for (econtext = error_context_stack;
339 econtext = econtext->previous)
340 (*econtext->callback) (econtext->arg);
342 /* Send to server log, if enabled */
343 if (edata->output_to_server)
344 send_message_to_server_log(edata);
347 * Abort any old-style COPY OUT in progress when an error is detected.
348 * This hack is necessary because of poor design of old-style copy
349 * protocol. Note we must do this even if client is fool enough to
350 * have set client_min_messages above ERROR, so don't look at
353 if (elevel >= ERROR && whereToSendOutput == Remote)
356 /* Send to client, if enabled */
357 if (edata->output_to_client)
358 send_message_to_frontend(edata);
360 /* Now free up subsidiary data attached to stack entry, and release it */
362 pfree(edata->message);
364 pfree(edata->detail);
368 pfree(edata->context);
369 if (edata->internalquery)
370 pfree(edata->internalquery);
372 MemoryContextSwitchTo(oldcontext);
374 errordata_stack_depth--;
378 * If the error level is ERROR or more, we are not going to return to
379 * caller; therefore, if there is any stacked error already in
380 * progress it will be lost. This is more or less okay, except we do
381 * not want to have a FATAL or PANIC error downgraded because the
382 * reporting process was interrupted by a lower-grade error. So check
383 * the stack and make sure we panic if panic is warranted.
389 for (i = 0; i <= errordata_stack_depth; i++)
390 elevel = Max(elevel, errordata[i].elevel);
393 * Also, be sure to reset the stack to empty. We do not clear
394 * ErrorContext here, though; PostgresMain does that later on.
396 errordata_stack_depth = -1;
398 error_context_stack = NULL;
402 * Perform error recovery action as specified by elevel.
404 if (elevel == ERROR || elevel == FATAL)
406 /* Prevent immediate interrupt while entering error recovery */
407 ImmediateInterruptOK = false;
410 * If we just reported a startup failure, the client will
411 * disconnect on receiving it, so don't send any more to the
414 if (!Warn_restart_ready && whereToSendOutput == Remote)
415 whereToSendOutput = None;
418 * For a FATAL error, we let proc_exit clean up and exit.
420 * There are several other cases in which we treat ERROR as FATAL and
421 * go directly to proc_exit:
423 * 1. ExitOnAnyError mode switch is set (initdb uses this).
425 * 2. we have not yet entered the main backend loop (ie, we are in
426 * the postmaster or in backend startup); we have noplace to
429 * 3. the error occurred after proc_exit has begun to run. (It's
430 * proc_exit's responsibility to see that this doesn't turn into
431 * infinite recursion!)
433 * In the last case, we exit with nonzero exit code to indicate that
434 * something's pretty wrong. We also want to exit with nonzero
435 * exit code if not running under the postmaster (for example, if
436 * we are being run from the initdb script, we'd better return an
439 if (elevel == FATAL ||
441 !Warn_restart_ready ||
442 proc_exit_inprogress)
445 * fflush here is just to improve the odds that we get to see
446 * the error message, in case things are so hosed that
447 * proc_exit crashes. Any other code you might be tempted to
448 * add here should probably be in an on_proc_exit callback
453 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
457 * Guard against infinite loop from errors during error recovery.
460 ereport(PANIC, (errmsg("error during error recovery, giving up")));
464 * Otherwise we can return to the main loop in postgres.c.
466 siglongjmp(Warn_restart, 1);
472 * Serious crash time. Postmaster will observe nonzero process
473 * exit status and kill the other backends too.
475 * XXX: what if we are *in* the postmaster? abort() won't kill our
478 ImmediateInterruptOK = false;
484 /* We reach here if elevel <= WARNING. OK to return to caller. */
489 * errcode --- add SQLSTATE error code to the current error
491 * The code is expected to be represented as per MAKE_SQLSTATE().
494 errcode(int sqlerrcode)
496 ErrorData *edata = &errordata[errordata_stack_depth];
498 /* we don't bother incrementing recursion_depth */
501 edata->sqlerrcode = sqlerrcode;
503 return 0; /* return value does not matter */
508 * errcode_for_file_access --- add SQLSTATE error code to the current error
510 * The SQLSTATE code is chosen based on the saved errno value. We assume
511 * that the failing operation was some type of disk file access.
513 * NOTE: the primary error message string should generally include %m
517 errcode_for_file_access(void)
519 ErrorData *edata = &errordata[errordata_stack_depth];
521 /* we don't bother incrementing recursion_depth */
524 switch (edata->saved_errno)
526 /* Permission-denied failures */
527 case EPERM: /* Not super-user */
528 case EACCES: /* Permission denied */
530 case EROFS: /* Read only file system */
532 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
536 case ENOENT: /* No such file or directory */
537 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
541 case EEXIST: /* File exists */
542 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
545 /* Wrong object type or state */
546 case ENOTDIR: /* Not a directory */
547 case EISDIR: /* Is a directory */
548 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
549 case ENOTEMPTY: /* Directory not empty */
551 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
554 /* Insufficient resources */
555 case ENOSPC: /* No space left on device */
556 edata->sqlerrcode = ERRCODE_DISK_FULL;
559 case ENFILE: /* File table overflow */
560 case EMFILE: /* Too many open files */
561 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
564 /* Hardware failure */
565 case EIO: /* I/O error */
566 edata->sqlerrcode = ERRCODE_IO_ERROR;
569 /* All else is classified as internal errors */
571 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
575 return 0; /* return value does not matter */
579 * errcode_for_socket_access --- add SQLSTATE error code to the current error
581 * The SQLSTATE code is chosen based on the saved errno value. We assume
582 * that the failing operation was some type of socket access.
584 * NOTE: the primary error message string should generally include %m
588 errcode_for_socket_access(void)
590 ErrorData *edata = &errordata[errordata_stack_depth];
592 /* we don't bother incrementing recursion_depth */
595 switch (edata->saved_errno)
597 /* Loss of connection */
602 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
605 /* All else is classified as internal errors */
607 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
611 return 0; /* return value does not matter */
616 * This macro handles expansion of a format string and associated parameters;
617 * it's common code for errmsg(), errdetail(), etc. Must be called inside
618 * a routine that is declared like "const char *fmt, ..." and has an edata
619 * pointer set up. The message is assigned to edata->targetfield, or
620 * appended to it if appendval is true.
622 * Note: we pstrdup the buffer rather than just transferring its storage
623 * to the edata field because the buffer might be considerably larger than
626 #define EVALUATE_MESSAGE(targetfield, appendval) \
629 StringInfoData buf; \
630 /* Internationalize the error format string */ \
631 fmt = gettext(fmt); \
632 /* Expand %m in format string */ \
633 fmtbuf = expand_fmt_string(fmt, edata); \
634 initStringInfo(&buf); \
635 if ((appendval) && edata->targetfield) \
636 appendStringInfo(&buf, "%s\n", edata->targetfield); \
637 /* Generate actual output --- have to use appendStringInfoVA */ \
642 va_start(args, fmt); \
643 success = appendStringInfoVA(&buf, fmtbuf, args); \
647 enlargeStringInfo(&buf, buf.maxlen); \
649 /* Done with expanded fmt */ \
651 /* Save the completed message into the stack item */ \
652 if (edata->targetfield) \
653 pfree(edata->targetfield); \
654 edata->targetfield = pstrdup(buf.data); \
660 * errmsg --- add a primary error message text to the current error
662 * In addition to the usual %-escapes recognized by printf, "%m" in
663 * fmt is replaced by the error message for the caller's value of errno.
665 * Note: no newline is needed at the end of the fmt string, since
666 * ereport will provide one for the output methods that need it.
669 errmsg(const char *fmt,...)
671 ErrorData *edata = &errordata[errordata_stack_depth];
672 MemoryContext oldcontext;
676 oldcontext = MemoryContextSwitchTo(ErrorContext);
678 EVALUATE_MESSAGE(message, false);
680 MemoryContextSwitchTo(oldcontext);
682 return 0; /* return value does not matter */
687 * errmsg_internal --- add a primary error message text to the current error
689 * This is exactly like errmsg() except that strings passed to errmsg_internal
690 * are customarily left out of the internationalization message dictionary.
691 * This should be used for "can't happen" cases that are probably not worth
692 * spending translation effort on.
695 errmsg_internal(const char *fmt,...)
697 ErrorData *edata = &errordata[errordata_stack_depth];
698 MemoryContext oldcontext;
702 oldcontext = MemoryContextSwitchTo(ErrorContext);
704 EVALUATE_MESSAGE(message, false);
706 MemoryContextSwitchTo(oldcontext);
708 return 0; /* return value does not matter */
713 * errdetail --- add a detail error message text to the current error
716 errdetail(const char *fmt,...)
718 ErrorData *edata = &errordata[errordata_stack_depth];
719 MemoryContext oldcontext;
723 oldcontext = MemoryContextSwitchTo(ErrorContext);
725 EVALUATE_MESSAGE(detail, false);
727 MemoryContextSwitchTo(oldcontext);
729 return 0; /* return value does not matter */
734 * errhint --- add a hint error message text to the current error
737 errhint(const char *fmt,...)
739 ErrorData *edata = &errordata[errordata_stack_depth];
740 MemoryContext oldcontext;
744 oldcontext = MemoryContextSwitchTo(ErrorContext);
746 EVALUATE_MESSAGE(hint, false);
748 MemoryContextSwitchTo(oldcontext);
750 return 0; /* return value does not matter */
755 * errcontext --- add a context error message text to the current error
757 * Unlike other cases, multiple calls are allowed to build up a stack of
758 * context information. We assume earlier calls represent more-closely-nested
762 errcontext(const char *fmt,...)
764 ErrorData *edata = &errordata[errordata_stack_depth];
765 MemoryContext oldcontext;
769 oldcontext = MemoryContextSwitchTo(ErrorContext);
771 EVALUATE_MESSAGE(context, true);
773 MemoryContextSwitchTo(oldcontext);
775 return 0; /* return value does not matter */
780 * errfunction --- add reporting function name to the current error
782 * This is used when backwards compatibility demands that the function
783 * name appear in messages sent to old-protocol clients. Note that the
784 * passed string is expected to be a non-freeable constant string.
787 errfunction(const char *funcname)
789 ErrorData *edata = &errordata[errordata_stack_depth];
791 /* we don't bother incrementing recursion_depth */
794 edata->funcname = funcname;
795 edata->show_funcname = true;
797 return 0; /* return value does not matter */
801 * errposition --- add cursor position to the current error
804 errposition(int cursorpos)
806 ErrorData *edata = &errordata[errordata_stack_depth];
808 /* we don't bother incrementing recursion_depth */
811 edata->cursorpos = cursorpos;
813 return 0; /* return value does not matter */
817 * internalerrposition --- add internal cursor position to the current error
820 internalerrposition(int cursorpos)
822 ErrorData *edata = &errordata[errordata_stack_depth];
824 /* we don't bother incrementing recursion_depth */
827 edata->internalpos = cursorpos;
829 return 0; /* return value does not matter */
833 * internalerrquery --- add internal query text to the current error
835 * Can also pass NULL to drop the internal query text entry. This case
836 * is intended for use in error callback subroutines that are editorializing
837 * on the layout of the error report.
840 internalerrquery(const char *query)
842 ErrorData *edata = &errordata[errordata_stack_depth];
844 /* we don't bother incrementing recursion_depth */
847 if (edata->internalquery)
849 pfree(edata->internalquery);
850 edata->internalquery = NULL;
854 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
856 return 0; /* return value does not matter */
860 * geterrposition --- return the currently set error position (0 if none)
862 * This is only intended for use in error callback subroutines, since there
863 * is no other place outside elog.c where the concept is meaningful.
868 ErrorData *edata = &errordata[errordata_stack_depth];
870 /* we don't bother incrementing recursion_depth */
873 return edata->cursorpos;
877 * getinternalerrposition --- same for internal error position
879 * This is only intended for use in error callback subroutines, since there
880 * is no other place outside elog.c where the concept is meaningful.
883 getinternalerrposition(void)
885 ErrorData *edata = &errordata[errordata_stack_depth];
887 /* we don't bother incrementing recursion_depth */
890 return edata->internalpos;
895 * elog_finish --- finish up for old-style API
897 * The elog() macro already called errstart, but with ERROR rather than
901 elog_finish(int elevel, const char *fmt,...)
903 ErrorData *edata = &errordata[errordata_stack_depth];
904 MemoryContext oldcontext;
909 * We need to redo errstart() because the elog macro had to call it
912 errordata_stack_depth--;
913 errno = edata->saved_errno;
914 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
915 return; /* nothing to do */
918 * Format error message just like errmsg().
921 oldcontext = MemoryContextSwitchTo(ErrorContext);
923 EVALUATE_MESSAGE(message, false);
925 MemoryContextSwitchTo(oldcontext);
929 * And let errfinish() finish up.
936 * Initialization of error output file
944 if (OutputFileName[0])
947 * A debug-output file name was given.
949 * Make sure we can write the file, and find out if it's a tty.
951 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
954 (errcode_for_file_access(),
955 errmsg("could not open file \"%s\": %m", OutputFileName)));
960 * Redirect our stderr to the debug output file.
962 if (!freopen(OutputFileName, "a", stderr))
964 (errcode_for_file_access(),
965 errmsg("could not reopen file \"%s\" as stderr: %m",
969 * If the file is a tty and we're running under the postmaster,
970 * try to send stdout there as well (if it isn't a tty then stderr
971 * will block out stdout, so we may as well let stdout go wherever
972 * it was going before).
974 if (istty && IsUnderPostmaster)
975 if (!freopen(OutputFileName, "a", stdout))
977 (errcode_for_file_access(),
978 errmsg("could not reopen file \"%s\" as stdout: %m",
987 #ifndef PG_SYSLOG_LIMIT
988 #define PG_SYSLOG_LIMIT 128
992 * Write a message line to syslog if the syslog option is set.
994 * Our problem here is that many syslog implementations don't handle
995 * long messages in an acceptable manner. While this function doesn't
996 * help that fact, it does work around by splitting up messages into
1000 write_syslog(int level, const char *line)
1002 static bool openlog_done = false;
1003 static unsigned long seq = 0;
1004 static int syslog_fac = LOG_LOCAL0;
1006 int len = strlen(line);
1008 if (Use_syslog == 0)
1013 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
1014 syslog_fac = LOG_LOCAL0;
1015 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
1016 syslog_fac = LOG_LOCAL1;
1017 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
1018 syslog_fac = LOG_LOCAL2;
1019 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
1020 syslog_fac = LOG_LOCAL3;
1021 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
1022 syslog_fac = LOG_LOCAL4;
1023 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
1024 syslog_fac = LOG_LOCAL5;
1025 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
1026 syslog_fac = LOG_LOCAL6;
1027 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
1028 syslog_fac = LOG_LOCAL7;
1029 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
1030 openlog_done = true;
1034 * We add a sequence number to each log message to suppress "same"
1039 /* divide into multiple syslog() calls if message is too long */
1040 /* or if the message contains embedded NewLine(s) '\n' */
1041 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1047 char buf[PG_SYSLOG_LIMIT + 1];
1051 /* if we start at a newline, move ahead one char */
1052 if (line[0] == '\n')
1059 strncpy(buf, line, PG_SYSLOG_LIMIT);
1060 buf[PG_SYSLOG_LIMIT] = '\0';
1061 if (strchr(buf, '\n') != NULL)
1062 *strchr(buf, '\n') = '\0';
1064 buflen = strlen(buf);
1066 /* trim to multibyte letter boundary */
1067 buflen = pg_mbcliplen(buf, buflen, buflen);
1072 /* already word boundary? */
1073 if (!isspace((unsigned char) line[buflen]) &&
1074 line[buflen] != '\0')
1076 /* try to divide at word boundary */
1078 while (i > 0 && !isspace((unsigned char) buf[i]))
1081 if (i > 0) /* else couldn't divide word boundary */
1090 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1097 /* message short enough */
1098 syslog(level, "[%lu] %s", seq, line);
1101 #endif /* HAVE_SYSLOG */
1104 * Format tag info for log lines; append to the provided buffer.
1107 log_line_prefix(StringInfo buf)
1109 /* static counter for line numbers */
1110 static long log_line_number = 0;
1111 /* has counter been reset in current process? */
1112 static int log_my_pid = 0;
1118 * This is one of the few places where we'd rather not inherit a
1119 * static variable's value from the postmaster. But since we will,
1120 * reset it when MyProcPid changes.
1122 if (log_my_pid != MyProcPid)
1124 log_line_number = 0;
1125 log_my_pid = MyProcPid;
1129 if (Log_line_prefix == NULL)
1130 return; /* in case guc hasn't run yet */
1132 format_len = strlen(Log_line_prefix);
1134 for (i = 0; i < format_len; i++)
1136 if (Log_line_prefix[i] != '%')
1138 /* literal char, just copy */
1139 appendStringInfoChar(buf, Log_line_prefix[i]);
1142 /* go to char after '%' */
1144 if (i >= format_len)
1146 /* format error - ignore it */
1150 /* process the option */
1151 switch (Log_line_prefix[i])
1156 const char *username = MyProcPort->user_name;
1158 if (username == NULL || *username == '\0')
1159 username = gettext("[unknown]");
1160 appendStringInfo(buf, "%s", username);
1166 const char *dbname = MyProcPort->database_name;
1168 if (dbname == NULL || *dbname == '\0')
1169 dbname = gettext("[unknown]");
1170 appendStringInfo(buf, "%s", dbname);
1176 appendStringInfo(buf, "%lx.%lx",
1177 (long)(MyProcPort->session_start.tv_sec),
1182 appendStringInfo(buf, "%ld", (long)MyProcPid);
1185 appendStringInfo(buf, "%ld", log_line_number);
1189 time_t stamp_time = time(NULL);
1192 strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S",
1193 localtime(&stamp_time));
1194 appendStringInfoString(buf, strfbuf);
1200 time_t stamp_time = MyProcPort->session_start.tv_sec;
1203 strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S",
1204 localtime(&stamp_time));
1205 appendStringInfoString(buf, strfbuf);
1211 appendStringInfo(buf, "%s", MyProcPort->commandTag);
1217 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1218 if (strlen(MyProcPort->remote_port) > 0)
1219 appendStringInfo(buf, "(%s)",
1220 MyProcPort->remote_port);
1224 /* in postmaster and friends, stop if %x is seen */
1225 /* in a backend, just ignore */
1226 if (MyProcPort == NULL)
1230 appendStringInfoChar(buf, '%');
1233 /* format error - ignore it */
1241 * Write error report to server's log
1244 send_message_to_server_log(ErrorData *edata)
1248 initStringInfo(&buf);
1250 log_line_prefix(&buf);
1251 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1253 if (Log_error_verbosity >= PGERROR_VERBOSE)
1255 /* unpack MAKE_SQLSTATE code */
1260 ssval = edata->sqlerrcode;
1261 for (i = 0; i < 5; i++)
1263 tbuf[i] = PGUNSIXBIT(ssval);
1267 appendStringInfo(&buf, "%s: ", tbuf);
1271 append_with_tabs(&buf, edata->message);
1273 append_with_tabs(&buf, gettext("missing error text"));
1275 if (edata->cursorpos > 0)
1276 appendStringInfo(&buf, gettext(" at character %d"),
1278 else if (edata->internalpos > 0)
1279 appendStringInfo(&buf, gettext(" at character %d"),
1280 edata->internalpos);
1282 appendStringInfoChar(&buf, '\n');
1284 if (Log_error_verbosity >= PGERROR_DEFAULT)
1288 log_line_prefix(&buf);
1289 appendStringInfoString(&buf, gettext("DETAIL: "));
1290 append_with_tabs(&buf, edata->detail);
1291 appendStringInfoChar(&buf, '\n');
1295 log_line_prefix(&buf);
1296 appendStringInfoString(&buf, gettext("HINT: "));
1297 append_with_tabs(&buf, edata->hint);
1298 appendStringInfoChar(&buf, '\n');
1300 if (edata->internalquery)
1302 log_line_prefix(&buf);
1303 appendStringInfoString(&buf, gettext("QUERY: "));
1304 append_with_tabs(&buf, edata->internalquery);
1305 appendStringInfoChar(&buf, '\n');
1309 log_line_prefix(&buf);
1310 appendStringInfoString(&buf, gettext("CONTEXT: "));
1311 append_with_tabs(&buf, edata->context);
1312 appendStringInfoChar(&buf, '\n');
1314 if (Log_error_verbosity >= PGERROR_VERBOSE)
1316 /* assume no newlines in funcname or filename... */
1317 if (edata->funcname && edata->filename)
1319 log_line_prefix(&buf);
1320 appendStringInfo(&buf, gettext("LOCATION: %s, %s:%d\n"),
1321 edata->funcname, edata->filename,
1324 else if (edata->filename)
1326 log_line_prefix(&buf);
1327 appendStringInfo(&buf, gettext("LOCATION: %s:%d\n"),
1328 edata->filename, edata->lineno);
1334 * If the user wants the query that generated this error logged, do it.
1336 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1338 log_line_prefix(&buf);
1339 appendStringInfoString(&buf, gettext("STATEMENT: "));
1340 append_with_tabs(&buf, debug_query_string);
1341 appendStringInfoChar(&buf, '\n');
1346 /* Write to syslog, if enabled */
1347 if (Use_syslog >= 1)
1351 switch (edata->elevel)
1358 syslog_level = LOG_DEBUG;
1363 syslog_level = LOG_INFO;
1367 syslog_level = LOG_NOTICE;
1370 syslog_level = LOG_WARNING;
1373 syslog_level = LOG_ERR;
1377 syslog_level = LOG_CRIT;
1381 write_syslog(syslog_level, buf.data);
1383 #endif /* HAVE_SYSLOG */
1385 /* Write to stderr, if enabled */
1386 if (Use_syslog <= 1 || whereToSendOutput == Debug)
1388 fprintf(stderr, "%s", buf.data);
1396 * Write error report to client
1399 send_message_to_frontend(ErrorData *edata)
1401 StringInfoData msgbuf;
1403 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1404 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1406 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1408 /* New style with separate fields */
1413 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1414 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1416 /* unpack MAKE_SQLSTATE code */
1417 ssval = edata->sqlerrcode;
1418 for (i = 0; i < 5; i++)
1420 tbuf[i] = PGUNSIXBIT(ssval);
1425 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1426 pq_sendstring(&msgbuf, tbuf);
1428 /* M field is required per protocol, so always send something */
1429 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1431 pq_sendstring(&msgbuf, edata->message);
1433 pq_sendstring(&msgbuf, gettext("missing error text"));
1437 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1438 pq_sendstring(&msgbuf, edata->detail);
1443 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1444 pq_sendstring(&msgbuf, edata->hint);
1449 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1450 pq_sendstring(&msgbuf, edata->context);
1453 if (edata->cursorpos > 0)
1455 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1456 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1457 pq_sendstring(&msgbuf, tbuf);
1460 if (edata->internalpos > 0)
1462 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1463 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1464 pq_sendstring(&msgbuf, tbuf);
1467 if (edata->internalquery)
1469 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1470 pq_sendstring(&msgbuf, edata->internalquery);
1473 if (edata->filename)
1475 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1476 pq_sendstring(&msgbuf, edata->filename);
1479 if (edata->lineno > 0)
1481 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1482 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1483 pq_sendstring(&msgbuf, tbuf);
1486 if (edata->funcname)
1488 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1489 pq_sendstring(&msgbuf, edata->funcname);
1492 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1496 /* Old style --- gin up a backwards-compatible message */
1499 initStringInfo(&buf);
1501 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1503 if (edata->show_funcname && edata->funcname)
1504 appendStringInfo(&buf, "%s: ", edata->funcname);
1507 appendStringInfoString(&buf, edata->message);
1509 appendStringInfoString(&buf, gettext("missing error text"));
1511 if (edata->cursorpos > 0)
1512 appendStringInfo(&buf, gettext(" at character %d"),
1514 else if (edata->internalpos > 0)
1515 appendStringInfo(&buf, gettext(" at character %d"),
1516 edata->internalpos);
1518 appendStringInfoChar(&buf, '\n');
1520 pq_sendstring(&msgbuf, buf.data);
1525 pq_endmessage(&msgbuf);
1528 * This flush is normally not necessary, since postgres.c will flush
1529 * out waiting data when control returns to the main loop. But it
1530 * seems best to leave it here, so that the client has some clue what
1531 * happened if the backend dies before getting back to the main loop
1532 * ... error/notice messages should not be a performance-critical path
1533 * anyway, so an extra flush won't hurt much ...
1540 * Support routines for formatting error messages.
1545 * expand_fmt_string --- process special format codes in a format string
1547 * We must replace %m with the appropriate strerror string, since vsnprintf
1548 * won't know what to do with it.
1550 * The result is a palloc'd string.
1553 expand_fmt_string(const char *fmt, ErrorData *edata)
1558 initStringInfo(&buf);
1560 for (cp = fmt; *cp; cp++)
1562 if (cp[0] == '%' && cp[1] != '\0')
1568 * Replace %m by system error string. If there are any
1569 * %'s in the string, we'd better double them so that
1570 * vsnprintf won't misinterpret.
1574 cp2 = useful_strerror(edata->saved_errno);
1578 appendStringInfoCharMacro(&buf, '%');
1579 appendStringInfoCharMacro(&buf, *cp2);
1584 /* copy % and next char --- this avoids trouble with %%m */
1585 appendStringInfoCharMacro(&buf, '%');
1586 appendStringInfoCharMacro(&buf, *cp);
1590 appendStringInfoCharMacro(&buf, *cp);
1598 * A slightly cleaned-up version of strerror()
1601 useful_strerror(int errnum)
1603 /* this buffer is only used if errno has a bogus value */
1604 static char errorstr_buf[48];
1607 str = strerror(errnum);
1610 * Some strerror()s return an empty string for out-of-range errno.
1611 * This is ANSI C spec compliant, but not exactly useful.
1613 if (str == NULL || *str == '\0')
1616 * translator: This string will be truncated at 47 characters
1619 snprintf(errorstr_buf, sizeof(errorstr_buf),
1620 gettext("operating system error %d"), errnum);
1629 * error_severity --- get localized string representing elevel
1632 error_severity(int elevel)
1643 prefix = gettext("DEBUG");
1647 prefix = gettext("LOG");
1650 prefix = gettext("INFO");
1653 prefix = gettext("NOTICE");
1656 prefix = gettext("WARNING");
1659 prefix = gettext("ERROR");
1662 prefix = gettext("FATAL");
1665 prefix = gettext("PANIC");
1679 * Append the string to the StringInfo buffer, inserting a tab after any
1683 append_with_tabs(StringInfo buf, const char *str)
1687 while ((ch = *str++) != '\0')
1689 appendStringInfoCharMacro(buf, ch);
1691 appendStringInfoCharMacro(buf, '\t');