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.141 2004/06/21 14:12:38 tgl Exp $
42 *-------------------------------------------------------------------------
56 #include "libpq/libpq.h"
57 #include "libpq/pqformat.h"
58 #include "mb/pg_wchar.h"
59 #include "miscadmin.h"
60 #include "postmaster/postmaster.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 */
73 unsigned int Log_destination = LOG_DESTINATION_STDERR;
75 bool in_fatal_exit = false;
78 char *Syslog_facility; /* openlog() parameters */
81 static void write_syslog(int level, const char *line);
84 static void write_eventlog(int level, const char *line);
88 * ErrorData holds the data accumulated during any one ereport() cycle.
89 * Any non-NULL pointers must point to palloc'd data in ErrorContext.
90 * (The const pointers are an exception; we assume they point at non-freeable
94 typedef struct ErrorData
96 int elevel; /* error level */
97 bool output_to_server; /* will report to server log? */
98 bool output_to_client; /* will report to client? */
99 bool show_funcname; /* true to force funcname inclusion */
100 const char *filename; /* __FILE__ of ereport() call */
101 int lineno; /* __LINE__ of ereport() call */
102 const char *funcname; /* __func__ of ereport() call */
103 int sqlerrcode; /* encoded ERRSTATE */
104 char *message; /* primary error message */
105 char *detail; /* detail error message */
106 char *hint; /* hint message */
107 char *context; /* context message */
108 int cursorpos; /* cursor index into query string */
109 int internalpos; /* cursor index into internalquery */
110 char *internalquery; /* text of internally-generated query */
111 int saved_errno; /* errno at entry */
114 /* We provide a small stack of ErrorData records for re-entrant cases */
115 #define ERRORDATA_STACK_SIZE 5
117 static ErrorData errordata[ERRORDATA_STACK_SIZE];
119 static int errordata_stack_depth = -1; /* index of topmost active frame */
121 static int recursion_depth = 0; /* to detect actual recursion */
124 /* Macro for checking errordata_stack_depth is reasonable */
125 #define CHECK_STACK_DEPTH() \
127 if (errordata_stack_depth < 0) \
129 errordata_stack_depth = -1; \
130 ereport(ERROR, (errmsg_internal("errstart was not called"))); \
135 static void log_line_prefix(StringInfo buf);
136 static void send_message_to_server_log(ErrorData *edata);
137 static void send_message_to_frontend(ErrorData *edata);
138 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
139 static const char *useful_strerror(int errnum);
140 static const char *error_severity(int elevel);
141 static void append_with_tabs(StringInfo buf, const char *str);
145 * errstart --- begin an error-reporting cycle
147 * Create a stack entry and store the given parameters in it. Subsequently,
148 * errmsg() and perhaps other routines will be called to further populate
149 * the stack entry. Finally, errfinish() will be called to actually process
152 * Returns TRUE in normal case. Returns FALSE to short-circuit the error
153 * report (if it's a warning or lower and not to be reported anywhere).
156 errstart(int elevel, const char *filename, int lineno,
157 const char *funcname)
160 bool output_to_server = false;
161 bool output_to_client = false;
164 * First decide whether we need to process this report at all; if it's
165 * warning or less and not enabled for logging, just return FALSE
166 * without starting up any error logging machinery.
170 * Convert initialization errors into fatal errors. This is probably
171 * redundant, because Warn_restart_ready won't be set anyway.
173 if (elevel == ERROR && IsInitProcessingMode())
177 * If we are inside a critical section, all errors become PANIC
178 * errors. See miscadmin.h.
182 if (CritSectionCount > 0)
186 /* Determine whether message is enabled for server log output */
187 if (IsPostmasterEnvironment)
189 /* Complicated because LOG is sorted out-of-order for this purpose */
190 if (elevel == LOG || elevel == COMMERROR)
192 if (log_min_messages == LOG)
193 output_to_server = true;
194 else if (log_min_messages < FATAL)
195 output_to_server = true;
200 if (log_min_messages == LOG)
203 output_to_server = true;
206 else if (elevel >= log_min_messages)
207 output_to_server = true;
212 /* In bootstrap/standalone case, do not sort LOG out-of-order */
213 output_to_server = (elevel >= log_min_messages);
216 /* Determine whether message is enabled for client output */
217 if (whereToSendOutput == Remote && elevel != COMMERROR)
220 * client_min_messages is honored only after we complete the
221 * authentication handshake. This is required both for security
222 * reasons and because many clients can't handle NOTICE messages
223 * during authentication.
225 if (ClientAuthInProgress)
226 output_to_client = (elevel >= ERROR);
228 output_to_client = (elevel >= client_min_messages ||
232 /* Skip processing effort if non-error message will not be output */
233 if (elevel < ERROR && !output_to_server && !output_to_client)
237 * Okay, crank up a stack entry to store the info in.
240 if (recursion_depth++ > 0)
243 * Ooops, error during error processing. Clear ErrorContext and
244 * force level up to ERROR or greater, as discussed at top of
245 * file. Adjust output decisions too.
247 MemoryContextReset(ErrorContext);
248 output_to_server = true;
249 if (whereToSendOutput == Remote && elevel != COMMERROR)
250 output_to_client = true;
251 elevel = Max(elevel, ERROR);
254 * If we recurse more than once, the problem might be something
255 * broken in a context traceback routine. Abandon them too.
257 if (recursion_depth > 2)
258 error_context_stack = NULL;
260 if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
262 /* Wups, stack not big enough */
265 elevel = Max(elevel, ERROR);
268 * Don't forget any FATAL/PANIC status on the stack (see comments
271 for (i = 0; i < errordata_stack_depth; i++)
272 elevel = Max(elevel, errordata[i].elevel);
273 /* Clear the stack and try again */
274 errordata_stack_depth = -1;
275 ereport(elevel, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
278 /* Initialize data for this error frame */
279 edata = &errordata[errordata_stack_depth];
280 MemSet(edata, 0, sizeof(ErrorData));
281 edata->elevel = elevel;
282 edata->output_to_server = output_to_server;
283 edata->output_to_client = output_to_client;
284 edata->filename = filename;
285 edata->lineno = lineno;
286 edata->funcname = funcname;
287 /* Select default errcode based on elevel */
289 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
290 else if (elevel == WARNING)
291 edata->sqlerrcode = ERRCODE_WARNING;
293 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
294 /* errno is saved here so that error parameter eval can't change it */
295 edata->saved_errno = errno;
302 * errfinish --- end an error-reporting cycle
304 * Produce the appropriate error report(s) and pop the error stack.
306 * If elevel is ERROR or worse, control does not return to the caller.
307 * See elog.h for the error level definitions.
310 errfinish(int dummy,...)
312 ErrorData *edata = &errordata[errordata_stack_depth];
313 int elevel = edata->elevel;
314 MemoryContext oldcontext;
315 ErrorContextCallback *econtext;
321 * Do processing in ErrorContext, which we hope has enough reserved
322 * space to report an error.
324 oldcontext = MemoryContextSwitchTo(ErrorContext);
327 * Call any context callback functions. Errors occurring in callback
328 * functions will be treated as recursive errors --- this ensures we
329 * will avoid infinite recursion (see errstart).
331 for (econtext = error_context_stack;
333 econtext = econtext->previous)
334 (*econtext->callback) (econtext->arg);
336 /* Send to server log, if enabled */
337 if (edata->output_to_server)
338 send_message_to_server_log(edata);
341 * Abort any old-style COPY OUT in progress when an error is detected.
342 * This hack is necessary because of poor design of old-style copy
343 * protocol. Note we must do this even if client is fool enough to
344 * have set client_min_messages above ERROR, so don't look at
347 if (elevel >= ERROR && whereToSendOutput == Remote)
350 /* Send to client, if enabled */
351 if (edata->output_to_client)
352 send_message_to_frontend(edata);
354 /* Now free up subsidiary data attached to stack entry, and release it */
356 pfree(edata->message);
358 pfree(edata->detail);
362 pfree(edata->context);
363 if (edata->internalquery)
364 pfree(edata->internalquery);
366 MemoryContextSwitchTo(oldcontext);
368 errordata_stack_depth--;
372 * If the error level is ERROR or more, we are not going to return to
373 * caller; therefore, if there is any stacked error already in
374 * progress it will be lost. This is more or less okay, except we do
375 * not want to have a FATAL or PANIC error downgraded because the
376 * reporting process was interrupted by a lower-grade error. So check
377 * the stack and make sure we panic if panic is warranted.
383 for (i = 0; i <= errordata_stack_depth; i++)
384 elevel = Max(elevel, errordata[i].elevel);
387 * Also, be sure to reset the stack to empty. We do not clear
388 * ErrorContext here, though; PostgresMain does that later on.
390 errordata_stack_depth = -1;
392 error_context_stack = NULL;
396 * Perform error recovery action as specified by elevel.
398 if (elevel == ERROR || elevel == FATAL)
400 /* Prevent immediate interrupt while entering error recovery */
401 ImmediateInterruptOK = false;
404 * If we just reported a startup failure, the client will
405 * disconnect on receiving it, so don't send any more to the
408 if (!Warn_restart_ready && whereToSendOutput == Remote)
409 whereToSendOutput = None;
412 * For a FATAL error, we let proc_exit clean up and exit.
414 * There are several other cases in which we treat ERROR as FATAL and
415 * go directly to proc_exit:
417 * 1. ExitOnAnyError mode switch is set (initdb uses this).
419 * 2. we have not yet entered the main backend loop (ie, we are in
420 * the postmaster or in backend startup); we have noplace to
423 * 3. the error occurred after proc_exit has begun to run. (It's
424 * proc_exit's responsibility to see that this doesn't turn into
425 * infinite recursion!)
427 * In the last case, we exit with nonzero exit code to indicate that
428 * something's pretty wrong. We also want to exit with nonzero
429 * exit code if not running under the postmaster (for example, if
430 * we are being run from the initdb script, we'd better return an
433 if (elevel == FATAL ||
435 !Warn_restart_ready ||
436 proc_exit_inprogress)
439 * fflush here is just to improve the odds that we get to see
440 * the error message, in case things are so hosed that
441 * proc_exit crashes. Any other code you might be tempted to
442 * add here should probably be in an on_proc_exit callback
449 ereport(PANIC, (errmsg("fatal error during fatal exit, giving up")));
451 /* not safe to longjump */
452 if (!Warn_restart_ready || proc_exit_inprogress)
453 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
455 /* We will exit the backend by simulating a client EOF */
456 in_fatal_exit = true;
460 * Guard against infinite loop from errors during error recovery.
463 ereport(PANIC, (errmsg("error during error recovery, giving up")));
467 * Otherwise we can return to the main loop in postgres.c.
469 siglongjmp(Warn_restart, 1);
475 * Serious crash time. Postmaster will observe nonzero process
476 * exit status and kill the other backends too.
478 * XXX: what if we are *in* the postmaster? abort() won't kill our
481 ImmediateInterruptOK = false;
487 /* We reach here if elevel <= WARNING. OK to return to caller. */
492 * errcode --- add SQLSTATE error code to the current error
494 * The code is expected to be represented as per MAKE_SQLSTATE().
497 errcode(int sqlerrcode)
499 ErrorData *edata = &errordata[errordata_stack_depth];
501 /* we don't bother incrementing recursion_depth */
504 edata->sqlerrcode = sqlerrcode;
506 return 0; /* return value does not matter */
511 * errcode_for_file_access --- add SQLSTATE error code to the current error
513 * The SQLSTATE code is chosen based on the saved errno value. We assume
514 * that the failing operation was some type of disk file access.
516 * NOTE: the primary error message string should generally include %m
520 errcode_for_file_access(void)
522 ErrorData *edata = &errordata[errordata_stack_depth];
524 /* we don't bother incrementing recursion_depth */
527 switch (edata->saved_errno)
529 /* Permission-denied failures */
530 case EPERM: /* Not super-user */
531 case EACCES: /* Permission denied */
533 case EROFS: /* Read only file system */
535 edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
539 case ENOENT: /* No such file or directory */
540 edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
544 case EEXIST: /* File exists */
545 edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
548 /* Wrong object type or state */
549 case ENOTDIR: /* Not a directory */
550 case EISDIR: /* Is a directory */
551 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
552 case ENOTEMPTY: /* Directory not empty */
554 edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
557 /* Insufficient resources */
558 case ENOSPC: /* No space left on device */
559 edata->sqlerrcode = ERRCODE_DISK_FULL;
562 case ENFILE: /* File table overflow */
563 case EMFILE: /* Too many open files */
564 edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
567 /* Hardware failure */
568 case EIO: /* I/O error */
569 edata->sqlerrcode = ERRCODE_IO_ERROR;
572 /* All else is classified as internal errors */
574 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
578 return 0; /* return value does not matter */
582 * errcode_for_socket_access --- add SQLSTATE error code to the current error
584 * The SQLSTATE code is chosen based on the saved errno value. We assume
585 * that the failing operation was some type of socket access.
587 * NOTE: the primary error message string should generally include %m
591 errcode_for_socket_access(void)
593 ErrorData *edata = &errordata[errordata_stack_depth];
595 /* we don't bother incrementing recursion_depth */
598 switch (edata->saved_errno)
600 /* Loss of connection */
605 edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
608 /* All else is classified as internal errors */
610 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
614 return 0; /* return value does not matter */
619 * This macro handles expansion of a format string and associated parameters;
620 * it's common code for errmsg(), errdetail(), etc. Must be called inside
621 * a routine that is declared like "const char *fmt, ..." and has an edata
622 * pointer set up. The message is assigned to edata->targetfield, or
623 * appended to it if appendval is true.
625 * Note: we pstrdup the buffer rather than just transferring its storage
626 * to the edata field because the buffer might be considerably larger than
629 #define EVALUATE_MESSAGE(targetfield, appendval) \
632 StringInfoData buf; \
633 /* Internationalize the error format string */ \
634 fmt = gettext(fmt); \
635 /* Expand %m in format string */ \
636 fmtbuf = expand_fmt_string(fmt, edata); \
637 initStringInfo(&buf); \
638 if ((appendval) && edata->targetfield) \
639 appendStringInfo(&buf, "%s\n", edata->targetfield); \
640 /* Generate actual output --- have to use appendStringInfoVA */ \
645 va_start(args, fmt); \
646 success = appendStringInfoVA(&buf, fmtbuf, args); \
650 enlargeStringInfo(&buf, buf.maxlen); \
652 /* Done with expanded fmt */ \
654 /* Save the completed message into the stack item */ \
655 if (edata->targetfield) \
656 pfree(edata->targetfield); \
657 edata->targetfield = pstrdup(buf.data); \
663 * errmsg --- add a primary error message text to the current error
665 * In addition to the usual %-escapes recognized by printf, "%m" in
666 * fmt is replaced by the error message for the caller's value of errno.
668 * Note: no newline is needed at the end of the fmt string, since
669 * ereport will provide one for the output methods that need it.
672 errmsg(const char *fmt,...)
674 ErrorData *edata = &errordata[errordata_stack_depth];
675 MemoryContext oldcontext;
679 oldcontext = MemoryContextSwitchTo(ErrorContext);
681 EVALUATE_MESSAGE(message, false);
683 MemoryContextSwitchTo(oldcontext);
685 return 0; /* return value does not matter */
690 * errmsg_internal --- add a primary error message text to the current error
692 * This is exactly like errmsg() except that strings passed to errmsg_internal
693 * are customarily left out of the internationalization message dictionary.
694 * This should be used for "can't happen" cases that are probably not worth
695 * spending translation effort on.
698 errmsg_internal(const char *fmt,...)
700 ErrorData *edata = &errordata[errordata_stack_depth];
701 MemoryContext oldcontext;
705 oldcontext = MemoryContextSwitchTo(ErrorContext);
707 EVALUATE_MESSAGE(message, false);
709 MemoryContextSwitchTo(oldcontext);
711 return 0; /* return value does not matter */
716 * errdetail --- add a detail error message text to the current error
719 errdetail(const char *fmt,...)
721 ErrorData *edata = &errordata[errordata_stack_depth];
722 MemoryContext oldcontext;
726 oldcontext = MemoryContextSwitchTo(ErrorContext);
728 EVALUATE_MESSAGE(detail, false);
730 MemoryContextSwitchTo(oldcontext);
732 return 0; /* return value does not matter */
737 * errhint --- add a hint error message text to the current error
740 errhint(const char *fmt,...)
742 ErrorData *edata = &errordata[errordata_stack_depth];
743 MemoryContext oldcontext;
747 oldcontext = MemoryContextSwitchTo(ErrorContext);
749 EVALUATE_MESSAGE(hint, false);
751 MemoryContextSwitchTo(oldcontext);
753 return 0; /* return value does not matter */
758 * errcontext --- add a context error message text to the current error
760 * Unlike other cases, multiple calls are allowed to build up a stack of
761 * context information. We assume earlier calls represent more-closely-nested
765 errcontext(const char *fmt,...)
767 ErrorData *edata = &errordata[errordata_stack_depth];
768 MemoryContext oldcontext;
772 oldcontext = MemoryContextSwitchTo(ErrorContext);
774 EVALUATE_MESSAGE(context, true);
776 MemoryContextSwitchTo(oldcontext);
778 return 0; /* return value does not matter */
783 * errfunction --- add reporting function name to the current error
785 * This is used when backwards compatibility demands that the function
786 * name appear in messages sent to old-protocol clients. Note that the
787 * passed string is expected to be a non-freeable constant string.
790 errfunction(const char *funcname)
792 ErrorData *edata = &errordata[errordata_stack_depth];
794 /* we don't bother incrementing recursion_depth */
797 edata->funcname = funcname;
798 edata->show_funcname = true;
800 return 0; /* return value does not matter */
804 * errposition --- add cursor position to the current error
807 errposition(int cursorpos)
809 ErrorData *edata = &errordata[errordata_stack_depth];
811 /* we don't bother incrementing recursion_depth */
814 edata->cursorpos = cursorpos;
816 return 0; /* return value does not matter */
820 * internalerrposition --- add internal cursor position to the current error
823 internalerrposition(int cursorpos)
825 ErrorData *edata = &errordata[errordata_stack_depth];
827 /* we don't bother incrementing recursion_depth */
830 edata->internalpos = cursorpos;
832 return 0; /* return value does not matter */
836 * internalerrquery --- add internal query text to the current error
838 * Can also pass NULL to drop the internal query text entry. This case
839 * is intended for use in error callback subroutines that are editorializing
840 * on the layout of the error report.
843 internalerrquery(const char *query)
845 ErrorData *edata = &errordata[errordata_stack_depth];
847 /* we don't bother incrementing recursion_depth */
850 if (edata->internalquery)
852 pfree(edata->internalquery);
853 edata->internalquery = NULL;
857 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
859 return 0; /* return value does not matter */
863 * geterrposition --- return the currently set error position (0 if none)
865 * This is only intended for use in error callback subroutines, since there
866 * is no other place outside elog.c where the concept is meaningful.
871 ErrorData *edata = &errordata[errordata_stack_depth];
873 /* we don't bother incrementing recursion_depth */
876 return edata->cursorpos;
880 * getinternalerrposition --- same for internal error position
882 * This is only intended for use in error callback subroutines, since there
883 * is no other place outside elog.c where the concept is meaningful.
886 getinternalerrposition(void)
888 ErrorData *edata = &errordata[errordata_stack_depth];
890 /* we don't bother incrementing recursion_depth */
893 return edata->internalpos;
898 * elog_finish --- finish up for old-style API
900 * The elog() macro already called errstart, but with ERROR rather than
904 elog_finish(int elevel, const char *fmt,...)
906 ErrorData *edata = &errordata[errordata_stack_depth];
907 MemoryContext oldcontext;
912 * We need to redo errstart() because the elog macro had to call it
915 errordata_stack_depth--;
916 errno = edata->saved_errno;
917 if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
918 return; /* nothing to do */
921 * Format error message just like errmsg().
924 oldcontext = MemoryContextSwitchTo(ErrorContext);
926 EVALUATE_MESSAGE(message, false);
928 MemoryContextSwitchTo(oldcontext);
932 * And let errfinish() finish up.
939 * Initialization of error output file
947 if (OutputFileName[0])
950 * A debug-output file name was given.
952 * Make sure we can write the file, and find out if it's a tty.
954 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
957 (errcode_for_file_access(),
958 errmsg("could not open file \"%s\": %m", OutputFileName)));
963 * Redirect our stderr to the debug output file.
965 if (!freopen(OutputFileName, "a", stderr))
967 (errcode_for_file_access(),
968 errmsg("could not reopen file \"%s\" as stderr: %m",
972 * If the file is a tty and we're running under the postmaster,
973 * try to send stdout there as well (if it isn't a tty then stderr
974 * will block out stdout, so we may as well let stdout go wherever
975 * it was going before).
977 if (istty && IsUnderPostmaster)
978 if (!freopen(OutputFileName, "a", stdout))
980 (errcode_for_file_access(),
981 errmsg("could not reopen file \"%s\" as stdout: %m",
990 #ifndef PG_SYSLOG_LIMIT
991 #define PG_SYSLOG_LIMIT 128
995 * Write a message line to syslog if the syslog option is set.
997 * Our problem here is that many syslog implementations don't handle
998 * long messages in an acceptable manner. While this function doesn't
999 * help that fact, it does work around by splitting up messages into
1003 write_syslog(int level, const char *line)
1005 static bool openlog_done = false;
1006 static unsigned long seq = 0;
1007 static int syslog_fac = LOG_LOCAL0;
1009 int len = strlen(line);
1013 if (pg_strcasecmp(Syslog_facility, "LOCAL0") == 0)
1014 syslog_fac = LOG_LOCAL0;
1015 if (pg_strcasecmp(Syslog_facility, "LOCAL1") == 0)
1016 syslog_fac = LOG_LOCAL1;
1017 if (pg_strcasecmp(Syslog_facility, "LOCAL2") == 0)
1018 syslog_fac = LOG_LOCAL2;
1019 if (pg_strcasecmp(Syslog_facility, "LOCAL3") == 0)
1020 syslog_fac = LOG_LOCAL3;
1021 if (pg_strcasecmp(Syslog_facility, "LOCAL4") == 0)
1022 syslog_fac = LOG_LOCAL4;
1023 if (pg_strcasecmp(Syslog_facility, "LOCAL5") == 0)
1024 syslog_fac = LOG_LOCAL5;
1025 if (pg_strcasecmp(Syslog_facility, "LOCAL6") == 0)
1026 syslog_fac = LOG_LOCAL6;
1027 if (pg_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 * Write a message line to the windows event log
1107 write_eventlog(int level, const char *line)
1109 static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1111 if (evtHandle == INVALID_HANDLE_VALUE) {
1112 evtHandle = RegisterEventSource(NULL,"PostgreSQL");
1113 if (evtHandle == NULL) {
1114 evtHandle = INVALID_HANDLE_VALUE;
1119 ReportEvent(evtHandle,
1122 0, /* All events are Id 0 */
1132 * Format tag info for log lines; append to the provided buffer.
1135 log_line_prefix(StringInfo buf)
1137 /* static counter for line numbers */
1138 static long log_line_number = 0;
1139 /* has counter been reset in current process? */
1140 static int log_my_pid = 0;
1146 * This is one of the few places where we'd rather not inherit a
1147 * static variable's value from the postmaster. But since we will,
1148 * reset it when MyProcPid changes.
1150 if (log_my_pid != MyProcPid)
1152 log_line_number = 0;
1153 log_my_pid = MyProcPid;
1157 if (Log_line_prefix == NULL)
1158 return; /* in case guc hasn't run yet */
1160 format_len = strlen(Log_line_prefix);
1162 for (i = 0; i < format_len; i++)
1164 if (Log_line_prefix[i] != '%')
1166 /* literal char, just copy */
1167 appendStringInfoChar(buf, Log_line_prefix[i]);
1170 /* go to char after '%' */
1172 if (i >= format_len)
1174 /* format error - ignore it */
1178 /* process the option */
1179 switch (Log_line_prefix[i])
1184 const char *username = MyProcPort->user_name;
1186 if (username == NULL || *username == '\0')
1187 username = gettext("[unknown]");
1188 appendStringInfo(buf, "%s", username);
1194 const char *dbname = MyProcPort->database_name;
1196 if (dbname == NULL || *dbname == '\0')
1197 dbname = gettext("[unknown]");
1198 appendStringInfo(buf, "%s", dbname);
1204 appendStringInfo(buf, "%lx.%lx",
1205 (long)(MyProcPort->session_start.tv_sec),
1210 appendStringInfo(buf, "%ld", (long)MyProcPid);
1213 appendStringInfo(buf, "%ld", log_line_number);
1218 * Note: for %t and %s we deliberately use the C library's
1219 * strftime/localtime, and not the equivalent functions
1220 * from src/timezone. This ensures that all backends
1221 * will report log entries in the same timezone, namely
1222 * whatever C-library setting they inherit from the
1223 * postmaster. If we used src/timezone then local
1224 * settings of the TimeZone GUC variable would confuse
1227 time_t stamp_time = time(NULL);
1230 strftime(strfbuf, sizeof(strfbuf),
1231 "%Y-%m-%d %H:%M:%S %Z",
1232 localtime(&stamp_time));
1233 appendStringInfoString(buf, strfbuf);
1239 time_t stamp_time = MyProcPort->session_start.tv_sec;
1242 strftime(strfbuf, sizeof(strfbuf),
1243 "%Y-%m-%d %H:%M:%S %Z",
1244 localtime(&stamp_time));
1245 appendStringInfoString(buf, strfbuf);
1251 appendStringInfo(buf, "%s", MyProcPort->commandTag);
1257 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1258 if (strlen(MyProcPort->remote_port) > 0)
1259 appendStringInfo(buf, "(%s)",
1260 MyProcPort->remote_port);
1264 /* in postmaster and friends, stop if %x is seen */
1265 /* in a backend, just ignore */
1266 if (MyProcPort == NULL)
1270 appendStringInfoChar(buf, '%');
1273 /* format error - ignore it */
1281 * Write error report to server's log
1284 send_message_to_server_log(ErrorData *edata)
1288 initStringInfo(&buf);
1290 log_line_prefix(&buf);
1291 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1293 if (Log_error_verbosity >= PGERROR_VERBOSE)
1295 /* unpack MAKE_SQLSTATE code */
1300 ssval = edata->sqlerrcode;
1301 for (i = 0; i < 5; i++)
1303 tbuf[i] = PGUNSIXBIT(ssval);
1307 appendStringInfo(&buf, "%s: ", tbuf);
1311 append_with_tabs(&buf, edata->message);
1313 append_with_tabs(&buf, gettext("missing error text"));
1315 if (edata->cursorpos > 0)
1316 appendStringInfo(&buf, gettext(" at character %d"),
1318 else if (edata->internalpos > 0)
1319 appendStringInfo(&buf, gettext(" at character %d"),
1320 edata->internalpos);
1322 appendStringInfoChar(&buf, '\n');
1324 if (Log_error_verbosity >= PGERROR_DEFAULT)
1328 log_line_prefix(&buf);
1329 appendStringInfoString(&buf, gettext("DETAIL: "));
1330 append_with_tabs(&buf, edata->detail);
1331 appendStringInfoChar(&buf, '\n');
1335 log_line_prefix(&buf);
1336 appendStringInfoString(&buf, gettext("HINT: "));
1337 append_with_tabs(&buf, edata->hint);
1338 appendStringInfoChar(&buf, '\n');
1340 if (edata->internalquery)
1342 log_line_prefix(&buf);
1343 appendStringInfoString(&buf, gettext("QUERY: "));
1344 append_with_tabs(&buf, edata->internalquery);
1345 appendStringInfoChar(&buf, '\n');
1349 log_line_prefix(&buf);
1350 appendStringInfoString(&buf, gettext("CONTEXT: "));
1351 append_with_tabs(&buf, edata->context);
1352 appendStringInfoChar(&buf, '\n');
1354 if (Log_error_verbosity >= PGERROR_VERBOSE)
1356 /* assume no newlines in funcname or filename... */
1357 if (edata->funcname && edata->filename)
1359 log_line_prefix(&buf);
1360 appendStringInfo(&buf, gettext("LOCATION: %s, %s:%d\n"),
1361 edata->funcname, edata->filename,
1364 else if (edata->filename)
1366 log_line_prefix(&buf);
1367 appendStringInfo(&buf, gettext("LOCATION: %s:%d\n"),
1368 edata->filename, edata->lineno);
1374 * If the user wants the query that generated this error logged, do it.
1376 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1378 log_line_prefix(&buf);
1379 appendStringInfoString(&buf, gettext("STATEMENT: "));
1380 append_with_tabs(&buf, debug_query_string);
1381 appendStringInfoChar(&buf, '\n');
1386 /* Write to syslog, if enabled */
1387 if (Log_destination & LOG_DESTINATION_SYSLOG)
1391 switch (edata->elevel)
1398 syslog_level = LOG_DEBUG;
1403 syslog_level = LOG_INFO;
1407 syslog_level = LOG_NOTICE;
1410 syslog_level = LOG_WARNING;
1413 syslog_level = LOG_ERR;
1417 syslog_level = LOG_CRIT;
1421 write_syslog(syslog_level, buf.data);
1423 #endif /* HAVE_SYSLOG */
1425 if (Log_destination & LOG_DESTINATION_EVENTLOG)
1428 switch (edata->elevel)
1439 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1442 eventlog_level = EVENTLOG_WARNING_TYPE;
1448 eventlog_level = EVENTLOG_ERROR_TYPE;
1451 write_eventlog(eventlog_level, buf.data);
1454 /* Write to stderr, if enabled */
1455 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1457 fprintf(stderr, "%s", buf.data);
1465 * Write error report to client
1468 send_message_to_frontend(ErrorData *edata)
1470 StringInfoData msgbuf;
1472 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1473 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1475 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1477 /* New style with separate fields */
1482 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1483 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1485 /* unpack MAKE_SQLSTATE code */
1486 ssval = edata->sqlerrcode;
1487 for (i = 0; i < 5; i++)
1489 tbuf[i] = PGUNSIXBIT(ssval);
1494 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1495 pq_sendstring(&msgbuf, tbuf);
1497 /* M field is required per protocol, so always send something */
1498 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1500 pq_sendstring(&msgbuf, edata->message);
1502 pq_sendstring(&msgbuf, gettext("missing error text"));
1506 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1507 pq_sendstring(&msgbuf, edata->detail);
1512 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1513 pq_sendstring(&msgbuf, edata->hint);
1518 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1519 pq_sendstring(&msgbuf, edata->context);
1522 if (edata->cursorpos > 0)
1524 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1525 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1526 pq_sendstring(&msgbuf, tbuf);
1529 if (edata->internalpos > 0)
1531 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1532 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1533 pq_sendstring(&msgbuf, tbuf);
1536 if (edata->internalquery)
1538 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1539 pq_sendstring(&msgbuf, edata->internalquery);
1542 if (edata->filename)
1544 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1545 pq_sendstring(&msgbuf, edata->filename);
1548 if (edata->lineno > 0)
1550 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1551 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1552 pq_sendstring(&msgbuf, tbuf);
1555 if (edata->funcname)
1557 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1558 pq_sendstring(&msgbuf, edata->funcname);
1561 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1565 /* Old style --- gin up a backwards-compatible message */
1568 initStringInfo(&buf);
1570 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1572 if (edata->show_funcname && edata->funcname)
1573 appendStringInfo(&buf, "%s: ", edata->funcname);
1576 appendStringInfoString(&buf, edata->message);
1578 appendStringInfoString(&buf, gettext("missing error text"));
1580 if (edata->cursorpos > 0)
1581 appendStringInfo(&buf, gettext(" at character %d"),
1583 else if (edata->internalpos > 0)
1584 appendStringInfo(&buf, gettext(" at character %d"),
1585 edata->internalpos);
1587 appendStringInfoChar(&buf, '\n');
1589 pq_sendstring(&msgbuf, buf.data);
1594 pq_endmessage(&msgbuf);
1597 * This flush is normally not necessary, since postgres.c will flush
1598 * out waiting data when control returns to the main loop. But it
1599 * seems best to leave it here, so that the client has some clue what
1600 * happened if the backend dies before getting back to the main loop
1601 * ... error/notice messages should not be a performance-critical path
1602 * anyway, so an extra flush won't hurt much ...
1609 * Support routines for formatting error messages.
1614 * expand_fmt_string --- process special format codes in a format string
1616 * We must replace %m with the appropriate strerror string, since vsnprintf
1617 * won't know what to do with it.
1619 * The result is a palloc'd string.
1622 expand_fmt_string(const char *fmt, ErrorData *edata)
1627 initStringInfo(&buf);
1629 for (cp = fmt; *cp; cp++)
1631 if (cp[0] == '%' && cp[1] != '\0')
1637 * Replace %m by system error string. If there are any
1638 * %'s in the string, we'd better double them so that
1639 * vsnprintf won't misinterpret.
1643 cp2 = useful_strerror(edata->saved_errno);
1647 appendStringInfoCharMacro(&buf, '%');
1648 appendStringInfoCharMacro(&buf, *cp2);
1653 /* copy % and next char --- this avoids trouble with %%m */
1654 appendStringInfoCharMacro(&buf, '%');
1655 appendStringInfoCharMacro(&buf, *cp);
1659 appendStringInfoCharMacro(&buf, *cp);
1667 * A slightly cleaned-up version of strerror()
1670 useful_strerror(int errnum)
1672 /* this buffer is only used if errno has a bogus value */
1673 static char errorstr_buf[48];
1677 /* Winsock error code range, per WinError.h */
1678 if (errnum >= 10000 && errnum <= 11999)
1679 return pgwin32_socket_strerror(errnum);
1681 str = strerror(errnum);
1684 * Some strerror()s return an empty string for out-of-range errno.
1685 * This is ANSI C spec compliant, but not exactly useful.
1687 if (str == NULL || *str == '\0')
1690 * translator: This string will be truncated at 47 characters
1693 snprintf(errorstr_buf, sizeof(errorstr_buf),
1694 gettext("operating system error %d"), errnum);
1703 * error_severity --- get localized string representing elevel
1706 error_severity(int elevel)
1717 prefix = gettext("DEBUG");
1721 prefix = gettext("LOG");
1724 prefix = gettext("INFO");
1727 prefix = gettext("NOTICE");
1730 prefix = gettext("WARNING");
1733 prefix = gettext("ERROR");
1736 prefix = gettext("FATAL");
1739 prefix = gettext("PANIC");
1753 * Append the string to the StringInfo buffer, inserting a tab after any
1757 append_with_tabs(StringInfo buf, const char *str)
1761 while ((ch = *str++) != '\0')
1763 appendStringInfoCharMacro(buf, ch);
1765 appendStringInfoCharMacro(buf, '\t');