1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/utils/error/elog.c,v 1.102 2002/09/02 05:42:54 momjian Exp $
13 *-------------------------------------------------------------------------
28 #include "commands/copy.h"
29 #include "libpq/libpq.h"
30 #include "libpq/pqformat.h"
31 #include "miscadmin.h"
32 #include "storage/ipc.h"
33 #include "storage/proc.h"
34 #include "tcop/tcopprot.h"
35 #include "utils/memutils.h"
36 #include "utils/guc.h"
38 #include "mb/pg_wchar.h"
42 * 0 = only stdout/stderr
43 * 1 = stdout+stderr and syslog
45 * ... in theory anyway
48 char *Syslog_facility;
51 static void write_syslog(int level, const char *line);
60 #define TIMESTAMP_SIZE 20 /* format `YYYY-MM-DD HH:MM:SS ' */
61 #define PID_SIZE 9 /* format `[123456] ' */
63 static const char *print_timestamp(void);
64 static const char *print_pid(void);
65 static void send_message_to_frontend(int type, const char *msg);
66 static const char *useful_strerror(int errnum);
67 static const char *elog_message_prefix(int lev);
69 static int Debugfile = -1;
72 /*--------------------
74 * Primary error logging function.
76 * 'lev': error level; indicates recovery action to take, if any.
77 * 'fmt': a printf-style string.
78 * Additional arguments, if any, are formatted per %-escapes in 'fmt'.
80 * In addition to the usual %-escapes recognized by printf, "%m" in
81 * fmt is replaced by the error message for the current value of errno.
83 * Note: no newline is needed at the end of the fmt string, since
84 * elog will provide one for the output methods that need it.
86 * If 'lev' is ERROR or worse, control does not return to the caller.
87 * See elog.h for the error level definitions.
91 elog(int lev, const char *fmt,...)
95 * The expanded format and final output message are dynamically
96 * allocated if necessary, but not if they fit in the "reasonable
97 * size" buffers shown here. In extremis, we'd rather depend on
98 * having a few hundred bytes of stack space than on malloc() still
99 * working (since memory-clobber errors often take out malloc first).
100 * Don't make these buffers unreasonably large though, on pain of
101 * having to chase a bug with no error message.
103 * Note that we use malloc() not palloc() because we want to retain
104 * control if we run out of memory. palloc() would recursively call
105 * elog(ERROR), which would be all right except if we are working on a
106 * FATAL or PANIC error. We'd lose track of the fatal condition
107 * and report a mere ERROR to outer loop, which would be a Bad Thing.
108 * So, we substitute an appropriate message in-place, without
109 * downgrading the level if it's above ERROR.
111 char fmt_fixedbuf[128];
112 char msg_fixedbuf[256];
113 char *fmt_buf = fmt_fixedbuf;
114 char *msg_buf = msg_fixedbuf;
115 char copylineno_buf[32]; /* for COPY line numbers */
116 const char *errorstr;
121 size_t timestamp_size; /* prefix len for timestamp+pid */
122 bool output_to_server = false;
123 bool output_to_client = false;
125 /* Check for old elog calls. Codes were renumbered in 7.3. 2002-02-24 */
127 elog(FATAL, "Pre-7.3 object file made an elog() call. Recompile.");
130 * Convert initialization errors into fatal errors. This is probably
131 * redundant, because Warn_restart_ready won't be set anyway.
133 if (lev == ERROR && IsInitProcessingMode())
137 * If we are inside a critical section, all errors become PANIC
138 * errors. See miscadmin.h.
142 if (CritSectionCount > 0)
146 /* Determine whether message is enabled for server log output */
147 /* Complicated because LOG is sorted out-of-order for this purpose */
148 if (lev == LOG || lev == COMMERROR)
150 if (server_min_messages == LOG)
151 output_to_server = true;
152 else if (server_min_messages < FATAL)
153 output_to_server = true;
158 if (server_min_messages == LOG)
161 output_to_server = true;
164 else if (lev >= server_min_messages)
165 output_to_server = true;
168 /* Determine whether message is enabled for client output */
169 if (whereToSendOutput == Remote && lev != COMMERROR)
172 * client_min_messages is honored only after we complete the
173 * authentication handshake. This is required both for security
174 * reasons and because many clients can't handle NOTICE messages
175 * during authentication.
177 if (ClientAuthInProgress)
178 output_to_client = (lev >= ERROR);
180 output_to_client = (lev >= client_min_messages || lev == INFO);
183 /* Skip formatting effort if non-error message will not be output */
184 if (lev < ERROR && !output_to_server && !output_to_client)
187 /* Save error str before calling any function that might change errno */
188 errorstr = useful_strerror(errno);
190 /* Internationalize the error format string */
193 /* Begin formatting by determining prefix information */
194 prefix = elog_message_prefix(lev);
198 timestamp_size += TIMESTAMP_SIZE;
200 timestamp_size += PID_SIZE;
203 * Set up the expanded format, consisting of the prefix string plus
204 * input format, with any %m replaced by strerror() string (since
205 * vsnprintf won't know what to do with %m). To keep space
206 * calculation simple, we only allow one %m.
208 space_needed = timestamp_size + strlen(prefix) +
209 strlen(fmt) + strlen(errorstr) + 1;
214 * Prints the failure line of the COPY. Wow, what a hack! bjm
215 * Translator: Error message will be truncated at 31 characters.
217 snprintf(copylineno_buf, 32, gettext("copy: line %d, "), copy_lineno);
218 space_needed += strlen(copylineno_buf);
221 if (space_needed > sizeof(fmt_fixedbuf))
223 fmt_buf = malloc(space_needed);
226 /* We're up against it, convert to out-of-memory error */
227 fmt_buf = fmt_fixedbuf;
231 prefix = elog_message_prefix(lev);
235 * gettext doesn't allocate memory, except in the very first
236 * call (which this isn't), so it's safe to translate here.
237 * Worst case we get the untranslated string back.
239 /* translator: This must fit in fmt_fixedbuf. */
240 fmt = gettext("elog: out of memory");
247 strcat(fmt_buf, print_timestamp());
249 strcat(fmt_buf, print_pid());
251 strcat(fmt_buf, prefix);
253 /* If error was in CopyFrom() print the offending line number -- dz */
256 strcat(fmt_buf, copylineno_buf);
261 bp = fmt_buf + strlen(fmt_buf);
263 for (cp = fmt; *cp; cp++)
265 if (cp[0] == '%' && cp[1] != '\0')
270 * XXX If there are any %'s in errorstr then vsnprintf
271 * will do the Wrong Thing; do we need to cope? Seems
272 * unlikely that % would appear in system errors.
274 strcpy(bp, errorstr);
277 * copy the rest of fmt literally, since we can't afford
278 * to insert another %m.
286 /* copy % and next char --- this avoids trouble with %%m */
297 * Now generate the actual output text using vsnprintf(). Be sure to
298 * leave space for \n added later as well as trailing null.
300 space_needed = sizeof(msg_fixedbuf);
306 nprinted = vsnprintf(msg_buf, space_needed - 2, fmt_buf, ap);
310 * Note: some versions of vsnprintf return the number of chars
311 * actually stored, but at least one returns -1 on failure. Be
312 * conservative about believing whether the print worked.
314 if (nprinted >= 0 && nprinted < space_needed - 3)
316 /* It didn't work, try to get a bigger buffer */
317 if (msg_buf != msg_fixedbuf)
320 msg_buf = malloc(space_needed);
323 /* We're up against it, convert to out-of-memory error */
324 msg_buf = msg_fixedbuf;
328 prefix = elog_message_prefix(lev);
332 strcat(msg_buf, print_timestamp());
334 strcat(msg_buf, print_pid());
335 strcat(msg_buf, prefix);
336 strcat(msg_buf, gettext("elog: out of memory"));
343 * Message prepared; send it where it should go
347 /* Write to syslog, if enabled */
348 if (output_to_server && Use_syslog >= 1)
359 syslog_level = LOG_DEBUG;
364 syslog_level = LOG_INFO;
368 syslog_level = LOG_NOTICE;
371 syslog_level = LOG_WARNING;
374 syslog_level = LOG_ERR;
378 syslog_level = LOG_CRIT;
382 write_syslog(syslog_level, msg_buf + timestamp_size);
384 #endif /* HAVE_SYSLOG */
386 /* syslog doesn't want a trailing newline, but other destinations do */
387 strcat(msg_buf, "\n");
389 /* Write to stderr, if enabled */
390 if (output_to_server && (Use_syslog <= 1 || whereToSendOutput == Debug))
391 write(2, msg_buf, strlen(msg_buf));
393 /* Send to client, if enabled */
394 if (output_to_client)
396 /* Send IPC message to the front-end program */
397 MemoryContext oldcxt;
400 * Since backend libpq may call palloc(), switch to a context
401 * where there's fairly likely to be some free space. After all
402 * the pushups above, we don't want to drop the ball by running
403 * out of space now...
405 oldcxt = MemoryContextSwitchTo(ErrorContext);
408 /* exclude the timestamp from msg sent to frontend */
409 send_message_to_frontend(lev, msg_buf + timestamp_size);
413 * Abort any COPY OUT in progress when an error is detected.
414 * This hack is necessary because of poor design of copy
418 send_message_to_frontend(ERROR, msg_buf + timestamp_size);
421 MemoryContextSwitchTo(oldcxt);
424 /* done with the message, release space */
425 if (fmt_buf != fmt_fixedbuf)
427 if (msg_buf != msg_fixedbuf)
430 /* If the user wants this elog() generating query logged,
431 * do so. We only want to log if the query has been
432 * written to debug_query_string. Also, avoid infinite loops.
435 if(lev != LOG && lev >= log_min_error_statement && debug_query_string)
436 elog(LOG,"statement: %s",debug_query_string);
439 * Perform error recovery action as specified by lev.
441 if (lev == ERROR || lev == FATAL)
443 /* Prevent immediate interrupt while entering error recovery */
444 ImmediateInterruptOK = false;
447 * If we just reported a startup failure, the client will
448 * disconnect on receiving it, so don't send any more to the client.
450 if (!Warn_restart_ready && whereToSendOutput == Remote)
451 whereToSendOutput = None;
454 * For a FATAL error, we let proc_exit clean up and exit.
456 * If we have not yet entered the main backend loop (ie, we are in
457 * the postmaster or in backend startup), we also go directly to
458 * proc_exit. The same is true if anyone tries to report an error
459 * after proc_exit has begun to run. (It's proc_exit's
460 * responsibility to see that this doesn't turn into infinite
461 * recursion!) But in the latter case, we exit with nonzero exit
462 * code to indicate that something's pretty wrong. We also want
463 * to exit with nonzero exit code if not running under the
464 * postmaster (for example, if we are being run from the initdb
465 * script, we'd better return an error status).
467 if (lev == FATAL || !Warn_restart_ready || proc_exit_inprogress)
470 * fflush here is just to improve the odds that we get to see
471 * the error message, in case things are so hosed that
472 * proc_exit crashes. Any other code you might be tempted to
473 * add here should probably be in an on_proc_exit callback
478 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
482 * Guard against infinite loop from elog() during error recovery.
485 elog(PANIC, "elog: error during error recovery, giving up!");
489 * Otherwise we can return to the main loop in postgres.c.
491 siglongjmp(Warn_restart, 1);
497 * Serious crash time. Postmaster will observe nonzero process
498 * exit status and kill the other backends too.
500 * XXX: what if we are *in* the postmaster? proc_exit() won't kill
503 ImmediateInterruptOK = false;
509 /* We reach here if lev <= WARNING. OK to return to caller. */
521 if (OutputFileName[0])
524 * A debug-output file name was given.
526 * Make sure we can write the file, and find out if it's a tty.
528 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
530 elog(FATAL, "DebugFileOpen: open of %s: %m",
536 * Redirect our stderr to the debug output file.
538 if (!freopen(OutputFileName, "a", stderr))
539 elog(FATAL, "DebugFileOpen: %s reopen as stderr: %m",
541 Debugfile = fileno(stderr);
544 * If the file is a tty and we're running under the postmaster,
545 * try to send stdout there as well (if it isn't a tty then stderr
546 * will block out stdout, so we may as well let stdout go wherever
547 * it was going before).
549 if (istty && IsUnderPostmaster)
550 if (!freopen(OutputFileName, "a", stdout))
551 elog(FATAL, "DebugFileOpen: %s reopen as stdout: %m",
557 * If no filename was specified, send debugging output to stderr. If
558 * stderr has been hosed, try to open a file.
561 if (fcntl(fd, F_GETFD, 0) < 0)
563 snprintf(OutputFileName, MAXPGPATH, "%s/pg.errors.%d",
564 DataDir, (int) MyProcPid);
565 fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY, 0666);
568 elog(FATAL, "DebugFileOpen: could not open debugging file");
576 * Return a timestamp string like
578 * "2000-06-04 13:12:03 "
581 print_timestamp(void)
584 static char buf[TIMESTAMP_SIZE + 1];
586 curtime = time(NULL);
588 strftime(buf, sizeof(buf),
589 "%Y-%m-%d %H:%M:%S ",
590 localtime(&curtime));
598 * Return a string like
602 * with the current pid.
607 static char buf[PID_SIZE + 1];
609 snprintf(buf, PID_SIZE + 1, "[%d] ", (int) MyProcPid);
617 #ifndef PG_SYSLOG_LIMIT
618 #define PG_SYSLOG_LIMIT 128
622 * Write a message line to syslog if the syslog option is set.
624 * Our problem here is that many syslog implementations don't handle
625 * long messages in an acceptable manner. While this function doesn't
626 * help that fact, it does work around by splitting up messages into
630 write_syslog(int level, const char *line)
632 static bool openlog_done = false;
633 static unsigned long seq = 0;
634 static int syslog_fac = LOG_LOCAL0;
636 int len = strlen(line);
643 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
644 syslog_fac = LOG_LOCAL0;
645 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
646 syslog_fac = LOG_LOCAL1;
647 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
648 syslog_fac = LOG_LOCAL2;
649 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
650 syslog_fac = LOG_LOCAL3;
651 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
652 syslog_fac = LOG_LOCAL4;
653 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
654 syslog_fac = LOG_LOCAL5;
655 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
656 syslog_fac = LOG_LOCAL6;
657 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
658 syslog_fac = LOG_LOCAL7;
659 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
664 * We add a sequence number to each log message to suppress "same"
669 /* divide into multiple syslog() calls if message is too long */
670 /* or if the message contains embedded NewLine(s) '\n' */
671 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
677 char buf[PG_SYSLOG_LIMIT + 1];
682 /* if we start at a newline, move ahead one char */
690 strncpy(buf, line, PG_SYSLOG_LIMIT);
691 buf[PG_SYSLOG_LIMIT] = '\0';
692 if (strchr(buf, '\n') != NULL)
693 *strchr(buf, '\n') = '\0';
697 /* trim to multibyte letter boundary */
698 buflen = pg_mbcliplen(buf, l, l);
704 /* already word boundary? */
705 if (isspace((unsigned char) line[l]) || line[l] == '\0')
709 /* try to divide at word boundary */
711 while (i > 0 && !isspace((unsigned char) buf[i]))
714 if (i <= 0) /* couldn't divide word boundary */
725 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
732 /* message short enough */
733 syslog(level, "[%lu] %s", seq, line);
736 #endif /* HAVE_SYSLOG */
740 send_message_to_frontend(int type, const char *msg)
744 AssertArg(type <= ERROR);
746 pq_beginmessage(&buf);
747 pq_sendbyte(&buf, type != ERROR ? 'N' : 'E'); /* N is INFO, NOTICE,
749 pq_sendstring(&buf, msg);
753 * This flush is normally not necessary, since postgres.c will flush
754 * out waiting data when control returns to the main loop. But it
755 * seems best to leave it here, so that the client has some clue what
756 * happened if the backend dies before getting back to the main loop
757 * ... error/notice messages should not be a performance-critical path
758 * anyway, so an extra flush won't hurt much ...
765 useful_strerror(int errnum)
767 /* this buffer is only used if errno has a bogus value */
768 static char errorstr_buf[48];
771 if (errnum == ERANGE)
772 /* small trick to save creating many regression test result files */
773 str = gettext("Numerical result out of range");
775 str = strerror(errnum);
778 * Some strerror()s return an empty string for out-of-range errno.
779 * This is ANSI C spec compliant, but not exactly useful.
781 if (str == NULL || *str == '\0')
784 * translator: This string will be truncated at 47 characters
787 snprintf(errorstr_buf, 48, gettext("operating system error %d"),
798 elog_message_prefix(int lev)
800 const char *prefix = NULL;
809 prefix = gettext("DEBUG: ");
813 prefix = gettext("LOG: ");
816 prefix = gettext("INFO: ");
819 prefix = gettext("NOTICE: ");
822 prefix = gettext("WARNING: ");
825 prefix = gettext("ERROR: ");
828 prefix = gettext("FATAL: ");
831 prefix = gettext("PANIC: ");
835 Assert(prefix != NULL);