1
/*-------------------------------------------------------------------------
4
* error logging and reporting
6
* Because of the extremely high rate at which log messages can be generated,
7
* we need to be mindful of the performance cost of obtaining any information
8
* that may be logged. Also, it's important to keep in mind that this code may
9
* get called from within an aborted transaction, in which case operations
10
* such as syscache lookups are unsafe.
12
* Some notes about recursion and errors during error processing:
14
* We need to be robust about recursive-error scenarios --- for example,
15
* if we run out of memory, it's important to be able to report that fact.
16
* There are a number of considerations that go into this.
18
* First, distinguish between re-entrant use and actual recursion. It
19
* is possible for an error or warning message to be emitted while the
20
* parameters for an error message are being computed. In this case
21
* errstart has been called for the outer message, and some field values
22
* may have already been saved, but we are not actually recursing. We handle
23
* this by providing a (small) stack of ErrorData records. The inner message
24
* can be computed and sent without disturbing the state of the outer message.
25
* (If the inner message is actually an error, this isn't very interesting
26
* because control won't come back to the outer message generator ... but
27
* if the inner message is only debug or log data, this is critical.)
29
* Second, actual recursion will occur if an error is reported by one of
30
* the elog.c routines or something they call. By far the most probable
31
* scenario of this sort is "out of memory"; and it's also the nastiest
32
* to handle because we'd likely also run out of memory while trying to
33
* report this error! Our escape hatch for this case is to reset the
34
* ErrorContext to empty before trying to process the inner error. Since
35
* ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
36
* we should be able to process an "out of memory" message successfully.
37
* Since we lose the prior error state due to the reset, we won't be able
38
* to return to processing the original error, but we wouldn't have anyway.
39
* (NOTE: the escape hatch is not used for recursive situations where the
40
* inner message is of less than ERROR severity; in that case we just
41
* try to process it and return normally. Usually this will work, but if
42
* it ends up in infinite recursion, we will PANIC due to error stack
46
* Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
47
* Portions Copyright (c) 1994, Regents of the University of California
51
* src/backend/utils/error/elog.c
53
*-------------------------------------------------------------------------
66
#include "access/transam.h"
67
#include "access/xact.h"
68
#include "libpq/libpq.h"
69
#include "libpq/pqformat.h"
70
#include "mb/pg_wchar.h"
71
#include "miscadmin.h"
72
#include "postmaster/postmaster.h"
73
#include "postmaster/syslogger.h"
74
#include "storage/ipc.h"
75
#include "storage/proc.h"
76
#include "tcop/tcopprot.h"
77
#include "utils/guc.h"
78
#include "utils/memutils.h"
79
#include "utils/ps_status.h"
83
#define _(x) err_gettext(x)
86
err_gettext(const char *str)
87
/* This extension allows gcc to check the format string for consistency with
88
the supplied arguments. */
89
__attribute__((format_arg(1)));
91
/* Global variables */
92
ErrorContextCallback *error_context_stack = NULL;
94
sigjmp_buf *PG_exception_stack = NULL;
96
extern bool redirection_done;
99
int Log_error_verbosity = PGERROR_VERBOSE;
100
char *Log_line_prefix = NULL; /* format for extra log line info */
101
int Log_destination = LOG_DESTINATION_STDERR;
106
* Max string length to send to syslog(). Note that this doesn't count the
107
* sequence-number prefix we add, and of course it doesn't count the prefix
108
* added by syslog itself. On many implementations it seems that the hard
109
* limit is approximately 2K bytes including both those prefixes.
111
#ifndef PG_SYSLOG_LIMIT
112
#define PG_SYSLOG_LIMIT 1024
115
static bool openlog_done = false;
116
static char *syslog_ident = NULL;
117
static int syslog_facility = LOG_LOCAL0;
119
static void write_syslog(int level, const char *line);
122
static void write_console(const char *line, int len);
125
static void write_eventlog(int level, const char *line, int len);
128
/* We provide a small stack of ErrorData records for re-entrant cases */
129
#define ERRORDATA_STACK_SIZE 5
131
static ErrorData errordata[ERRORDATA_STACK_SIZE];
133
static int errordata_stack_depth = -1; /* index of topmost active frame */
135
static int recursion_depth = 0; /* to detect actual recursion */
137
/* buffers for formatted timestamps that might be used by both
138
* log_line_prefix and csv logs.
141
#define FORMATTED_TS_LEN 128
142
static char formatted_start_time[FORMATTED_TS_LEN];
143
static char formatted_log_time[FORMATTED_TS_LEN];
146
/* Macro for checking errordata_stack_depth is reasonable */
147
#define CHECK_STACK_DEPTH() \
149
if (errordata_stack_depth < 0) \
151
errordata_stack_depth = -1; \
152
ereport(ERROR, (errmsg_internal("errstart was not called"))); \
157
static void log_line_prefix(StringInfo buf, ErrorData *edata);
158
static void send_message_to_server_log(ErrorData *edata);
159
static void send_message_to_frontend(ErrorData *edata);
160
static char *expand_fmt_string(const char *fmt, ErrorData *edata);
161
static const char *useful_strerror(int errnum);
162
static const char *error_severity(int elevel);
163
static void append_with_tabs(StringInfo buf, const char *str);
164
static bool is_log_level_output(int elevel, int log_min_level);
165
static void write_pipe_chunks(char *data, int len, int dest);
166
static void write_csvlog(ErrorData *edata);
167
static void setup_formatted_log_time(void);
168
static void setup_formatted_start_time(void);
172
* in_error_recursion_trouble --- are we at risk of infinite error recursion?
174
* This function exists to provide common control of various fallback steps
175
* that we take if we think we are facing infinite error recursion. See the
176
* callers for details.
179
in_error_recursion_trouble(void)
181
/* Pull the plug if recurse more than once */
182
return (recursion_depth > 2);
186
* One of those fallback steps is to stop trying to localize the error
187
* message, since there's a significant probability that that's exactly
188
* what's causing the recursion.
190
static inline const char *
191
err_gettext(const char *str)
194
if (in_error_recursion_trouble())
205
* errstart --- begin an error-reporting cycle
207
* Create a stack entry and store the given parameters in it. Subsequently,
208
* errmsg() and perhaps other routines will be called to further populate
209
* the stack entry. Finally, errfinish() will be called to actually process
212
* Returns TRUE in normal case. Returns FALSE to short-circuit the error
213
* report (if it's a warning or lower and not to be reported anywhere).
216
errstart(int elevel, const char *filename, int lineno,
217
const char *funcname, const char *domain)
220
bool output_to_server;
221
bool output_to_client = false;
225
* Check some cases in which we want to promote an error into a more
226
* severe error. None of this logic applies for non-error messages.
231
* If we are inside a critical section, all errors become PANIC
232
* errors. See miscadmin.h.
234
if (CritSectionCount > 0)
238
* Check reasons for treating ERROR as FATAL:
240
* 1. we have no handler to pass the error to (implies we are in the
241
* postmaster or in backend startup).
243
* 2. ExitOnAnyError mode switch is set (initdb uses this).
245
* 3. the error occurred after proc_exit has begun to run. (It's
246
* proc_exit's responsibility to see that this doesn't turn into
247
* infinite recursion!)
251
if (PG_exception_stack == NULL ||
253
proc_exit_inprogress)
258
* If the error level is ERROR or more, errfinish is not going to
259
* return to caller; therefore, if there is any stacked error already
260
* in progress it will be lost. This is more or less okay, except we
261
* do not want to have a FATAL or PANIC error downgraded because the
262
* reporting process was interrupted by a lower-grade error. So check
263
* the stack and make sure we panic if panic is warranted.
265
for (i = 0; i <= errordata_stack_depth; i++)
266
elevel = Max(elevel, errordata[i].elevel);
270
* Now decide whether we need to process this report at all; if it's
271
* warning or less and not enabled for logging, just return FALSE without
272
* starting up any error logging machinery.
275
/* Determine whether message is enabled for server log output */
276
if (IsPostmasterEnvironment)
277
output_to_server = is_log_level_output(elevel, log_min_messages);
279
/* In bootstrap/standalone case, do not sort LOG out-of-order */
280
output_to_server = (elevel >= log_min_messages);
282
/* Determine whether message is enabled for client output */
283
if (whereToSendOutput == DestRemote && elevel != COMMERROR)
286
* client_min_messages is honored only after we complete the
287
* authentication handshake. This is required both for security
288
* reasons and because many clients can't handle NOTICE messages
289
* during authentication.
291
if (ClientAuthInProgress)
292
output_to_client = (elevel >= ERROR);
294
output_to_client = (elevel >= client_min_messages ||
298
/* Skip processing effort if non-error message will not be output */
299
if (elevel < ERROR && !output_to_server && !output_to_client)
303
* Okay, crank up a stack entry to store the info in.
306
if (recursion_depth++ > 0 && elevel >= ERROR)
309
* Ooops, error during error processing. Clear ErrorContext as
310
* discussed at top of file. We will not return to the original
311
* error's reporter or handler, so we don't need it.
313
MemoryContextReset(ErrorContext);
316
* Infinite error recursion might be due to something broken in a
317
* context traceback routine. Abandon them too. We also abandon
318
* attempting to print the error statement (which, if long, could
319
* itself be the source of the recursive failure).
321
if (in_error_recursion_trouble())
323
error_context_stack = NULL;
324
debug_query_string = NULL;
327
if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
330
* Wups, stack not big enough. We treat this as a PANIC condition
331
* because it suggests an infinite loop of errors during error
334
errordata_stack_depth = -1; /* make room on stack */
335
ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
338
/* Initialize data for this error frame */
339
edata = &errordata[errordata_stack_depth];
340
MemSet(edata, 0, sizeof(ErrorData));
341
edata->elevel = elevel;
342
edata->output_to_server = output_to_server;
343
edata->output_to_client = output_to_client;
344
edata->filename = filename;
345
edata->lineno = lineno;
346
edata->funcname = funcname;
347
/* the default text domain is the backend's */
348
edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
349
/* Select default errcode based on elevel */
351
edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
352
else if (elevel == WARNING)
353
edata->sqlerrcode = ERRCODE_WARNING;
355
edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
356
/* errno is saved here so that error parameter eval can't change it */
357
edata->saved_errno = errno;
364
* errfinish --- end an error-reporting cycle
366
* Produce the appropriate error report(s) and pop the error stack.
368
* If elevel is ERROR or worse, control does not return to the caller.
369
* See elog.h for the error level definitions.
372
errfinish(int dummy,...)
374
ErrorData *edata = &errordata[errordata_stack_depth];
375
int elevel = edata->elevel;
376
MemoryContext oldcontext;
377
ErrorContextCallback *econtext;
383
* Do processing in ErrorContext, which we hope has enough reserved space
384
* to report an error.
386
oldcontext = MemoryContextSwitchTo(ErrorContext);
389
* Call any context callback functions. Errors occurring in callback
390
* functions will be treated as recursive errors --- this ensures we will
391
* avoid infinite recursion (see errstart).
393
for (econtext = error_context_stack;
395
econtext = econtext->previous)
396
(*econtext->callback) (econtext->arg);
399
* If ERROR (not more nor less) we pass it off to the current handler.
400
* Printing it and popping the stack is the responsibility of the handler.
405
* We do some minimal cleanup before longjmp'ing so that handlers can
406
* execute in a reasonably sane state.
409
/* This is just in case the error came while waiting for input */
410
ImmediateInterruptOK = false;
413
* Reset InterruptHoldoffCount in case we ereport'd from inside an
414
* interrupt holdoff section. (We assume here that no handler will
415
* itself be inside a holdoff section. If necessary, such a handler
416
* could save and restore InterruptHoldoffCount for itself, but this
417
* should make life easier for most.)
419
InterruptHoldoffCount = 0;
421
CritSectionCount = 0; /* should be unnecessary, but... */
424
* Note that we leave CurrentMemoryContext set to ErrorContext. The
425
* handler should reset it to something else soon.
433
* If we are doing FATAL or PANIC, abort any old-style COPY OUT in
434
* progress, so that we can report the message before dying. (Without
435
* this, pq_putmessage will refuse to send the message at all, which is
436
* what we want for NOTICE messages, but not for fatal exits.) This hack
437
* is necessary because of poor design of old-style copy protocol. Note
438
* we must do this even if client is fool enough to have set
439
* client_min_messages above FATAL, so don't look at output_to_client.
441
if (elevel >= FATAL && whereToSendOutput == DestRemote)
444
/* Emit the message to the right places */
447
/* Now free up subsidiary data attached to stack entry, and release it */
449
pfree(edata->message);
451
pfree(edata->detail);
452
if (edata->detail_log)
453
pfree(edata->detail_log);
457
pfree(edata->context);
458
if (edata->internalquery)
459
pfree(edata->internalquery);
461
errordata_stack_depth--;
463
/* Exit error-handling context */
464
MemoryContextSwitchTo(oldcontext);
468
* Perform error recovery action as specified by elevel.
473
* For a FATAL error, we let proc_exit clean up and exit.
475
ImmediateInterruptOK = false;
478
* If we just reported a startup failure, the client will disconnect
479
* on receiving it, so don't send any more to the client.
481
if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
482
whereToSendOutput = DestNone;
485
* fflush here is just to improve the odds that we get to see the
486
* error message, in case things are so hosed that proc_exit crashes.
487
* Any other code you might be tempted to add here should probably be
488
* in an on_proc_exit or on_shmem_exit callback instead.
494
* Do normal process-exit cleanup, then return exit code 1 to indicate
495
* FATAL termination. The postmaster may or may not consider this
496
* worthy of panic, depending on which subprocess returns it.
504
* Serious crash time. Postmaster will observe SIGABRT process exit
505
* status and kill the other backends too.
507
* XXX: what if we are *in* the postmaster? abort() won't kill our
510
ImmediateInterruptOK = false;
517
* We reach here if elevel <= WARNING. OK to return to caller.
519
* But check for cancel/die interrupt first --- this is so that the user
520
* can stop a query emitting tons of notice or warning messages, even if
521
* it's in a loop that otherwise fails to check for interrupts.
523
CHECK_FOR_INTERRUPTS();
528
* errcode --- add SQLSTATE error code to the current error
530
* The code is expected to be represented as per MAKE_SQLSTATE().
533
errcode(int sqlerrcode)
535
ErrorData *edata = &errordata[errordata_stack_depth];
537
/* we don't bother incrementing recursion_depth */
540
edata->sqlerrcode = sqlerrcode;
542
return 0; /* return value does not matter */
547
* errcode_for_file_access --- add SQLSTATE error code to the current error
549
* The SQLSTATE code is chosen based on the saved errno value. We assume
550
* that the failing operation was some type of disk file access.
552
* NOTE: the primary error message string should generally include %m
556
errcode_for_file_access(void)
558
ErrorData *edata = &errordata[errordata_stack_depth];
560
/* we don't bother incrementing recursion_depth */
563
switch (edata->saved_errno)
565
/* Permission-denied failures */
566
case EPERM: /* Not super-user */
567
case EACCES: /* Permission denied */
569
case EROFS: /* Read only file system */
571
edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
575
case ENOENT: /* No such file or directory */
576
edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
580
case EEXIST: /* File exists */
581
edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
584
/* Wrong object type or state */
585
case ENOTDIR: /* Not a directory */
586
case EISDIR: /* Is a directory */
587
#if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
588
case ENOTEMPTY: /* Directory not empty */
590
edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
593
/* Insufficient resources */
594
case ENOSPC: /* No space left on device */
595
edata->sqlerrcode = ERRCODE_DISK_FULL;
598
case ENFILE: /* File table overflow */
599
case EMFILE: /* Too many open files */
600
edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
603
/* Hardware failure */
604
case EIO: /* I/O error */
605
edata->sqlerrcode = ERRCODE_IO_ERROR;
608
/* All else is classified as internal errors */
610
edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
614
return 0; /* return value does not matter */
618
* errcode_for_socket_access --- add SQLSTATE error code to the current error
620
* The SQLSTATE code is chosen based on the saved errno value. We assume
621
* that the failing operation was some type of socket access.
623
* NOTE: the primary error message string should generally include %m
627
errcode_for_socket_access(void)
629
ErrorData *edata = &errordata[errordata_stack_depth];
631
/* we don't bother incrementing recursion_depth */
634
switch (edata->saved_errno)
636
/* Loss of connection */
641
edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
644
/* All else is classified as internal errors */
646
edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
650
return 0; /* return value does not matter */
655
* This macro handles expansion of a format string and associated parameters;
656
* it's common code for errmsg(), errdetail(), etc. Must be called inside
657
* a routine that is declared like "const char *fmt, ..." and has an edata
658
* pointer set up. The message is assigned to edata->targetfield, or
659
* appended to it if appendval is true. The message is subject to translation
660
* if translateit is true.
662
* Note: we pstrdup the buffer rather than just transferring its storage
663
* to the edata field because the buffer might be considerably larger than
666
#define EVALUATE_MESSAGE(targetfield, appendval, translateit) \
669
StringInfoData buf; \
670
/* Internationalize the error format string */ \
671
if (translateit && !in_error_recursion_trouble()) \
672
fmt = dgettext(edata->domain, fmt); \
673
/* Expand %m in format string */ \
674
fmtbuf = expand_fmt_string(fmt, edata); \
675
initStringInfo(&buf); \
676
if ((appendval) && edata->targetfield) { \
677
appendStringInfoString(&buf, edata->targetfield); \
678
appendStringInfoChar(&buf, '\n'); \
680
/* Generate actual output --- have to use appendStringInfoVA */ \
685
va_start(args, fmt); \
686
success = appendStringInfoVA(&buf, fmtbuf, args); \
690
enlargeStringInfo(&buf, buf.maxlen); \
692
/* Done with expanded fmt */ \
694
/* Save the completed message into the stack item */ \
695
if (edata->targetfield) \
696
pfree(edata->targetfield); \
697
edata->targetfield = pstrdup(buf.data); \
702
* Same as above, except for pluralized error messages. The calling routine
703
* must be declared like "const char *fmt_singular, const char *fmt_plural,
704
* unsigned long n, ...". Translation is assumed always wanted.
706
#define EVALUATE_MESSAGE_PLURAL(targetfield, appendval) \
710
StringInfoData buf; \
711
/* Internationalize the error format string */ \
712
if (!in_error_recursion_trouble()) \
713
fmt = dngettext(edata->domain, fmt_singular, fmt_plural, n); \
715
fmt = (n == 1 ? fmt_singular : fmt_plural); \
716
/* Expand %m in format string */ \
717
fmtbuf = expand_fmt_string(fmt, edata); \
718
initStringInfo(&buf); \
719
if ((appendval) && edata->targetfield) { \
720
appendStringInfoString(&buf, edata->targetfield); \
721
appendStringInfoChar(&buf, '\n'); \
723
/* Generate actual output --- have to use appendStringInfoVA */ \
729
success = appendStringInfoVA(&buf, fmtbuf, args); \
733
enlargeStringInfo(&buf, buf.maxlen); \
735
/* Done with expanded fmt */ \
737
/* Save the completed message into the stack item */ \
738
if (edata->targetfield) \
739
pfree(edata->targetfield); \
740
edata->targetfield = pstrdup(buf.data); \
746
* errmsg --- add a primary error message text to the current error
748
* In addition to the usual %-escapes recognized by printf, "%m" in
749
* fmt is replaced by the error message for the caller's value of errno.
751
* Note: no newline is needed at the end of the fmt string, since
752
* ereport will provide one for the output methods that need it.
755
errmsg(const char *fmt,...)
757
ErrorData *edata = &errordata[errordata_stack_depth];
758
MemoryContext oldcontext;
762
oldcontext = MemoryContextSwitchTo(ErrorContext);
764
EVALUATE_MESSAGE(message, false, true);
766
MemoryContextSwitchTo(oldcontext);
768
return 0; /* return value does not matter */
773
* errmsg_internal --- add a primary error message text to the current error
775
* This is exactly like errmsg() except that strings passed to errmsg_internal
776
* are not translated, and are customarily left out of the
777
* internationalization message dictionary. This should be used for "can't
778
* happen" cases that are probably not worth spending translation effort on.
779
* We also use this for certain cases where we *must* not try to translate
780
* the message because the translation would fail and result in infinite
784
errmsg_internal(const char *fmt,...)
786
ErrorData *edata = &errordata[errordata_stack_depth];
787
MemoryContext oldcontext;
791
oldcontext = MemoryContextSwitchTo(ErrorContext);
793
EVALUATE_MESSAGE(message, false, false);
795
MemoryContextSwitchTo(oldcontext);
797
return 0; /* return value does not matter */
802
* errmsg_plural --- add a primary error message text to the current error,
803
* with support for pluralization of the message text
806
errmsg_plural(const char *fmt_singular, const char *fmt_plural,
809
ErrorData *edata = &errordata[errordata_stack_depth];
810
MemoryContext oldcontext;
814
oldcontext = MemoryContextSwitchTo(ErrorContext);
816
EVALUATE_MESSAGE_PLURAL(message, false);
818
MemoryContextSwitchTo(oldcontext);
820
return 0; /* return value does not matter */
825
* errdetail --- add a detail error message text to the current error
828
errdetail(const char *fmt,...)
830
ErrorData *edata = &errordata[errordata_stack_depth];
831
MemoryContext oldcontext;
835
oldcontext = MemoryContextSwitchTo(ErrorContext);
837
EVALUATE_MESSAGE(detail, false, true);
839
MemoryContextSwitchTo(oldcontext);
841
return 0; /* return value does not matter */
846
* errdetail_log --- add a detail_log error message text to the current error
849
errdetail_log(const char *fmt,...)
851
ErrorData *edata = &errordata[errordata_stack_depth];
852
MemoryContext oldcontext;
856
oldcontext = MemoryContextSwitchTo(ErrorContext);
858
EVALUATE_MESSAGE(detail_log, false, true);
860
MemoryContextSwitchTo(oldcontext);
862
return 0; /* return value does not matter */
867
* errdetail_plural --- add a detail error message text to the current error,
868
* with support for pluralization of the message text
871
errdetail_plural(const char *fmt_singular, const char *fmt_plural,
874
ErrorData *edata = &errordata[errordata_stack_depth];
875
MemoryContext oldcontext;
879
oldcontext = MemoryContextSwitchTo(ErrorContext);
881
EVALUATE_MESSAGE_PLURAL(detail, false);
883
MemoryContextSwitchTo(oldcontext);
885
return 0; /* return value does not matter */
890
* errhint --- add a hint error message text to the current error
893
errhint(const char *fmt,...)
895
ErrorData *edata = &errordata[errordata_stack_depth];
896
MemoryContext oldcontext;
900
oldcontext = MemoryContextSwitchTo(ErrorContext);
902
EVALUATE_MESSAGE(hint, false, true);
904
MemoryContextSwitchTo(oldcontext);
906
return 0; /* return value does not matter */
911
* errcontext --- add a context error message text to the current error
913
* Unlike other cases, multiple calls are allowed to build up a stack of
914
* context information. We assume earlier calls represent more-closely-nested
918
errcontext(const char *fmt,...)
920
ErrorData *edata = &errordata[errordata_stack_depth];
921
MemoryContext oldcontext;
925
oldcontext = MemoryContextSwitchTo(ErrorContext);
927
EVALUATE_MESSAGE(context, true, true);
929
MemoryContextSwitchTo(oldcontext);
931
return 0; /* return value does not matter */
936
* errhidestmt --- optionally suppress STATEMENT: field of log entry
938
* This should be called if the message text already includes the statement.
941
errhidestmt(bool hide_stmt)
943
ErrorData *edata = &errordata[errordata_stack_depth];
945
/* we don't bother incrementing recursion_depth */
948
edata->hide_stmt = hide_stmt;
950
return 0; /* return value does not matter */
955
* errfunction --- add reporting function name to the current error
957
* This is used when backwards compatibility demands that the function
958
* name appear in messages sent to old-protocol clients. Note that the
959
* passed string is expected to be a non-freeable constant string.
962
errfunction(const char *funcname)
964
ErrorData *edata = &errordata[errordata_stack_depth];
966
/* we don't bother incrementing recursion_depth */
969
edata->funcname = funcname;
970
edata->show_funcname = true;
972
return 0; /* return value does not matter */
976
* errposition --- add cursor position to the current error
979
errposition(int cursorpos)
981
ErrorData *edata = &errordata[errordata_stack_depth];
983
/* we don't bother incrementing recursion_depth */
986
edata->cursorpos = cursorpos;
988
return 0; /* return value does not matter */
992
* internalerrposition --- add internal cursor position to the current error
995
internalerrposition(int cursorpos)
997
ErrorData *edata = &errordata[errordata_stack_depth];
999
/* we don't bother incrementing recursion_depth */
1000
CHECK_STACK_DEPTH();
1002
edata->internalpos = cursorpos;
1004
return 0; /* return value does not matter */
1008
* internalerrquery --- add internal query text to the current error
1010
* Can also pass NULL to drop the internal query text entry. This case
1011
* is intended for use in error callback subroutines that are editorializing
1012
* on the layout of the error report.
1015
internalerrquery(const char *query)
1017
ErrorData *edata = &errordata[errordata_stack_depth];
1019
/* we don't bother incrementing recursion_depth */
1020
CHECK_STACK_DEPTH();
1022
if (edata->internalquery)
1024
pfree(edata->internalquery);
1025
edata->internalquery = NULL;
1029
edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1031
return 0; /* return value does not matter */
1035
* geterrcode --- return the currently set SQLSTATE error code
1037
* This is only intended for use in error callback subroutines, since there
1038
* is no other place outside elog.c where the concept is meaningful.
1043
ErrorData *edata = &errordata[errordata_stack_depth];
1045
/* we don't bother incrementing recursion_depth */
1046
CHECK_STACK_DEPTH();
1048
return edata->sqlerrcode;
1052
* geterrposition --- return the currently set error position (0 if none)
1054
* This is only intended for use in error callback subroutines, since there
1055
* is no other place outside elog.c where the concept is meaningful.
1058
geterrposition(void)
1060
ErrorData *edata = &errordata[errordata_stack_depth];
1062
/* we don't bother incrementing recursion_depth */
1063
CHECK_STACK_DEPTH();
1065
return edata->cursorpos;
1069
* getinternalerrposition --- same for internal error position
1071
* This is only intended for use in error callback subroutines, since there
1072
* is no other place outside elog.c where the concept is meaningful.
1075
getinternalerrposition(void)
1077
ErrorData *edata = &errordata[errordata_stack_depth];
1079
/* we don't bother incrementing recursion_depth */
1080
CHECK_STACK_DEPTH();
1082
return edata->internalpos;
1087
* elog_start --- startup for old-style API
1089
* All that we do here is stash the hidden filename/lineno/funcname
1090
* arguments into a stack entry.
1092
* We need this to be separate from elog_finish because there's no other
1093
* portable way to deal with inserting extra arguments into the elog call.
1094
* (If macros with variable numbers of arguments were portable, it'd be
1095
* easy, but they aren't.)
1098
elog_start(const char *filename, int lineno, const char *funcname)
1102
if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1105
* Wups, stack not big enough. We treat this as a PANIC condition
1106
* because it suggests an infinite loop of errors during error
1107
* recovery. Note that the message is intentionally not localized,
1108
* else failure to convert it to client encoding could cause further
1111
errordata_stack_depth = -1; /* make room on stack */
1112
ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1115
edata = &errordata[errordata_stack_depth];
1116
edata->filename = filename;
1117
edata->lineno = lineno;
1118
edata->funcname = funcname;
1119
/* errno is saved now so that error parameter eval can't change it */
1120
edata->saved_errno = errno;
1124
* elog_finish --- finish up for old-style API
1127
elog_finish(int elevel, const char *fmt,...)
1129
ErrorData *edata = &errordata[errordata_stack_depth];
1130
MemoryContext oldcontext;
1132
CHECK_STACK_DEPTH();
1135
* Do errstart() to see if we actually want to report the message.
1137
errordata_stack_depth--;
1138
errno = edata->saved_errno;
1139
if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1140
return; /* nothing to do */
1143
* Format error message just like errmsg_internal().
1146
oldcontext = MemoryContextSwitchTo(ErrorContext);
1148
EVALUATE_MESSAGE(message, false, false);
1150
MemoryContextSwitchTo(oldcontext);
1154
* And let errfinish() finish up.
1161
* Functions to allow construction of error message strings separately from
1162
* the ereport() call itself.
1164
* The expected calling convention is
1166
* pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1168
* which can be hidden behind a macro such as GUC_check_errdetail(). We
1169
* assume that any functions called in the arguments of format_elog_string()
1170
* cannot result in re-entrant use of these functions --- otherwise the wrong
1171
* text domain might be used, or the wrong errno substituted for %m. This is
1172
* okay for the current usage with GUC check hooks, but might need further
1175
* The result of format_elog_string() is stored in ErrorContext, and will
1176
* therefore survive until FlushErrorState() is called.
1178
static int save_format_errnumber;
1179
static const char *save_format_domain;
1182
pre_format_elog_string(int errnumber, const char *domain)
1184
/* Save errno before evaluation of argument functions can change it */
1185
save_format_errnumber = errnumber;
1186
/* Save caller's text domain */
1187
save_format_domain = domain;
1191
format_elog_string(const char *fmt,...)
1195
MemoryContext oldcontext;
1197
/* Initialize a mostly-dummy error frame */
1199
MemSet(edata, 0, sizeof(ErrorData));
1200
/* the default text domain is the backend's */
1201
edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1202
/* set the errno to be used to interpret %m */
1203
edata->saved_errno = save_format_errnumber;
1205
oldcontext = MemoryContextSwitchTo(ErrorContext);
1207
EVALUATE_MESSAGE(message, false, true);
1209
MemoryContextSwitchTo(oldcontext);
1211
return edata->message;
1216
* Actual output of the top-of-stack error message
1218
* In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1219
* if the error is caught by somebody). For all other severity levels this
1220
* is called by errfinish.
1223
EmitErrorReport(void)
1225
ErrorData *edata = &errordata[errordata_stack_depth];
1226
MemoryContext oldcontext;
1229
CHECK_STACK_DEPTH();
1230
oldcontext = MemoryContextSwitchTo(ErrorContext);
1232
/* Send to server log, if enabled */
1233
if (edata->output_to_server)
1234
send_message_to_server_log(edata);
1236
/* Send to client, if enabled */
1237
if (edata->output_to_client)
1238
send_message_to_frontend(edata);
1240
MemoryContextSwitchTo(oldcontext);
1245
* CopyErrorData --- obtain a copy of the topmost error stack entry
1247
* This is only for use in error handler code. The data is copied into the
1248
* current memory context, so callers should always switch away from
1249
* ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1254
ErrorData *edata = &errordata[errordata_stack_depth];
1255
ErrorData *newedata;
1258
* we don't increment recursion_depth because out-of-memory here does not
1259
* indicate a problem within the error subsystem.
1261
CHECK_STACK_DEPTH();
1263
Assert(CurrentMemoryContext != ErrorContext);
1265
/* Copy the struct itself */
1266
newedata = (ErrorData *) palloc(sizeof(ErrorData));
1267
memcpy(newedata, edata, sizeof(ErrorData));
1269
/* Make copies of separately-allocated fields */
1270
if (newedata->message)
1271
newedata->message = pstrdup(newedata->message);
1272
if (newedata->detail)
1273
newedata->detail = pstrdup(newedata->detail);
1274
if (newedata->detail_log)
1275
newedata->detail_log = pstrdup(newedata->detail_log);
1277
newedata->hint = pstrdup(newedata->hint);
1278
if (newedata->context)
1279
newedata->context = pstrdup(newedata->context);
1280
if (newedata->internalquery)
1281
newedata->internalquery = pstrdup(newedata->internalquery);
1287
* FreeErrorData --- free the structure returned by CopyErrorData.
1289
* Error handlers should use this in preference to assuming they know all
1290
* the separately-allocated fields.
1293
FreeErrorData(ErrorData *edata)
1296
pfree(edata->message);
1298
pfree(edata->detail);
1299
if (edata->detail_log)
1300
pfree(edata->detail_log);
1304
pfree(edata->context);
1305
if (edata->internalquery)
1306
pfree(edata->internalquery);
1311
* FlushErrorState --- flush the error state after error recovery
1313
* This should be called by an error handler after it's done processing
1314
* the error; or as soon as it's done CopyErrorData, if it intends to
1315
* do stuff that is likely to provoke another error. You are not "out" of
1316
* the error subsystem until you have done this.
1319
FlushErrorState(void)
1322
* Reset stack to empty. The only case where it would be more than one
1323
* deep is if we serviced an error that interrupted construction of
1324
* another message. We assume control escaped out of that message
1325
* construction and won't ever go back.
1327
errordata_stack_depth = -1;
1328
recursion_depth = 0;
1329
/* Delete all data in ErrorContext */
1330
MemoryContextResetAndDeleteChildren(ErrorContext);
1334
* ReThrowError --- re-throw a previously copied error
1336
* A handler can do CopyErrorData/FlushErrorState to get out of the error
1337
* subsystem, then do some processing, and finally ReThrowError to re-throw
1338
* the original error. This is slower than just PG_RE_THROW() but should
1339
* be used if the "some processing" is likely to incur another error.
1342
ReThrowError(ErrorData *edata)
1344
ErrorData *newedata;
1346
Assert(edata->elevel == ERROR);
1348
/* Push the data back into the error context */
1350
MemoryContextSwitchTo(ErrorContext);
1352
if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1355
* Wups, stack not big enough. We treat this as a PANIC condition
1356
* because it suggests an infinite loop of errors during error
1359
errordata_stack_depth = -1; /* make room on stack */
1360
ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1363
newedata = &errordata[errordata_stack_depth];
1364
memcpy(newedata, edata, sizeof(ErrorData));
1366
/* Make copies of separately-allocated fields */
1367
if (newedata->message)
1368
newedata->message = pstrdup(newedata->message);
1369
if (newedata->detail)
1370
newedata->detail = pstrdup(newedata->detail);
1371
if (newedata->detail_log)
1372
newedata->detail_log = pstrdup(newedata->detail_log);
1374
newedata->hint = pstrdup(newedata->hint);
1375
if (newedata->context)
1376
newedata->context = pstrdup(newedata->context);
1377
if (newedata->internalquery)
1378
newedata->internalquery = pstrdup(newedata->internalquery);
1385
* pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1390
/* If possible, throw the error to the next outer setjmp handler */
1391
if (PG_exception_stack != NULL)
1392
siglongjmp(*PG_exception_stack, 1);
1396
* If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1397
* we have now exited only to discover that there is no outer setjmp
1398
* handler to pass the error to. Had the error been thrown outside
1399
* the block to begin with, we'd have promoted the error to FATAL, so
1400
* the correct behavior is to make it FATAL now; that is, emit it and
1401
* then call proc_exit.
1403
ErrorData *edata = &errordata[errordata_stack_depth];
1405
Assert(errordata_stack_depth >= 0);
1406
Assert(edata->elevel == ERROR);
1407
edata->elevel = FATAL;
1410
* At least in principle, the increase in severity could have changed
1411
* where-to-output decisions, so recalculate. This should stay in
1412
* sync with errstart(), which see for comments.
1414
if (IsPostmasterEnvironment)
1415
edata->output_to_server = is_log_level_output(FATAL,
1418
edata->output_to_server = (FATAL >= log_min_messages);
1419
if (whereToSendOutput == DestRemote)
1421
if (ClientAuthInProgress)
1422
edata->output_to_client = true;
1424
edata->output_to_client = (FATAL >= client_min_messages);
1428
* We can use errfinish() for the rest, but we don't want it to call
1429
* any error context routines a second time. Since we know we are
1430
* about to exit, it should be OK to just clear the context stack.
1432
error_context_stack = NULL;
1437
/* We mustn't return... */
1438
ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1439
__FILE__, __LINE__);
1442
* Since ExceptionalCondition isn't declared noreturn because of
1443
* TrapMacro(), we need this to keep gcc from complaining.
1450
* Initialization of error output file
1458
if (OutputFileName[0])
1461
* A debug-output file name was given.
1463
* Make sure we can write the file, and find out if it's a tty.
1465
if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1468
(errcode_for_file_access(),
1469
errmsg("could not open file \"%s\": %m", OutputFileName)));
1474
* Redirect our stderr to the debug output file.
1476
if (!freopen(OutputFileName, "a", stderr))
1478
(errcode_for_file_access(),
1479
errmsg("could not reopen file \"%s\" as stderr: %m",
1483
* If the file is a tty and we're running under the postmaster, try to
1484
* send stdout there as well (if it isn't a tty then stderr will block
1485
* out stdout, so we may as well let stdout go wherever it was going
1488
if (istty && IsUnderPostmaster)
1489
if (!freopen(OutputFileName, "a", stdout))
1491
(errcode_for_file_access(),
1492
errmsg("could not reopen file \"%s\" as stdout: %m",
1501
* Set or update the parameters for syslog logging
1504
set_syslog_parameters(const char *ident, int facility)
1507
* guc.c is likely to call us repeatedly with same parameters, so don't
1508
* thrash the syslog connection unnecessarily. Also, we do not re-open
1509
* the connection until needed, since this routine will get called whether
1510
* or not Log_destination actually mentions syslog.
1512
* Note that we make our own copy of the ident string rather than relying
1513
* on guc.c's. This may be overly paranoid, but it ensures that we cannot
1514
* accidentally free a string that syslog is still using.
1516
if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1517
syslog_facility != facility)
1522
openlog_done = false;
1526
syslog_ident = strdup(ident);
1527
/* if the strdup fails, we will cope in write_syslog() */
1528
syslog_facility = facility;
1534
* Write a message line to syslog
1537
write_syslog(int level, const char *line)
1539
static unsigned long seq = 0;
1544
/* Open syslog connection if not done yet */
1547
openlog(syslog_ident ? syslog_ident : "postgres",
1548
LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1550
openlog_done = true;
1554
* We add a sequence number to each log message to suppress "same"
1560
* Our problem here is that many syslog implementations don't handle long
1561
* messages in an acceptable manner. While this function doesn't help that
1562
* fact, it does work around by splitting up messages into smaller pieces.
1564
* We divide into multiple syslog() calls if message is too long or if the
1565
* message contains embedded newline(s).
1568
nlpos = strchr(line, '\n');
1569
if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1575
char buf[PG_SYSLOG_LIMIT + 1];
1579
/* if we start at a newline, move ahead one char */
1580
if (line[0] == '\n')
1584
/* we need to recompute the next newline's position, too */
1585
nlpos = strchr(line, '\n');
1589
/* copy one line, or as much as will fit, to buf */
1591
buflen = nlpos - line;
1594
buflen = Min(buflen, PG_SYSLOG_LIMIT);
1595
memcpy(buf, line, buflen);
1598
/* trim to multibyte letter boundary */
1599
buflen = pg_mbcliplen(buf, buflen, buflen);
1604
/* already word boundary? */
1605
if (line[buflen] != '\0' &&
1606
!isspace((unsigned char) line[buflen]))
1608
/* try to divide at word boundary */
1610
while (i > 0 && !isspace((unsigned char) buf[i]))
1613
if (i > 0) /* else couldn't divide word boundary */
1622
syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1629
/* message short enough */
1630
syslog(level, "[%lu] %s", seq, line);
1633
#endif /* HAVE_SYSLOG */
1637
* Write a message line to the windows event log
1640
write_eventlog(int level, const char *line, int len)
1643
int eventlevel = EVENTLOG_ERROR_TYPE;
1644
static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1646
if (evtHandle == INVALID_HANDLE_VALUE)
1648
evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1649
if (evtHandle == NULL)
1651
evtHandle = INVALID_HANDLE_VALUE;
1667
eventlevel = EVENTLOG_INFORMATION_TYPE;
1670
eventlevel = EVENTLOG_WARNING_TYPE;
1676
eventlevel = EVENTLOG_ERROR_TYPE;
1681
* Convert message to UTF16 text and write it with ReportEventW, but
1682
* fall-back into ReportEventA if conversion failed.
1684
* Also verify that we are not on our way into error recursion trouble due
1685
* to error messages thrown deep inside pgwin32_toUTF16().
1687
if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1688
!in_error_recursion_trouble())
1690
utf16 = pgwin32_toUTF16(line, len, NULL);
1693
ReportEventW(evtHandle,
1696
0, /* All events are Id 0 */
1707
ReportEventA(evtHandle,
1710
0, /* All events are Id 0 */
1720
write_console(const char *line, int len)
1725
* WriteConsoleW() will fail of stdout is redirected, so just fall through
1726
* to writing unconverted to the logfile in this case.
1728
* Since we palloc the structure required for conversion, also fall
1729
* through to writing unconverted if we have not yet set up
1730
* CurrentMemoryContext.
1732
if (GetDatabaseEncoding() != GetPlatformEncoding() &&
1733
!in_error_recursion_trouble() &&
1734
!redirection_done &&
1735
CurrentMemoryContext != NULL)
1740
utf16 = pgwin32_toUTF16(line, len, &utf16len);
1746
stdHandle = GetStdHandle(STD_ERROR_HANDLE);
1747
if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
1754
* In case WriteConsoleW() failed, fall back to writing the
1755
* message unconverted.
1763
* Conversion on non-win32 platform is not implemented yet. It requires
1764
* non-throw version of pg_do_encoding_conversion(), that converts
1765
* unconvertable characters to '?' without errors.
1769
write(fileno(stderr), line, len);
1773
* setup formatted_log_time, for consistent times between CSV and regular logs
1776
setup_formatted_log_time(void)
1779
pg_time_t stamp_time;
1783
gettimeofday(&tv, NULL);
1784
stamp_time = (pg_time_t) tv.tv_sec;
1787
* Normally we print log timestamps in log_timezone, but during startup we
1788
* could get here before that's set. If so, fall back to gmt_timezone
1789
* (which guc.c ensures is set up before Log_line_prefix can become
1792
tz = log_timezone ? log_timezone : gmt_timezone;
1794
pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1795
/* leave room for milliseconds... */
1796
"%Y-%m-%d %H:%M:%S %Z",
1797
pg_localtime(&stamp_time, tz));
1799
/* 'paste' milliseconds into place... */
1800
sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1801
strncpy(formatted_log_time + 19, msbuf, 4);
1805
* setup formatted_start_time
1808
setup_formatted_start_time(void)
1810
pg_time_t stamp_time = (pg_time_t) MyStartTime;
1814
* Normally we print log timestamps in log_timezone, but during startup we
1815
* could get here before that's set. If so, fall back to gmt_timezone
1816
* (which guc.c ensures is set up before Log_line_prefix can become
1819
tz = log_timezone ? log_timezone : gmt_timezone;
1821
pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1822
"%Y-%m-%d %H:%M:%S %Z",
1823
pg_localtime(&stamp_time, tz));
1827
* Format tag info for log lines; append to the provided buffer.
1830
log_line_prefix(StringInfo buf, ErrorData *edata)
1832
/* static counter for line numbers */
1833
static long log_line_number = 0;
1835
/* has counter been reset in current process? */
1836
static int log_my_pid = 0;
1842
* This is one of the few places where we'd rather not inherit a static
1843
* variable's value from the postmaster. But since we will, reset it when
1844
* MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1845
* reset the formatted start timestamp too.
1847
if (log_my_pid != MyProcPid)
1849
log_line_number = 0;
1850
log_my_pid = MyProcPid;
1851
formatted_start_time[0] = '\0';
1855
if (Log_line_prefix == NULL)
1856
return; /* in case guc hasn't run yet */
1858
format_len = strlen(Log_line_prefix);
1860
for (i = 0; i < format_len; i++)
1862
if (Log_line_prefix[i] != '%')
1864
/* literal char, just copy */
1865
appendStringInfoChar(buf, Log_line_prefix[i]);
1868
/* go to char after '%' */
1870
if (i >= format_len)
1871
break; /* format error - ignore it */
1873
/* process the option */
1874
switch (Log_line_prefix[i])
1879
const char *appname = application_name;
1881
if (appname == NULL || *appname == '\0')
1882
appname = _("[unknown]");
1883
appendStringInfoString(buf, appname);
1889
const char *username = MyProcPort->user_name;
1891
if (username == NULL || *username == '\0')
1892
username = _("[unknown]");
1893
appendStringInfoString(buf, username);
1899
const char *dbname = MyProcPort->database_name;
1901
if (dbname == NULL || *dbname == '\0')
1902
dbname = _("[unknown]");
1903
appendStringInfoString(buf, dbname);
1907
appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1910
appendStringInfo(buf, "%d", MyProcPid);
1913
appendStringInfo(buf, "%ld", log_line_number);
1916
setup_formatted_log_time();
1917
appendStringInfoString(buf, formatted_log_time);
1921
pg_time_t stamp_time = (pg_time_t) time(NULL);
1925
tz = log_timezone ? log_timezone : gmt_timezone;
1927
pg_strftime(strfbuf, sizeof(strfbuf),
1928
"%Y-%m-%d %H:%M:%S %Z",
1929
pg_localtime(&stamp_time, tz));
1930
appendStringInfoString(buf, strfbuf);
1934
if (formatted_start_time[0] == '\0')
1935
setup_formatted_start_time();
1936
appendStringInfoString(buf, formatted_start_time);
1944
psdisp = get_ps_display(&displen);
1945
appendBinaryStringInfo(buf, psdisp, displen);
1949
if (MyProcPort && MyProcPort->remote_host)
1951
appendStringInfoString(buf, MyProcPort->remote_host);
1952
if (MyProcPort->remote_port &&
1953
MyProcPort->remote_port[0] != '\0')
1954
appendStringInfo(buf, "(%s)",
1955
MyProcPort->remote_port);
1959
if (MyProcPort && MyProcPort->remote_host)
1960
appendStringInfoString(buf, MyProcPort->remote_host);
1963
/* in postmaster and friends, stop if %q is seen */
1964
/* in a backend, just ignore */
1965
if (MyProcPort == NULL)
1969
/* keep VXID format in sync with lockfuncs.c */
1970
if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1971
appendStringInfo(buf, "%d/%u",
1972
MyProc->backendId, MyProc->lxid);
1975
appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1978
appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
1981
appendStringInfoChar(buf, '%');
1984
/* format error - ignore it */
1991
* append a CSV'd version of a string to a StringInfo
1992
* We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1993
* If it's NULL, append nothing.
1996
appendCSVLiteral(StringInfo buf, const char *data)
1998
const char *p = data;
2001
/* avoid confusing an empty string with NULL */
2005
appendStringInfoCharMacro(buf, '"');
2006
while ((c = *p++) != '\0')
2009
appendStringInfoCharMacro(buf, '"');
2010
appendStringInfoCharMacro(buf, c);
2012
appendStringInfoCharMacro(buf, '"');
2016
* Constructs the error message, depending on the Errordata it gets, in a CSV
2017
* format which is described in doc/src/sgml/config.sgml.
2020
write_csvlog(ErrorData *edata)
2023
bool print_stmt = false;
2025
/* static counter for line numbers */
2026
static long log_line_number = 0;
2028
/* has counter been reset in current process? */
2029
static int log_my_pid = 0;
2032
* This is one of the few places where we'd rather not inherit a static
2033
* variable's value from the postmaster. But since we will, reset it when
2034
* MyProcPid changes.
2036
if (log_my_pid != MyProcPid)
2038
log_line_number = 0;
2039
log_my_pid = MyProcPid;
2040
formatted_start_time[0] = '\0';
2044
initStringInfo(&buf);
2047
* timestamp with milliseconds
2049
* Check if the timestamp is already calculated for the syslog message,
2050
* and use it if so. Otherwise, get the current timestamp. This is done
2051
* to put same timestamp in both syslog and csvlog messages.
2053
if (formatted_log_time[0] == '\0')
2054
setup_formatted_log_time();
2056
appendStringInfoString(&buf, formatted_log_time);
2057
appendStringInfoChar(&buf, ',');
2061
appendCSVLiteral(&buf, MyProcPort->user_name);
2062
appendStringInfoChar(&buf, ',');
2066
appendCSVLiteral(&buf, MyProcPort->database_name);
2067
appendStringInfoChar(&buf, ',');
2071
appendStringInfo(&buf, "%d", MyProcPid);
2072
appendStringInfoChar(&buf, ',');
2074
/* Remote host and port */
2075
if (MyProcPort && MyProcPort->remote_host)
2077
appendStringInfoChar(&buf, '"');
2078
appendStringInfoString(&buf, MyProcPort->remote_host);
2079
if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2081
appendStringInfoChar(&buf, ':');
2082
appendStringInfoString(&buf, MyProcPort->remote_port);
2084
appendStringInfoChar(&buf, '"');
2086
appendStringInfoChar(&buf, ',');
2089
appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2090
appendStringInfoChar(&buf, ',');
2093
appendStringInfo(&buf, "%ld", log_line_number);
2094
appendStringInfoChar(&buf, ',');
2099
StringInfoData msgbuf;
2103
initStringInfo(&msgbuf);
2105
psdisp = get_ps_display(&displen);
2106
appendBinaryStringInfo(&msgbuf, psdisp, displen);
2107
appendCSVLiteral(&buf, msgbuf.data);
2111
appendStringInfoChar(&buf, ',');
2113
/* session start timestamp */
2114
if (formatted_start_time[0] == '\0')
2115
setup_formatted_start_time();
2116
appendStringInfoString(&buf, formatted_start_time);
2117
appendStringInfoChar(&buf, ',');
2119
/* Virtual transaction id */
2120
/* keep VXID format in sync with lockfuncs.c */
2121
if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2122
appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2123
appendStringInfoChar(&buf, ',');
2125
/* Transaction id */
2126
appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2127
appendStringInfoChar(&buf, ',');
2129
/* Error severity */
2130
appendStringInfoString(&buf, error_severity(edata->elevel));
2131
appendStringInfoChar(&buf, ',');
2133
/* SQL state code */
2134
appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2135
appendStringInfoChar(&buf, ',');
2138
appendCSVLiteral(&buf, edata->message);
2139
appendStringInfoChar(&buf, ',');
2141
/* errdetail or errdetail_log */
2142
if (edata->detail_log)
2143
appendCSVLiteral(&buf, edata->detail_log);
2145
appendCSVLiteral(&buf, edata->detail);
2146
appendStringInfoChar(&buf, ',');
2149
appendCSVLiteral(&buf, edata->hint);
2150
appendStringInfoChar(&buf, ',');
2152
/* internal query */
2153
appendCSVLiteral(&buf, edata->internalquery);
2154
appendStringInfoChar(&buf, ',');
2156
/* if printed internal query, print internal pos too */
2157
if (edata->internalpos > 0 && edata->internalquery != NULL)
2158
appendStringInfo(&buf, "%d", edata->internalpos);
2159
appendStringInfoChar(&buf, ',');
2162
appendCSVLiteral(&buf, edata->context);
2163
appendStringInfoChar(&buf, ',');
2165
/* user query --- only reported if not disabled by the caller */
2166
if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2167
debug_query_string != NULL &&
2171
appendCSVLiteral(&buf, debug_query_string);
2172
appendStringInfoChar(&buf, ',');
2173
if (print_stmt && edata->cursorpos > 0)
2174
appendStringInfo(&buf, "%d", edata->cursorpos);
2175
appendStringInfoChar(&buf, ',');
2177
/* file error location */
2178
if (Log_error_verbosity >= PGERROR_VERBOSE)
2180
StringInfoData msgbuf;
2182
initStringInfo(&msgbuf);
2184
if (edata->funcname && edata->filename)
2185
appendStringInfo(&msgbuf, "%s, %s:%d",
2186
edata->funcname, edata->filename,
2188
else if (edata->filename)
2189
appendStringInfo(&msgbuf, "%s:%d",
2190
edata->filename, edata->lineno);
2191
appendCSVLiteral(&buf, msgbuf.data);
2194
appendStringInfoChar(&buf, ',');
2196
/* application name */
2197
if (application_name)
2198
appendCSVLiteral(&buf, application_name);
2200
appendStringInfoChar(&buf, '\n');
2202
/* If in the syslogger process, try to write messages direct to file */
2204
write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2206
write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2212
* Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2216
unpack_sql_state(int sql_state)
2218
static char buf[12];
2221
for (i = 0; i < 5; i++)
2223
buf[i] = PGUNSIXBIT(sql_state);
2233
* Write error report to server's log
2236
send_message_to_server_log(ErrorData *edata)
2240
initStringInfo(&buf);
2242
formatted_log_time[0] = '\0';
2244
log_line_prefix(&buf, edata);
2245
appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2247
if (Log_error_verbosity >= PGERROR_VERBOSE)
2248
appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2251
append_with_tabs(&buf, edata->message);
2253
append_with_tabs(&buf, _("missing error text"));
2255
if (edata->cursorpos > 0)
2256
appendStringInfo(&buf, _(" at character %d"),
2258
else if (edata->internalpos > 0)
2259
appendStringInfo(&buf, _(" at character %d"),
2260
edata->internalpos);
2262
appendStringInfoChar(&buf, '\n');
2264
if (Log_error_verbosity >= PGERROR_DEFAULT)
2266
if (edata->detail_log)
2268
log_line_prefix(&buf, edata);
2269
appendStringInfoString(&buf, _("DETAIL: "));
2270
append_with_tabs(&buf, edata->detail_log);
2271
appendStringInfoChar(&buf, '\n');
2273
else if (edata->detail)
2275
log_line_prefix(&buf, edata);
2276
appendStringInfoString(&buf, _("DETAIL: "));
2277
append_with_tabs(&buf, edata->detail);
2278
appendStringInfoChar(&buf, '\n');
2282
log_line_prefix(&buf, edata);
2283
appendStringInfoString(&buf, _("HINT: "));
2284
append_with_tabs(&buf, edata->hint);
2285
appendStringInfoChar(&buf, '\n');
2287
if (edata->internalquery)
2289
log_line_prefix(&buf, edata);
2290
appendStringInfoString(&buf, _("QUERY: "));
2291
append_with_tabs(&buf, edata->internalquery);
2292
appendStringInfoChar(&buf, '\n');
2296
log_line_prefix(&buf, edata);
2297
appendStringInfoString(&buf, _("CONTEXT: "));
2298
append_with_tabs(&buf, edata->context);
2299
appendStringInfoChar(&buf, '\n');
2301
if (Log_error_verbosity >= PGERROR_VERBOSE)
2303
/* assume no newlines in funcname or filename... */
2304
if (edata->funcname && edata->filename)
2306
log_line_prefix(&buf, edata);
2307
appendStringInfo(&buf, _("LOCATION: %s, %s:%d\n"),
2308
edata->funcname, edata->filename,
2311
else if (edata->filename)
2313
log_line_prefix(&buf, edata);
2314
appendStringInfo(&buf, _("LOCATION: %s:%d\n"),
2315
edata->filename, edata->lineno);
2321
* If the user wants the query that generated this error logged, do it.
2323
if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2324
debug_query_string != NULL &&
2327
log_line_prefix(&buf, edata);
2328
appendStringInfoString(&buf, _("STATEMENT: "));
2329
append_with_tabs(&buf, debug_query_string);
2330
appendStringInfoChar(&buf, '\n');
2334
/* Write to syslog, if enabled */
2335
if (Log_destination & LOG_DESTINATION_SYSLOG)
2339
switch (edata->elevel)
2346
syslog_level = LOG_DEBUG;
2351
syslog_level = LOG_INFO;
2355
syslog_level = LOG_NOTICE;
2358
syslog_level = LOG_WARNING;
2361
syslog_level = LOG_ERR;
2365
syslog_level = LOG_CRIT;
2369
write_syslog(syslog_level, buf.data);
2371
#endif /* HAVE_SYSLOG */
2374
/* Write to eventlog, if enabled */
2375
if (Log_destination & LOG_DESTINATION_EVENTLOG)
2377
write_eventlog(edata->elevel, buf.data, buf.len);
2381
/* Write to stderr, if enabled */
2382
if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2385
* Use the chunking protocol if we know the syslogger should be
2386
* catching stderr output, and we are not ourselves the syslogger.
2387
* Otherwise, just do a vanilla write to stderr.
2389
if (redirection_done && !am_syslogger)
2390
write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2394
* In a win32 service environment, there is no usable stderr. Capture
2395
* anything going there and write it to the eventlog instead.
2397
* If stderr redirection is active, it was OK to write to stderr above
2398
* because that's really a pipe to the syslogger process.
2400
else if (pgwin32_is_service())
2401
write_eventlog(edata->elevel, buf.data, buf.len);
2404
write_console(buf.data, buf.len);
2407
/* If in the syslogger process, try to write messages direct to file */
2409
write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2411
/* Write to CSV log if enabled */
2412
if (Log_destination & LOG_DESTINATION_CSVLOG)
2414
if (redirection_done || am_syslogger)
2417
* send CSV data if it's safe to do so (syslogger doesn't need the
2418
* pipe). First get back the space in the message buffer.
2421
write_csvlog(edata);
2426
* syslogger not up (yet), so just dump the message to stderr,
2427
* unless we already did so above.
2429
if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2430
whereToSendOutput != DestDebug)
2431
write_console(buf.data, buf.len);
2442
* Send data to the syslogger using the chunked protocol
2445
write_pipe_chunks(char *data, int len, int dest)
2449
int fd = fileno(stderr);
2453
p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2454
p.proto.pid = MyProcPid;
2456
/* write all but the last chunk */
2457
while (len > PIPE_MAX_PAYLOAD)
2459
p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2460
p.proto.len = PIPE_MAX_PAYLOAD;
2461
memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2462
write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2463
data += PIPE_MAX_PAYLOAD;
2464
len -= PIPE_MAX_PAYLOAD;
2467
/* write the last chunk */
2468
p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2470
memcpy(p.proto.data, data, len);
2471
write(fd, &p, PIPE_HEADER_SIZE + len);
2476
* Append a text string to the error report being built for the client.
2478
* This is ordinarily identical to pq_sendstring(), but if we are in
2479
* error recursion trouble we skip encoding conversion, because of the
2480
* possibility that the problem is a failure in the encoding conversion
2481
* subsystem itself. Code elsewhere should ensure that the passed-in
2482
* strings will be plain 7-bit ASCII, and thus not in need of conversion,
2483
* in such cases. (In particular, we disable localization of error messages
2484
* to help ensure that's true.)
2487
err_sendstring(StringInfo buf, const char *str)
2489
if (in_error_recursion_trouble())
2490
pq_send_ascii_string(buf, str);
2492
pq_sendstring(buf, str);
2496
* Write error report to client
2499
send_message_to_frontend(ErrorData *edata)
2501
StringInfoData msgbuf;
2503
/* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2504
pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2506
if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2508
/* New style with separate fields */
2513
pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2514
err_sendstring(&msgbuf, error_severity(edata->elevel));
2516
/* unpack MAKE_SQLSTATE code */
2517
ssval = edata->sqlerrcode;
2518
for (i = 0; i < 5; i++)
2520
tbuf[i] = PGUNSIXBIT(ssval);
2525
pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2526
err_sendstring(&msgbuf, tbuf);
2528
/* M field is required per protocol, so always send something */
2529
pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2531
err_sendstring(&msgbuf, edata->message);
2533
err_sendstring(&msgbuf, _("missing error text"));
2537
pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2538
err_sendstring(&msgbuf, edata->detail);
2541
/* detail_log is intentionally not used here */
2545
pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2546
err_sendstring(&msgbuf, edata->hint);
2551
pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2552
err_sendstring(&msgbuf, edata->context);
2555
if (edata->cursorpos > 0)
2557
snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2558
pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2559
err_sendstring(&msgbuf, tbuf);
2562
if (edata->internalpos > 0)
2564
snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2565
pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2566
err_sendstring(&msgbuf, tbuf);
2569
if (edata->internalquery)
2571
pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2572
err_sendstring(&msgbuf, edata->internalquery);
2575
if (edata->filename)
2577
pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2578
err_sendstring(&msgbuf, edata->filename);
2581
if (edata->lineno > 0)
2583
snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2584
pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2585
err_sendstring(&msgbuf, tbuf);
2588
if (edata->funcname)
2590
pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2591
err_sendstring(&msgbuf, edata->funcname);
2594
pq_sendbyte(&msgbuf, '\0'); /* terminator */
2598
/* Old style --- gin up a backwards-compatible message */
2601
initStringInfo(&buf);
2603
appendStringInfo(&buf, "%s: ", error_severity(edata->elevel));
2605
if (edata->show_funcname && edata->funcname)
2606
appendStringInfo(&buf, "%s: ", edata->funcname);
2609
appendStringInfoString(&buf, edata->message);
2611
appendStringInfoString(&buf, _("missing error text"));
2613
if (edata->cursorpos > 0)
2614
appendStringInfo(&buf, _(" at character %d"),
2616
else if (edata->internalpos > 0)
2617
appendStringInfo(&buf, _(" at character %d"),
2618
edata->internalpos);
2620
appendStringInfoChar(&buf, '\n');
2622
err_sendstring(&msgbuf, buf.data);
2627
pq_endmessage(&msgbuf);
2630
* This flush is normally not necessary, since postgres.c will flush out
2631
* waiting data when control returns to the main loop. But it seems best
2632
* to leave it here, so that the client has some clue what happened if the
2633
* backend dies before getting back to the main loop ... error/notice
2634
* messages should not be a performance-critical path anyway, so an extra
2635
* flush won't hurt much ...
2642
* Support routines for formatting error messages.
2647
* expand_fmt_string --- process special format codes in a format string
2649
* We must replace %m with the appropriate strerror string, since vsnprintf
2650
* won't know what to do with it.
2652
* The result is a palloc'd string.
2655
expand_fmt_string(const char *fmt, ErrorData *edata)
2660
initStringInfo(&buf);
2662
for (cp = fmt; *cp; cp++)
2664
if (cp[0] == '%' && cp[1] != '\0')
2670
* Replace %m by system error string. If there are any %'s in
2671
* the string, we'd better double them so that vsnprintf won't
2676
cp2 = useful_strerror(edata->saved_errno);
2680
appendStringInfoCharMacro(&buf, '%');
2681
appendStringInfoCharMacro(&buf, *cp2);
2686
/* copy % and next char --- this avoids trouble with %%m */
2687
appendStringInfoCharMacro(&buf, '%');
2688
appendStringInfoCharMacro(&buf, *cp);
2692
appendStringInfoCharMacro(&buf, *cp);
2700
* A slightly cleaned-up version of strerror()
2703
useful_strerror(int errnum)
2705
/* this buffer is only used if errno has a bogus value */
2706
static char errorstr_buf[48];
2710
/* Winsock error code range, per WinError.h */
2711
if (errnum >= 10000 && errnum <= 11999)
2712
return pgwin32_socket_strerror(errnum);
2714
str = strerror(errnum);
2717
* Some strerror()s return an empty string for out-of-range errno. This is
2718
* ANSI C spec compliant, but not exactly useful.
2720
if (str == NULL || *str == '\0')
2722
snprintf(errorstr_buf, sizeof(errorstr_buf),
2724
translator: This string will be truncated at 47
2725
characters expanded. */
2726
_("operating system error %d"), errnum);
2735
* error_severity --- get localized string representing elevel
2738
error_severity(int elevel)
2749
prefix = _("DEBUG");
2759
prefix = _("NOTICE");
2762
prefix = _("WARNING");
2765
prefix = _("ERROR");
2768
prefix = _("FATAL");
2771
prefix = _("PANIC");
2785
* Append the string to the StringInfo buffer, inserting a tab after any
2789
append_with_tabs(StringInfo buf, const char *str)
2793
while ((ch = *str++) != '\0')
2795
appendStringInfoCharMacro(buf, ch);
2797
appendStringInfoCharMacro(buf, '\t');
2803
* Write errors to stderr (or by equal means when stderr is
2804
* not available). Used before ereport/elog can be used
2805
* safely (memory context, GUC load etc)
2808
write_stderr(const char *fmt,...)
2813
char errbuf[2048]; /* Arbitrary size? */
2820
/* On Unix, we just fprintf to stderr */
2821
vfprintf(stderr, fmt, ap);
2824
vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2827
* On Win32, we print to stderr if running on a console, or write to
2828
* eventlog if running as a service
2830
if (pgwin32_is_service()) /* Running as a service */
2832
write_eventlog(ERROR, errbuf, strlen(errbuf));
2836
/* Not running as service, write to stderr */
2837
write_console(errbuf, strlen(errbuf));
2846
* is_log_level_output -- is elevel logically >= log_min_level?
2848
* We use this for tests that should consider LOG to sort out-of-order,
2849
* between ERROR and FATAL. Generally this is the right thing for testing
2850
* whether a message should go to the postmaster log, whereas a simple >=
2851
* test is correct for testing whether the message should go to the client.
2854
is_log_level_output(int elevel, int log_min_level)
2856
if (elevel == LOG || elevel == COMMERROR)
2858
if (log_min_level == LOG || log_min_level <= ERROR)
2861
else if (log_min_level == LOG)
2864
if (elevel >= FATAL)
2867
/* Neither is LOG */
2868
else if (elevel >= log_min_level)
2875
* Adjust the level of a recovery-related message per trace_recovery_messages.
2877
* The argument is the default log level of the message, eg, DEBUG2. (This
2878
* should only be applied to DEBUGn log messages, otherwise it's a no-op.)
2879
* If the level is >= trace_recovery_messages, we return LOG, causing the
2880
* message to be logged unconditionally (for most settings of
2881
* log_min_messages). Otherwise, we return the argument unchanged.
2882
* The message will then be shown based on the setting of log_min_messages.
2884
* Intention is to keep this for at least the whole of the 9.0 production
2885
* release, so we can more easily diagnose production problems in the field.
2886
* It should go away eventually, though, because it's an ugly and
2887
* hard-to-explain kluge.
2890
trace_recovery(int trace_level)
2892
if (trace_level < LOG &&
2893
trace_level >= trace_recovery_messages)