1 /*-------------------------------------------------------------------------
6 * Portions Copyright (c) 1996-2001, 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.86 2001/06/08 21:16:48 petere Exp $
13 *-------------------------------------------------------------------------
19 #include <sys/types.h>
29 #include "commands/copy.h"
30 #include "libpq/libpq.h"
31 #include "libpq/pqformat.h"
32 #include "miscadmin.h"
33 #include "storage/proc.h"
34 #include "tcop/tcopprot.h"
35 #include "utils/memutils.h"
38 #include "mb/pg_wchar.h"
43 * 0 = only stdout/stderr
44 * 1 = stdout+stderr and syslog
46 * ... in theory anyway
49 char *Syslog_facility;
52 static void write_syslog(int level, const char *line);
61 #define TIMESTAMP_SIZE 20 /* format `YYYY-MM-DD HH:MM:SS ' */
62 #define PID_SIZE 9 /* format `[123456] ' */
64 static const char *print_timestamp(void);
65 static const char *print_pid(void);
66 static void send_notice_to_frontend(const char *msg);
67 static void send_error_to_frontend(const char *msg);
68 static const char *useful_strerror(int errnum);
69 static const char *elog_message_prefix(int lev);
72 static int Debugfile = -1;
75 /*--------------------
77 * Primary error logging function.
79 * 'lev': error level; indicates recovery action to take, if any.
80 * 'fmt': a printf-style string.
81 * Additional arguments, if any, are formatted per %-escapes in 'fmt'.
83 * In addition to the usual %-escapes recognized by printf, "%m" in
84 * fmt is replaced by the error message for the current value of errno.
86 * Note: no newline is needed at the end of the fmt string, since
87 * elog will provide one for the output methods that need it.
89 * If 'lev' is ERROR or worse, control does not return to the caller.
90 * See elog.h for the error level definitions.
94 elog(int lev, const char *fmt,...)
99 * The expanded format and final output message are dynamically
100 * allocated if necessary, but not if they fit in the "reasonable
101 * size" buffers shown here. In extremis, we'd rather depend on
102 * having a few hundred bytes of stack space than on malloc() still
103 * working (since memory-clobber errors often take out malloc first).
104 * Don't make these buffers unreasonably large though, on pain of
105 * having to chase a bug with no error message.
107 * Note that we use malloc() not palloc() because we want to retain
108 * control if we run out of memory. palloc() would recursively call
109 * elog(ERROR), which would be all right except if we are working on a
110 * FATAL or REALLYFATAL error. We'd lose track of the fatal condition
111 * and report a mere ERROR to outer loop, which would be a Bad Thing.
112 * So, we substitute an appropriate message in-place, without
113 * downgrading the level if it's above ERROR.
115 char fmt_fixedbuf[128];
116 char msg_fixedbuf[256];
117 char *fmt_buf = fmt_fixedbuf;
118 char *msg_buf = msg_fixedbuf;
120 /* for COPY line numbers */
121 char copylineno_buf[32];
123 const char *errorstr;
129 /* size of the prefix needed for timestamp and pid, if enabled */
130 size_t timestamp_size;
132 /* ignore debug msgs if noplace to send */
133 if (lev == DEBUG && Debugfile < 0)
136 /* Save error str before calling any function that might change errno */
137 errorstr = useful_strerror(errno);
140 * Convert initialization errors into fatal errors. This is
141 * probably redundant, because Warn_restart_ready won't be set
144 if (lev == ERROR && IsInitProcessingMode())
148 * If we are inside a critical section, all errors become
149 * REALLYFATAL errors. See miscadmin.h.
151 if (lev == ERROR || lev == FATAL)
153 if (CritSectionCount > 0)
157 prefix = elog_message_prefix(lev);
161 timestamp_size += TIMESTAMP_SIZE;
163 timestamp_size += PID_SIZE;
167 * Set up the expanded format, consisting of the prefix string plus
168 * input format, with any %m replaced by strerror() string (since
169 * vsnprintf won't know what to do with %m). To keep space
170 * calculation simple, we only allow one %m.
172 space_needed = timestamp_size + strlen(prefix)
173 + strlen(fmt) + strlen(errorstr) + 1;
177 /* translator: This string will be truncated at 31 characters. */
178 snprintf(copylineno_buf, 32, gettext("copy: line %d, "), copy_lineno);
179 space_needed += strlen(copylineno_buf);
182 if (space_needed > sizeof(fmt_fixedbuf))
184 fmt_buf = malloc(space_needed);
187 /* We're up against it, convert to out-of-memory error */
188 fmt_buf = fmt_fixedbuf;
189 if (lev != FATAL && lev != REALLYFATAL)
192 prefix = elog_message_prefix(lev);
195 * gettext doesn't allocate memory, except in the very
196 * first call (which this isn't), so it's safe to
197 * translate here. Worst case we get the untranslated
200 /* translator: This must fit in fmt_fixedbuf. */
201 fmt = gettext("elog: out of memory");
208 strcat(fmt_buf, print_timestamp());
210 strcat(fmt_buf, print_pid());
212 strcat(fmt_buf, prefix);
214 /* If error was in CopyFrom() print the offending line number -- dz */
217 strcat(fmt_buf, copylineno_buf);
218 if (lev == ERROR || lev == FATAL || lev == REALLYFATAL)
222 bp = fmt_buf + strlen(fmt_buf);
224 for (cp = fmt; *cp; cp++)
226 if (cp[0] == '%' && cp[1] != '\0')
231 * XXX If there are any %'s in errorstr then vsnprintf
232 * will do the Wrong Thing; do we need to cope? Seems
233 * unlikely that % would appear in system errors.
235 strcpy(bp, errorstr);
238 * copy the rest of fmt literally, since we can't afford
239 * to insert another %m.
247 /* copy % and next char --- this avoids trouble with %%m */
258 * Now generate the actual output text using vsnprintf(). Be sure to
259 * leave space for \n added later as well as trailing null.
261 space_needed = sizeof(msg_fixedbuf);
267 nprinted = vsnprintf(msg_buf, space_needed - 2, fmt_buf, ap);
271 * Note: some versions of vsnprintf return the number of chars
272 * actually stored, but at least one returns -1 on failure. Be
273 * conservative about believing whether the print worked.
275 if (nprinted >= 0 && nprinted < space_needed - 3)
277 /* It didn't work, try to get a bigger buffer */
278 if (msg_buf != msg_fixedbuf)
281 msg_buf = malloc(space_needed);
284 /* We're up against it, convert to out-of-memory error */
285 msg_buf = msg_fixedbuf;
286 if (lev != FATAL && lev != REALLYFATAL)
289 prefix = elog_message_prefix(lev);
293 strcat(msg_buf, print_timestamp());
295 strcat(msg_buf, print_pid());
296 strcat(msg_buf, prefix);
297 strcat(msg_buf, gettext("elog: out of memory"));
303 * Message prepared; send it where it should go
307 /* Write to syslog, if enabled */
315 syslog_level = LOG_DEBUG;
318 syslog_level = LOG_NOTICE;
321 syslog_level = LOG_WARNING;
324 syslog_level = LOG_ERR;
328 syslog_level = LOG_CRIT;
332 write_syslog(syslog_level, msg_buf + timestamp_size);
334 #endif /* ENABLE_SYSLOG */
336 /* syslog doesn't want a trailing newline, but other destinations do */
337 strcat(msg_buf, "\n");
339 /* Write to debug file, if open and enabled */
340 /* NOTE: debug file is typically pointed at stderr */
341 if (Debugfile >= 0 && Use_syslog <= 1)
342 write(Debugfile, msg_buf, strlen(msg_buf));
344 if (lev > DEBUG && whereToSendOutput == Remote)
346 /* Send IPC message to the front-end program */
347 MemoryContext oldcxt;
350 * Since backend libpq may call palloc(), switch to a context
351 * where there's fairly likely to be some free space. After all
352 * the pushups above, we don't want to drop the ball by running
353 * out of space now...
355 oldcxt = MemoryContextSwitchTo(ErrorContext);
358 /* exclude the timestamp from msg sent to frontend */
359 send_notice_to_frontend(msg_buf + timestamp_size);
363 * Abort any COPY OUT in progress when an error is detected.
364 * This hack is necessary because of poor design of copy
368 send_error_to_frontend(msg_buf + timestamp_size);
371 MemoryContextSwitchTo(oldcxt);
374 if (lev > DEBUG && whereToSendOutput != Remote)
377 * We are running as an interactive backend, so just send the
378 * message to stderr. But don't send a duplicate if Debugfile
379 * write, above, already sent to stderr.
381 if (Debugfile != fileno(stderr))
382 fputs(msg_buf, stderr);
385 /* done with the message, release space */
386 if (fmt_buf != fmt_fixedbuf)
388 if (msg_buf != msg_fixedbuf)
392 * Perform error recovery action as specified by lev.
394 if (lev == ERROR || lev == FATAL)
396 /* Prevent immediate interrupt while entering error recovery */
397 ImmediateInterruptOK = false;
400 * For a FATAL error, we let proc_exit clean up and exit.
402 * If we have not yet entered the main backend loop (ie, we are in
403 * the postmaster or in backend startup), we also go directly to
404 * proc_exit. The same is true if anyone tries to report an error
405 * after proc_exit has begun to run. (It's proc_exit's
406 * responsibility to see that this doesn't turn into infinite
407 * recursion!) But in the latter case, we exit with nonzero exit
408 * code to indicate that something's pretty wrong. We also want
409 * to exit with nonzero exit code if not running under the
410 * postmaster (for example, if we are being run from the initdb
411 * script, we'd better return an error status).
413 if (lev == FATAL || !Warn_restart_ready || proc_exit_inprogress)
416 * fflush here is just to improve the odds that we get to see
417 * the error message, in case things are so hosed that
418 * proc_exit crashes. Any other code you might be tempted to
419 * add here should probably be in an on_proc_exit callback
424 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
428 * Guard against infinite loop from elog() during error recovery.
431 elog(REALLYFATAL, "elog: error during error recovery, giving up!");
435 * Otherwise we can return to the main loop in postgres.c.
437 siglongjmp(Warn_restart, 1);
440 if (lev == FATAL || lev == REALLYFATAL)
443 * Serious crash time. Postmaster will observe nonzero process
444 * exit status and kill the other backends too.
446 * XXX: what if we are *in* the postmaster? proc_exit() won't kill
449 ImmediateInterruptOK = false;
455 /* We reach here if lev <= NOTICE. OK to return to caller. */
467 if (OutputFileName[0])
470 * A debug-output file name was given.
472 * Make sure we can write the file, and find out if it's a tty.
474 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
476 elog(FATAL, "DebugFileOpen: open of %s: %m",
482 * Redirect our stderr to the debug output file.
484 if (!freopen(OutputFileName, "a", stderr))
485 elog(FATAL, "DebugFileOpen: %s reopen as stderr: %m",
487 Debugfile = fileno(stderr);
490 * If the file is a tty and we're running under the postmaster,
491 * try to send stdout there as well (if it isn't a tty then stderr
492 * will block out stdout, so we may as well let stdout go wherever
493 * it was going before).
495 if (istty && IsUnderPostmaster)
496 if (!freopen(OutputFileName, "a", stdout))
497 elog(FATAL, "DebugFileOpen: %s reopen as stdout: %m",
503 * If no filename was specified, send debugging output to stderr. If
504 * stderr has been hosed, try to open a file.
507 if (fcntl(fd, F_GETFD, 0) < 0)
509 snprintf(OutputFileName, MAXPGPATH, "%s/pg.errors.%d",
510 DataDir, (int) MyProcPid);
511 fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY, 0666);
514 elog(FATAL, "DebugFileOpen: could not open debugging file");
522 * Return a timestamp string like
524 * "2000-06-04 13:12:03 "
527 print_timestamp(void)
530 static char buf[TIMESTAMP_SIZE + 1];
532 curtime = time(NULL);
534 strftime(buf, sizeof(buf),
535 "%Y-%m-%d %H:%M:%S ",
536 localtime(&curtime));
544 * Return a string like
548 * with the current pid.
553 static char buf[PID_SIZE + 1];
555 snprintf(buf, PID_SIZE + 1, "[%d] ", (int) MyProcPid);
563 #ifndef PG_SYSLOG_LIMIT
564 #define PG_SYSLOG_LIMIT 128
568 * Write a message line to syslog if the syslog option is set.
570 * Our problem here is that many syslog implementations don't handle
571 * long messages in an acceptable manner. While this function doesn't
572 * help that fact, it does work around by splitting up messages into
576 write_syslog(int level, const char *line)
578 static bool openlog_done = false;
579 static unsigned long seq = 0;
580 static int syslog_fac = LOG_LOCAL0;
582 int len = strlen(line);
589 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
590 syslog_fac = LOG_LOCAL0;
591 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
592 syslog_fac = LOG_LOCAL1;
593 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
594 syslog_fac = LOG_LOCAL2;
595 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
596 syslog_fac = LOG_LOCAL3;
597 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
598 syslog_fac = LOG_LOCAL4;
599 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
600 syslog_fac = LOG_LOCAL5;
601 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
602 syslog_fac = LOG_LOCAL6;
603 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
604 syslog_fac = LOG_LOCAL7;
605 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
610 * We add a sequence number to each log message to suppress "same"
615 /* divide into multiple syslog() calls if message is too long */
616 /* or if the message contains embedded NewLine(s) '\n' */
617 if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
623 char buf[PG_SYSLOG_LIMIT + 1];
628 /* if we start at a newline, move ahead one char */
636 strncpy(buf, line, PG_SYSLOG_LIMIT);
637 buf[PG_SYSLOG_LIMIT] = '\0';
638 if (strchr(buf, '\n') != NULL)
639 *strchr(buf, '\n') = '\0';
643 /* trim to multibyte letter boundary */
644 buflen = pg_mbcliplen(buf, l, l);
650 /* already word boundary? */
651 if (isspace((unsigned char) line[l]) || line[l] == '\0')
655 /* try to divide at word boundary */
657 while (i > 0 && !isspace((unsigned char) buf[i]))
660 if (i <= 0) /* couldn't divide word boundary */
671 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
678 /* message short enough */
679 syslog(level, "[%lu] %s", seq, line);
683 #endif /* ENABLE_SYSLOG */
688 send_notice_or_error_to_frontend(int type, const char *msg);
692 send_notice_to_frontend(const char *msg)
694 send_notice_or_error_to_frontend(NOTICE, msg);
699 send_error_to_frontend(const char *msg)
701 send_notice_or_error_to_frontend(ERROR, msg);
706 send_notice_or_error_to_frontend(int type, const char *msg)
710 AssertArg(type == NOTICE || type == ERROR);
712 buf = makeStringInfo();
714 pq_beginmessage(buf);
715 pq_sendbyte(buf, type == NOTICE ? 'N' : 'E');
716 pq_sendstring(buf, msg);
721 * This flush is normally not necessary, since postgres.c will
722 * flush out waiting data when control returns to the main loop.
723 * But it seems best to leave it here, so that the client has some
724 * clue what happened if the backend dies before getting back to
725 * the main loop ... error/notice messages should not be a
726 * performance-critical path anyway, so an extra flush won't hurt
733 static const char *useful_strerror(int errnum)
735 /* this buffer is only used if errno has a bogus value */
736 static char errorstr_buf[48];
739 str = strerror(errnum);
742 * Some strerror()s return an empty string for out-of-range errno.
743 * This is ANSI C spec compliant, but not exactly useful.
745 if (str == NULL || *str == '\0')
747 /* translator: This string will be truncated at 47 characters expanded. */
748 snprintf(errorstr_buf, 48, gettext("operating system error %d"), errnum);
758 elog_message_prefix(int lev)
760 const char * prefix = NULL;
765 prefix = gettext("DEBUG: ");
768 prefix = gettext("NOTICE: ");
771 prefix = gettext("ERROR: ");
774 prefix = gettext("FATAL 1: ");
777 prefix = gettext("FATAL 2: ");
781 Assert(prefix != NULL);