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.135 2004/04/22 03:51:09 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 = NULL; /* format for extra log line info */
73 unsigned int Log_destination;
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 (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 * 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);
1217 time_t stamp_time = time(NULL);
1220 strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z",
1221 localtime(&stamp_time));
1222 appendStringInfoString(buf, strfbuf);
1228 time_t stamp_time = MyProcPort->session_start.tv_sec;
1231 strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z",
1232 localtime(&stamp_time));
1233 appendStringInfoString(buf, strfbuf);
1239 appendStringInfo(buf, "%s", MyProcPort->commandTag);
1245 appendStringInfo(buf, "%s", MyProcPort->remote_host);
1246 if (strlen(MyProcPort->remote_port) > 0)
1247 appendStringInfo(buf, "(%s)",
1248 MyProcPort->remote_port);
1252 /* in postmaster and friends, stop if %x is seen */
1253 /* in a backend, just ignore */
1254 if (MyProcPort == NULL)
1258 appendStringInfoChar(buf, '%');
1261 /* format error - ignore it */
1269 * Write error report to server's log
1272 send_message_to_server_log(ErrorData *edata)
1276 initStringInfo(&buf);
1278 log_line_prefix(&buf);
1279 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1281 if (Log_error_verbosity >= PGERROR_VERBOSE)
1283 /* unpack MAKE_SQLSTATE code */
1288 ssval = edata->sqlerrcode;
1289 for (i = 0; i < 5; i++)
1291 tbuf[i] = PGUNSIXBIT(ssval);
1295 appendStringInfo(&buf, "%s: ", tbuf);
1299 append_with_tabs(&buf, edata->message);
1301 append_with_tabs(&buf, gettext("missing error text"));
1303 if (edata->cursorpos > 0)
1304 appendStringInfo(&buf, gettext(" at character %d"),
1306 else if (edata->internalpos > 0)
1307 appendStringInfo(&buf, gettext(" at character %d"),
1308 edata->internalpos);
1310 appendStringInfoChar(&buf, '\n');
1312 if (Log_error_verbosity >= PGERROR_DEFAULT)
1316 log_line_prefix(&buf);
1317 appendStringInfoString(&buf, gettext("DETAIL: "));
1318 append_with_tabs(&buf, edata->detail);
1319 appendStringInfoChar(&buf, '\n');
1323 log_line_prefix(&buf);
1324 appendStringInfoString(&buf, gettext("HINT: "));
1325 append_with_tabs(&buf, edata->hint);
1326 appendStringInfoChar(&buf, '\n');
1328 if (edata->internalquery)
1330 log_line_prefix(&buf);
1331 appendStringInfoString(&buf, gettext("QUERY: "));
1332 append_with_tabs(&buf, edata->internalquery);
1333 appendStringInfoChar(&buf, '\n');
1337 log_line_prefix(&buf);
1338 appendStringInfoString(&buf, gettext("CONTEXT: "));
1339 append_with_tabs(&buf, edata->context);
1340 appendStringInfoChar(&buf, '\n');
1342 if (Log_error_verbosity >= PGERROR_VERBOSE)
1344 /* assume no newlines in funcname or filename... */
1345 if (edata->funcname && edata->filename)
1347 log_line_prefix(&buf);
1348 appendStringInfo(&buf, gettext("LOCATION: %s, %s:%d\n"),
1349 edata->funcname, edata->filename,
1352 else if (edata->filename)
1354 log_line_prefix(&buf);
1355 appendStringInfo(&buf, gettext("LOCATION: %s:%d\n"),
1356 edata->filename, edata->lineno);
1362 * If the user wants the query that generated this error logged, do it.
1364 if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1366 log_line_prefix(&buf);
1367 appendStringInfoString(&buf, gettext("STATEMENT: "));
1368 append_with_tabs(&buf, debug_query_string);
1369 appendStringInfoChar(&buf, '\n');
1374 /* Write to syslog, if enabled */
1375 if (Log_destination & LOG_DESTINATION_SYSLOG)
1379 switch (edata->elevel)
1386 syslog_level = LOG_DEBUG;
1391 syslog_level = LOG_INFO;
1395 syslog_level = LOG_NOTICE;
1398 syslog_level = LOG_WARNING;
1401 syslog_level = LOG_ERR;
1405 syslog_level = LOG_CRIT;
1409 write_syslog(syslog_level, buf.data);
1411 #endif /* HAVE_SYSLOG */
1413 if (Log_destination & LOG_DESTINATION_EVENTLOG)
1416 switch (edata->elevel)
1427 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1430 eventlog_level = EVENTLOG_WARNING_TYPE;
1436 eventlog_level = EVENTLOG_ERROR_TYPE;
1439 write_eventlog(eventlog_level, buf.data);
1442 /* Write to stderr, if enabled */
1443 if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1445 fprintf(stderr, "%s", buf.data);
1453 * Write error report to client
1456 send_message_to_frontend(ErrorData *edata)
1458 StringInfoData msgbuf;
1460 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1461 pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1463 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1465 /* New style with separate fields */
1470 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1471 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1473 /* unpack MAKE_SQLSTATE code */
1474 ssval = edata->sqlerrcode;
1475 for (i = 0; i < 5; i++)
1477 tbuf[i] = PGUNSIXBIT(ssval);
1482 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1483 pq_sendstring(&msgbuf, tbuf);
1485 /* M field is required per protocol, so always send something */
1486 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1488 pq_sendstring(&msgbuf, edata->message);
1490 pq_sendstring(&msgbuf, gettext("missing error text"));
1494 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1495 pq_sendstring(&msgbuf, edata->detail);
1500 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1501 pq_sendstring(&msgbuf, edata->hint);
1506 pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1507 pq_sendstring(&msgbuf, edata->context);
1510 if (edata->cursorpos > 0)
1512 snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1513 pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1514 pq_sendstring(&msgbuf, tbuf);
1517 if (edata->internalpos > 0)
1519 snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1520 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1521 pq_sendstring(&msgbuf, tbuf);
1524 if (edata->internalquery)
1526 pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1527 pq_sendstring(&msgbuf, edata->internalquery);
1530 if (edata->filename)
1532 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1533 pq_sendstring(&msgbuf, edata->filename);
1536 if (edata->lineno > 0)
1538 snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1539 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1540 pq_sendstring(&msgbuf, tbuf);
1543 if (edata->funcname)
1545 pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1546 pq_sendstring(&msgbuf, edata->funcname);
1549 pq_sendbyte(&msgbuf, '\0'); /* terminator */
1553 /* Old style --- gin up a backwards-compatible message */
1556 initStringInfo(&buf);
1558 appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
1560 if (edata->show_funcname && edata->funcname)
1561 appendStringInfo(&buf, "%s: ", edata->funcname);
1564 appendStringInfoString(&buf, edata->message);
1566 appendStringInfoString(&buf, gettext("missing error text"));
1568 if (edata->cursorpos > 0)
1569 appendStringInfo(&buf, gettext(" at character %d"),
1571 else if (edata->internalpos > 0)
1572 appendStringInfo(&buf, gettext(" at character %d"),
1573 edata->internalpos);
1575 appendStringInfoChar(&buf, '\n');
1577 pq_sendstring(&msgbuf, buf.data);
1582 pq_endmessage(&msgbuf);
1585 * This flush is normally not necessary, since postgres.c will flush
1586 * out waiting data when control returns to the main loop. But it
1587 * seems best to leave it here, so that the client has some clue what
1588 * happened if the backend dies before getting back to the main loop
1589 * ... error/notice messages should not be a performance-critical path
1590 * anyway, so an extra flush won't hurt much ...
1597 * Support routines for formatting error messages.
1602 * expand_fmt_string --- process special format codes in a format string
1604 * We must replace %m with the appropriate strerror string, since vsnprintf
1605 * won't know what to do with it.
1607 * The result is a palloc'd string.
1610 expand_fmt_string(const char *fmt, ErrorData *edata)
1615 initStringInfo(&buf);
1617 for (cp = fmt; *cp; cp++)
1619 if (cp[0] == '%' && cp[1] != '\0')
1625 * Replace %m by system error string. If there are any
1626 * %'s in the string, we'd better double them so that
1627 * vsnprintf won't misinterpret.
1631 cp2 = useful_strerror(edata->saved_errno);
1635 appendStringInfoCharMacro(&buf, '%');
1636 appendStringInfoCharMacro(&buf, *cp2);
1641 /* copy % and next char --- this avoids trouble with %%m */
1642 appendStringInfoCharMacro(&buf, '%');
1643 appendStringInfoCharMacro(&buf, *cp);
1647 appendStringInfoCharMacro(&buf, *cp);
1655 * A slightly cleaned-up version of strerror()
1658 useful_strerror(int errnum)
1660 /* this buffer is only used if errno has a bogus value */
1661 static char errorstr_buf[48];
1665 /* Winsock error code range, per WinError.h */
1666 if (errnum >= 10000 && errnum <= 11999)
1667 return pgwin32_socket_strerror(errnum);
1669 str = strerror(errnum);
1672 * Some strerror()s return an empty string for out-of-range errno.
1673 * This is ANSI C spec compliant, but not exactly useful.
1675 if (str == NULL || *str == '\0')
1678 * translator: This string will be truncated at 47 characters
1681 snprintf(errorstr_buf, sizeof(errorstr_buf),
1682 gettext("operating system error %d"), errnum);
1691 * error_severity --- get localized string representing elevel
1694 error_severity(int elevel)
1705 prefix = gettext("DEBUG");
1709 prefix = gettext("LOG");
1712 prefix = gettext("INFO");
1715 prefix = gettext("NOTICE");
1718 prefix = gettext("WARNING");
1721 prefix = gettext("ERROR");
1724 prefix = gettext("FATAL");
1727 prefix = gettext("PANIC");
1741 * Append the string to the StringInfo buffer, inserting a tab after any
1745 append_with_tabs(StringInfo buf, const char *str)
1749 while ((ch = *str++) != '\0')
1751 appendStringInfoCharMacro(buf, ch);
1753 appendStringInfoCharMacro(buf, '\t');