1 /*-------------------------------------------------------------------------
5 * The system logger (syslogger) is new in Postgres 8.0. It catches all
6 * stderr output from the postmaster, backends, and other subprocesses
7 * by redirecting to a pipe, and writes it to a set of logfiles.
8 * It's possible to have size and age limits for the logfile configured
9 * in postgresql.conf. If these limits are reached or passed, the
10 * current logfile is closed and a new one is created (rotated).
11 * The logfiles are stored in a subdirectory (configurable in
12 * postgresql.conf), using an internal naming scheme that mangles
13 * creation time and current postmaster pid.
15 * Author: Andreas Pflug <pgadmin@pse-consulting.de>
17 * Copyright (c) 2004-2009, PostgreSQL Global Development Group
23 *-------------------------------------------------------------------------
34 #include "lib/stringinfo.h"
35 #include "libpq/pqsignal.h"
36 #include "miscadmin.h"
38 #include "postmaster/fork_process.h"
39 #include "postmaster/postmaster.h"
40 #include "postmaster/syslogger.h"
41 #include "storage/ipc.h"
42 #include "storage/pg_shmem.h"
43 #include "utils/guc.h"
44 #include "utils/ps_status.h"
45 #include "utils/timestamp.h"
48 * We really want line-buffered mode for logfile output, but Windows does
49 * not have it, and interprets _IOLBF as _IOFBF (bozos). So use _IONBF
53 #define LBF_MODE _IONBF
55 #define LBF_MODE _IOLBF
59 * We read() into a temp buffer twice as big as a chunk, so that any fragment
60 * left after processing can be moved down to the front and we'll still have
61 * room to read a full chunk.
63 #define READ_BUF_SIZE (2 * PIPE_CHUNK_SIZE)
67 * GUC parameters. Logging_collector cannot be changed after postmaster
68 * start, but the rest can change at SIGHUP.
70 bool Logging_collector
= false;
71 int Log_RotationAge
= HOURS_PER_DAY
* MINS_PER_HOUR
;
72 int Log_RotationSize
= 10 * 1024;
73 char *Log_directory
= NULL
;
74 char *Log_filename
= NULL
;
75 bool Log_truncate_on_rotation
= false;
78 * Globally visible state (used by elog.c)
80 bool am_syslogger
= false;
82 extern bool redirection_done
;
87 static pg_time_t next_rotation_time
;
88 static bool pipe_eof_seen
= false;
89 static FILE *syslogFile
= NULL
;
90 static FILE *csvlogFile
= NULL
;
91 static char *last_file_name
= NULL
;
92 static char *last_csv_file_name
= NULL
;
95 * Buffers for saving partial messages from different backends. We don't expect
96 * that there will be very many outstanding at one time, so 20 seems plenty of
97 * leeway. If this array gets full we won't lose messages, but we will lose
98 * the protocol protection against them being partially written or interleaved.
100 * An inactive buffer has pid == 0 and undefined contents of data.
104 int32 pid
; /* PID of source process */
105 StringInfoData data
; /* accumulated data, as a StringInfo */
108 #define CHUNK_SLOTS 20
109 static save_buffer saved_chunks
[CHUNK_SLOTS
];
111 /* These must be exported for EXEC_BACKEND case ... annoying */
113 int syslogPipe
[2] = {-1, -1};
115 HANDLE syslogPipe
[2] = {0, 0};
119 static HANDLE threadHandle
= 0;
120 static CRITICAL_SECTION sysfileSection
;
124 * Flags set by interrupt handlers for later service in the main loop.
126 static volatile sig_atomic_t got_SIGHUP
= false;
127 static volatile sig_atomic_t rotation_requested
= false;
130 /* Local subroutines */
132 static pid_t
syslogger_forkexec(void);
133 static void syslogger_parseArgs(int argc
, char *argv
[]);
135 static void process_pipe_input(char *logbuffer
, int *bytes_in_logbuffer
);
136 static void flush_pipe_input(char *logbuffer
, int *bytes_in_logbuffer
);
137 static void open_csvlogfile(void);
140 static unsigned int __stdcall
pipeThread(void *arg
);
142 static void logfile_rotate(bool time_based_rotation
, int size_rotation_for
);
143 static char *logfile_getname(pg_time_t timestamp
, char *suffix
);
144 static void set_next_rotation_time(void);
145 static void sigHupHandler(SIGNAL_ARGS
);
146 static void sigUsr1Handler(SIGNAL_ARGS
);
150 * Main entry point for syslogger process
151 * argc/argv parameters are valid only in EXEC_BACKEND case.
154 SysLoggerMain(int argc
, char *argv
[])
157 char logbuffer
[READ_BUF_SIZE
];
158 int bytes_in_logbuffer
= 0;
161 char *currentLogFilename
;
162 int currentLogRotationAge
;
164 IsUnderPostmaster
= true; /* we are a postmaster subprocess now */
166 MyProcPid
= getpid(); /* reset MyProcPid */
168 MyStartTime
= time(NULL
); /* set our start time in case we call elog */
171 syslogger_parseArgs(argc
, argv
);
172 #endif /* EXEC_BACKEND */
176 init_ps_display("logger process", "", "", "");
179 * If we restarted, our stderr is already redirected into our own input
180 * pipe. This is of course pretty useless, not to mention that it
181 * interferes with detecting pipe EOF. Point stderr to /dev/null. This
182 * assumes that all interesting messages generated in the syslogger will
183 * come through elog.c and will be sent to write_syslogger_file.
185 if (redirection_done
)
187 int fd
= open(DEVNULL
, O_WRONLY
, 0);
190 * The closes might look redundant, but they are not: we want to be
191 * darn sure the pipe gets closed even if the open failed. We can
192 * survive running with stderr pointing nowhere, but we can't afford
193 * to have extra pipe input descriptors hanging around.
195 close(fileno(stdout
));
196 close(fileno(stderr
));
197 dup2(fd
, fileno(stdout
));
198 dup2(fd
, fileno(stderr
));
203 * Syslogger's own stderr can't be the syslogPipe, so set it back to text
204 * mode if we didn't just close it. (It was set to binary in
205 * SubPostmasterMain).
209 _setmode(_fileno(stderr
), _O_TEXT
);
213 * Also close our copy of the write end of the pipe. This is needed to
214 * ensure we can detect pipe EOF correctly. (But note that in the restart
215 * case, the postmaster already did this.)
218 if (syslogPipe
[1] >= 0)
219 close(syslogPipe
[1]);
223 CloseHandle(syslogPipe
[1]);
228 * If possible, make this process a group leader, so that the postmaster
229 * can signal any child processes too. (syslogger probably never has any
230 * child processes, but for consistency we make all postmaster child
231 * processes do this.)
235 elog(FATAL
, "setsid() failed: %m");
239 * Properly accept or ignore signals the postmaster might send us
241 * Note: we ignore all termination signals, and instead exit only when all
242 * upstream processes are gone, to ensure we don't miss any dying gasps of
246 pqsignal(SIGHUP
, sigHupHandler
); /* set flag to read config file */
247 pqsignal(SIGINT
, SIG_IGN
);
248 pqsignal(SIGTERM
, SIG_IGN
);
249 pqsignal(SIGQUIT
, SIG_IGN
);
250 pqsignal(SIGALRM
, SIG_IGN
);
251 pqsignal(SIGPIPE
, SIG_IGN
);
252 pqsignal(SIGUSR1
, sigUsr1Handler
); /* request log rotation */
253 pqsignal(SIGUSR2
, SIG_IGN
);
256 * Reset some signals that are accepted by postmaster but not here
258 pqsignal(SIGCHLD
, SIG_DFL
);
259 pqsignal(SIGTTIN
, SIG_DFL
);
260 pqsignal(SIGTTOU
, SIG_DFL
);
261 pqsignal(SIGCONT
, SIG_DFL
);
262 pqsignal(SIGWINCH
, SIG_DFL
);
264 PG_SETMASK(&UnBlockSig
);
267 /* Fire up separate data transfer thread */
268 InitializeCriticalSection(&sysfileSection
);
270 threadHandle
= (HANDLE
) _beginthreadex(NULL
, 0, pipeThread
, NULL
, 0, NULL
);
271 if (threadHandle
== 0)
272 elog(FATAL
, "could not create syslogger data transfer thread: %m");
275 /* remember active logfile parameters */
276 currentLogDir
= pstrdup(Log_directory
);
277 currentLogFilename
= pstrdup(Log_filename
);
278 currentLogRotationAge
= Log_RotationAge
;
279 /* set next planned rotation time */
280 set_next_rotation_time();
282 /* main worker loop */
285 bool time_based_rotation
= false;
286 int size_rotation_for
= 0;
292 struct timeval timeout
;
298 ProcessConfigFile(PGC_SIGHUP
);
301 * Check if the log directory or filename pattern changed in
302 * postgresql.conf. If so, force rotation to make sure we're
303 * writing the logfiles in the right place.
305 if (strcmp(Log_directory
, currentLogDir
) != 0)
307 pfree(currentLogDir
);
308 currentLogDir
= pstrdup(Log_directory
);
309 rotation_requested
= true;
311 if (strcmp(Log_filename
, currentLogFilename
) != 0)
313 pfree(currentLogFilename
);
314 currentLogFilename
= pstrdup(Log_filename
);
315 rotation_requested
= true;
319 * If rotation time parameter changed, reset next rotation time,
320 * but don't immediately force a rotation.
322 if (currentLogRotationAge
!= Log_RotationAge
)
324 currentLogRotationAge
= Log_RotationAge
;
325 set_next_rotation_time();
329 if (!rotation_requested
&& Log_RotationAge
> 0)
331 /* Do a logfile rotation if it's time */
332 pg_time_t now
= (pg_time_t
) time(NULL
);
334 if (now
>= next_rotation_time
)
335 rotation_requested
= time_based_rotation
= true;
338 if (!rotation_requested
&& Log_RotationSize
> 0)
340 /* Do a rotation if file is too big */
341 if (ftell(syslogFile
) >= Log_RotationSize
* 1024L)
343 rotation_requested
= true;
344 size_rotation_for
|= LOG_DESTINATION_STDERR
;
346 if (csvlogFile
!= NULL
&&
347 ftell(csvlogFile
) >= Log_RotationSize
* 1024L)
349 rotation_requested
= true;
350 size_rotation_for
|= LOG_DESTINATION_CSVLOG
;
354 if (rotation_requested
)
357 * Force rotation when both values are zero. It means the request
358 * was sent by pg_rotate_logfile.
360 if (!time_based_rotation
&& size_rotation_for
== 0)
361 size_rotation_for
= LOG_DESTINATION_STDERR
| LOG_DESTINATION_CSVLOG
;
362 logfile_rotate(time_based_rotation
, size_rotation_for
);
368 * Wait for some data, timing out after 1 second
371 FD_SET(syslogPipe
[0], &rfds
);
375 rc
= select(syslogPipe
[0] + 1, &rfds
, NULL
, NULL
, &timeout
);
381 (errcode_for_socket_access(),
382 errmsg("select() failed in logger process: %m")));
384 else if (rc
> 0 && FD_ISSET(syslogPipe
[0], &rfds
))
386 bytesRead
= piperead(syslogPipe
[0],
387 logbuffer
+ bytes_in_logbuffer
,
388 sizeof(logbuffer
) - bytes_in_logbuffer
);
393 (errcode_for_socket_access(),
394 errmsg("could not read from logger pipe: %m")));
396 else if (bytesRead
> 0)
398 bytes_in_logbuffer
+= bytesRead
;
399 process_pipe_input(logbuffer
, &bytes_in_logbuffer
);
405 * Zero bytes read when select() is saying read-ready means
406 * EOF on the pipe: that is, there are no longer any processes
407 * with the pipe write end open. Therefore, the postmaster
408 * and all backends are shut down, and we are done.
410 pipe_eof_seen
= true;
412 /* if there's any data left then force it out now */
413 flush_pipe_input(logbuffer
, &bytes_in_logbuffer
);
419 * On Windows we leave it to a separate thread to transfer data and
420 * detect pipe EOF. The main thread just wakes up once a second to
421 * check for SIGHUP and rotation conditions.
429 * seeing this message on the real stderr is annoying - so we make
430 * it DEBUG1 to suppress in normal use.
433 (errmsg("logger shutting down")));
436 * Normal exit from the syslogger is here. Note that we
437 * deliberately do not close syslogFile before exiting; this is to
438 * allow for the possibility of elog messages being generated
439 * inside proc_exit. Regular exit() will take care of flushing
440 * and closing stdio channels.
448 * Postmaster subroutine to start a syslogger subprocess.
451 SysLogger_Start(void)
456 if (!Logging_collector
)
460 * If first time through, create the pipe which will receive stderr
463 * If the syslogger crashes and needs to be restarted, we continue to use
464 * the same pipe (indeed must do so, since extant backends will be writing
467 * This means the postmaster must continue to hold the read end of the
468 * pipe open, so we can pass it down to the reincarnated syslogger. This
469 * is a bit klugy but we have little choice.
472 if (syslogPipe
[0] < 0)
474 if (pgpipe(syslogPipe
) < 0)
476 (errcode_for_socket_access(),
477 (errmsg("could not create pipe for syslog: %m"))));
482 SECURITY_ATTRIBUTES sa
;
484 memset(&sa
, 0, sizeof(SECURITY_ATTRIBUTES
));
485 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
486 sa
.bInheritHandle
= TRUE
;
488 if (!CreatePipe(&syslogPipe
[0], &syslogPipe
[1], &sa
, 32768))
490 (errcode_for_file_access(),
491 (errmsg("could not create pipe for syslog: %m"))));
496 * Create log directory if not present; ignore errors
498 mkdir(Log_directory
, 0700);
501 * The initial logfile is created right in the postmaster, to verify that
502 * the Log_directory is writable.
504 filename
= logfile_getname(time(NULL
), NULL
);
506 syslogFile
= fopen(filename
, "a");
510 (errcode_for_file_access(),
511 (errmsg("could not create log file \"%s\": %m",
514 setvbuf(syslogFile
, NULL
, LBF_MODE
, 0);
519 switch ((sysloggerPid
= syslogger_forkexec()))
521 switch ((sysloggerPid
= fork_process()))
526 (errmsg("could not fork system logger: %m")));
531 /* in postmaster child ... */
532 /* Close the postmaster's sockets */
533 ClosePostmasterPorts(true);
535 /* Lose the postmaster's on-exit routines */
538 /* Drop our connection to postmaster's shared memory, as well */
539 PGSharedMemoryDetach();
542 SysLoggerMain(0, NULL
);
547 /* success, in postmaster */
549 /* now we redirect stderr, if not done already */
550 if (!redirection_done
)
554 if (dup2(syslogPipe
[1], fileno(stdout
)) < 0)
556 (errcode_for_file_access(),
557 errmsg("could not redirect stdout: %m")));
559 if (dup2(syslogPipe
[1], fileno(stderr
)) < 0)
561 (errcode_for_file_access(),
562 errmsg("could not redirect stderr: %m")));
563 /* Now we are done with the write end of the pipe. */
564 close(syslogPipe
[1]);
570 * open the pipe in binary mode and make sure stderr is binary
571 * after it's been dup'ed into, to avoid disturbing the pipe
575 fd
= _open_osfhandle((long) syslogPipe
[1],
576 _O_APPEND
| _O_BINARY
);
577 if (dup2(fd
, _fileno(stderr
)) < 0)
579 (errcode_for_file_access(),
580 errmsg("could not redirect stderr: %m")));
582 _setmode(_fileno(stderr
), _O_BINARY
);
583 /* Now we are done with the write end of the pipe. */
584 CloseHandle(syslogPipe
[1]);
587 redirection_done
= true;
590 /* postmaster will never write the file; close it */
593 return (int) sysloggerPid
;
596 /* we should never reach here */
604 * syslogger_forkexec() -
606 * Format up the arglist for, then fork and exec, a syslogger process
609 syslogger_forkexec(void)
615 av
[ac
++] = "postgres";
616 av
[ac
++] = "--forklog";
617 av
[ac
++] = NULL
; /* filled in by postmaster_forkexec */
619 /* static variables (those not passed by write_backend_variables) */
621 if (syslogFile
!= NULL
)
622 snprintf(filenobuf
, sizeof(filenobuf
), "%d",
625 strcpy(filenobuf
, "-1");
627 if (syslogFile
!= NULL
)
628 snprintf(filenobuf
, sizeof(filenobuf
), "%ld",
629 _get_osfhandle(_fileno(syslogFile
)));
631 strcpy(filenobuf
, "0");
633 av
[ac
++] = filenobuf
;
636 Assert(ac
< lengthof(av
));
638 return postmaster_forkexec(ac
, av
);
642 * syslogger_parseArgs() -
644 * Extract data from the arglist for exec'ed syslogger process
647 syslogger_parseArgs(int argc
, char *argv
[])
658 syslogFile
= fdopen(fd
, "a");
659 setvbuf(syslogFile
, NULL
, LBF_MODE
, 0);
665 fd
= _open_osfhandle(fd
, _O_APPEND
| _O_TEXT
);
668 syslogFile
= fdopen(fd
, "a");
669 setvbuf(syslogFile
, NULL
, LBF_MODE
, 0);
674 #endif /* EXEC_BACKEND */
677 /* --------------------------------
678 * pipe protocol handling
679 * --------------------------------
683 * Process data received through the syslogger pipe.
685 * This routine interprets the log pipe protocol which sends log messages as
686 * (hopefully atomic) chunks - such chunks are detected and reassembled here.
688 * The protocol has a header that starts with two nul bytes, then has a 16 bit
689 * length, the pid of the sending process, and a flag to indicate if it is
690 * the last chunk in a message. Incomplete chunks are saved until we read some
691 * more, and non-final chunks are accumulated until we get the final chunk.
693 * All of this is to avoid 2 problems:
694 * . partial messages being written to logfiles (messes rotation), and
695 * . messages from different backends being interleaved (messages garbled).
697 * Any non-protocol messages are written out directly. These should only come
698 * from non-PostgreSQL sources, however (e.g. third party libraries writing to
701 * logbuffer is the data input buffer, and *bytes_in_logbuffer is the number
702 * of bytes present. On exit, any not-yet-eaten data is left-justified in
703 * logbuffer, and *bytes_in_logbuffer is updated.
706 process_pipe_input(char *logbuffer
, int *bytes_in_logbuffer
)
708 char *cursor
= logbuffer
;
709 int count
= *bytes_in_logbuffer
;
710 int dest
= LOG_DESTINATION_STDERR
;
712 /* While we have enough for a header, process data... */
713 while (count
>= (int) sizeof(PipeProtoHeader
))
718 /* Do we have a valid header? */
719 memcpy(&p
, cursor
, sizeof(PipeProtoHeader
));
720 if (p
.nuls
[0] == '\0' && p
.nuls
[1] == '\0' &&
721 p
.len
> 0 && p
.len
<= PIPE_MAX_PAYLOAD
&&
723 (p
.is_last
== 't' || p
.is_last
== 'f' ||
724 p
.is_last
== 'T' || p
.is_last
== 'F'))
726 chunklen
= PIPE_HEADER_SIZE
+ p
.len
;
728 /* Fall out of loop if we don't have the whole chunk yet */
729 if (count
< chunklen
)
732 dest
= (p
.is_last
== 'T' || p
.is_last
== 'F') ?
733 LOG_DESTINATION_CSVLOG
: LOG_DESTINATION_STDERR
;
735 if (p
.is_last
== 'f' || p
.is_last
== 'F')
738 * Save a complete non-final chunk in the per-pid buffer if
739 * possible - if not just write it out.
746 for (i
= 0; i
< CHUNK_SLOTS
; i
++)
748 if (saved_chunks
[i
].pid
== p
.pid
)
753 if (free_slot
< 0 && saved_chunks
[i
].pid
== 0)
756 if (existing_slot
>= 0)
758 str
= &(saved_chunks
[existing_slot
].data
);
759 appendBinaryStringInfo(str
,
760 cursor
+ PIPE_HEADER_SIZE
,
763 else if (free_slot
>= 0)
765 saved_chunks
[free_slot
].pid
= p
.pid
;
766 str
= &(saved_chunks
[free_slot
].data
);
768 appendBinaryStringInfo(str
,
769 cursor
+ PIPE_HEADER_SIZE
,
775 * If there is no free slot we'll just have to take our
776 * chances and write out a partial message and hope that
777 * it's not followed by something from another pid.
779 write_syslogger_file(cursor
+ PIPE_HEADER_SIZE
, p
.len
,
786 * Final chunk --- add it to anything saved for that pid, and
787 * either way write the whole thing out.
789 int existing_slot
= -1;
793 for (i
= 0; i
< CHUNK_SLOTS
; i
++)
795 if (saved_chunks
[i
].pid
== p
.pid
)
801 if (existing_slot
>= 0)
803 str
= &(saved_chunks
[existing_slot
].data
);
804 appendBinaryStringInfo(str
,
805 cursor
+ PIPE_HEADER_SIZE
,
807 write_syslogger_file(str
->data
, str
->len
, dest
);
808 saved_chunks
[existing_slot
].pid
= 0;
813 /* The whole message was one chunk, evidently. */
814 write_syslogger_file(cursor
+ PIPE_HEADER_SIZE
, p
.len
,
819 /* Finished processing this chunk */
825 /* Process non-protocol data */
828 * Look for the start of a protocol header. If found, dump data
829 * up to there and repeat the loop. Otherwise, dump it all and
830 * fall out of the loop. (Note: we want to dump it all if at all
831 * possible, so as to avoid dividing non-protocol messages across
832 * logfiles. We expect that in many scenarios, a non-protocol
833 * message will arrive all in one read(), and we want to respect
834 * the read() boundary if possible.)
836 for (chunklen
= 1; chunklen
< count
; chunklen
++)
838 if (cursor
[chunklen
] == '\0')
841 /* fall back on the stderr log as the destination */
842 write_syslogger_file(cursor
, chunklen
, LOG_DESTINATION_STDERR
);
848 /* We don't have a full chunk, so left-align what remains in the buffer */
849 if (count
> 0 && cursor
!= logbuffer
)
850 memmove(logbuffer
, cursor
, count
);
851 *bytes_in_logbuffer
= count
;
855 * Force out any buffered data
857 * This is currently used only at syslogger shutdown, but could perhaps be
858 * useful at other times, so it is careful to leave things in a clean state.
861 flush_pipe_input(char *logbuffer
, int *bytes_in_logbuffer
)
866 /* Dump any incomplete protocol messages */
867 for (i
= 0; i
< CHUNK_SLOTS
; i
++)
869 if (saved_chunks
[i
].pid
!= 0)
871 str
= &(saved_chunks
[i
].data
);
872 write_syslogger_file(str
->data
, str
->len
, LOG_DESTINATION_STDERR
);
873 saved_chunks
[i
].pid
= 0;
879 * Force out any remaining pipe data as-is; we don't bother trying to
880 * remove any protocol headers that may exist in it.
882 if (*bytes_in_logbuffer
> 0)
883 write_syslogger_file(logbuffer
, *bytes_in_logbuffer
,
884 LOG_DESTINATION_STDERR
);
885 *bytes_in_logbuffer
= 0;
889 /* --------------------------------
891 * --------------------------------
895 * Write text to the currently open logfile
897 * This is exported so that elog.c can call it when am_syslogger is true.
898 * This allows the syslogger process to record elog messages of its own,
899 * even though its stderr does not point at the syslog pipe.
902 write_syslogger_file(const char *buffer
, int count
, int destination
)
907 if (destination
== LOG_DESTINATION_CSVLOG
&& csvlogFile
== NULL
)
911 EnterCriticalSection(&sysfileSection
);
914 logfile
= destination
== LOG_DESTINATION_CSVLOG
? csvlogFile
: syslogFile
;
915 rc
= fwrite(buffer
, 1, count
, logfile
);
918 LeaveCriticalSection(&sysfileSection
);
921 /* can't use ereport here because of possible recursion */
923 write_stderr("could not write to log file: %s\n", strerror(errno
));
929 * Worker thread to transfer data from the pipe to the current logfile.
931 * We need this because on Windows, WaitForSingleObject does not work on
932 * unnamed pipes: it always reports "signaled", so the blocking ReadFile won't
933 * allow for SIGHUP; and select is for sockets only.
935 static unsigned int __stdcall
936 pipeThread(void *arg
)
938 char logbuffer
[READ_BUF_SIZE
];
939 int bytes_in_logbuffer
= 0;
945 if (!ReadFile(syslogPipe
[0],
946 logbuffer
+ bytes_in_logbuffer
,
947 sizeof(logbuffer
) - bytes_in_logbuffer
,
950 DWORD error
= GetLastError();
952 if (error
== ERROR_HANDLE_EOF
||
953 error
== ERROR_BROKEN_PIPE
)
957 (errcode_for_file_access(),
958 errmsg("could not read from logger pipe: %m")));
960 else if (bytesRead
> 0)
962 bytes_in_logbuffer
+= bytesRead
;
963 process_pipe_input(logbuffer
, &bytes_in_logbuffer
);
967 /* We exit the above loop only upon detecting pipe EOF */
968 pipe_eof_seen
= true;
970 /* if there's any data left then force it out now */
971 flush_pipe_input(logbuffer
, &bytes_in_logbuffer
);
979 * open the csv log file - we do this opportunistically, because
980 * we don't know if CSV logging will be wanted.
983 open_csvlogfile(void)
988 filename
= logfile_getname(time(NULL
), ".csv");
990 fh
= fopen(filename
, "a");
994 (errcode_for_file_access(),
995 (errmsg("could not create log file \"%s\": %m",
998 setvbuf(fh
, NULL
, LBF_MODE
, 0);
1001 _setmode(_fileno(fh
), _O_TEXT
); /* use CRLF line endings on Windows */
1011 * perform logfile rotation
1014 logfile_rotate(bool time_based_rotation
, int size_rotation_for
)
1017 char *csvfilename
= NULL
;
1020 rotation_requested
= false;
1023 * When doing a time-based rotation, invent the new logfile name based on
1024 * the planned rotation time, not current time, to avoid "slippage" in the
1025 * file name when we don't do the rotation immediately.
1027 if (time_based_rotation
)
1029 filename
= logfile_getname(next_rotation_time
, NULL
);
1030 if (csvlogFile
!= NULL
)
1031 csvfilename
= logfile_getname(next_rotation_time
, ".csv");
1035 filename
= logfile_getname(time(NULL
), NULL
);
1036 if (csvlogFile
!= NULL
)
1037 csvfilename
= logfile_getname(time(NULL
), ".csv");
1041 * Decide whether to overwrite or append. We can overwrite if (a)
1042 * Log_truncate_on_rotation is set, (b) the rotation was triggered by
1043 * elapsed time and not something else, and (c) the computed file name is
1044 * different from what we were previously logging into.
1046 * Note: during the first rotation after forking off from the postmaster,
1047 * last_file_name will be NULL. (We don't bother to set it in the
1048 * postmaster because it ain't gonna work in the EXEC_BACKEND case.) So we
1049 * will always append in that situation, even though truncating would
1052 * For consistency, we treat CSV logs the same even though they aren't
1053 * opened in the postmaster.
1055 if (time_based_rotation
|| (size_rotation_for
& LOG_DESTINATION_STDERR
))
1057 if (Log_truncate_on_rotation
&& time_based_rotation
&&
1058 last_file_name
!= NULL
&&
1059 strcmp(filename
, last_file_name
) != 0)
1060 fh
= fopen(filename
, "w");
1062 fh
= fopen(filename
, "a");
1066 int saveerrno
= errno
;
1069 (errcode_for_file_access(),
1070 errmsg("could not open new log file \"%s\": %m",
1074 * ENFILE/EMFILE are not too surprising on a busy system; just
1075 * keep using the old file till we manage to get a new one.
1076 * Otherwise, assume something's wrong with Log_directory and stop
1077 * trying to create files.
1079 if (saveerrno
!= ENFILE
&& saveerrno
!= EMFILE
)
1082 (errmsg("disabling automatic rotation (use SIGHUP to reenable)")));
1083 Log_RotationAge
= 0;
1084 Log_RotationSize
= 0;
1092 setvbuf(fh
, NULL
, LBF_MODE
, 0);
1095 _setmode(_fileno(fh
), _O_TEXT
); /* use CRLF line endings on Windows */
1098 /* On Windows, need to interlock against data-transfer thread */
1100 EnterCriticalSection(&sysfileSection
);
1105 LeaveCriticalSection(&sysfileSection
);
1108 /* instead of pfree'ing filename, remember it for next time */
1109 if (last_file_name
!= NULL
)
1110 pfree(last_file_name
);
1111 last_file_name
= filename
;
1114 /* Same as above, but for csv file. */
1116 if (csvlogFile
!= NULL
&&
1117 (time_based_rotation
|| (size_rotation_for
& LOG_DESTINATION_CSVLOG
)))
1119 if (Log_truncate_on_rotation
&& time_based_rotation
&&
1120 last_csv_file_name
!= NULL
&&
1121 strcmp(csvfilename
, last_csv_file_name
) != 0)
1122 fh
= fopen(csvfilename
, "w");
1124 fh
= fopen(csvfilename
, "a");
1128 int saveerrno
= errno
;
1131 (errcode_for_file_access(),
1132 errmsg("could not open new log file \"%s\": %m",
1136 * ENFILE/EMFILE are not too surprising on a busy system; just
1137 * keep using the old file till we manage to get a new one.
1138 * Otherwise, assume something's wrong with Log_directory and stop
1139 * trying to create files.
1141 if (saveerrno
!= ENFILE
&& saveerrno
!= EMFILE
)
1144 (errmsg("disabling automatic rotation (use SIGHUP to reenable)")));
1145 Log_RotationAge
= 0;
1146 Log_RotationSize
= 0;
1152 setvbuf(fh
, NULL
, LBF_MODE
, 0);
1155 _setmode(_fileno(fh
), _O_TEXT
); /* use CRLF line endings on Windows */
1158 /* On Windows, need to interlock against data-transfer thread */
1160 EnterCriticalSection(&sysfileSection
);
1165 LeaveCriticalSection(&sysfileSection
);
1168 /* instead of pfree'ing filename, remember it for next time */
1169 if (last_csv_file_name
!= NULL
)
1170 pfree(last_csv_file_name
);
1171 last_csv_file_name
= csvfilename
;
1174 set_next_rotation_time();
1179 * construct logfile name using timestamp information
1181 * Result is palloc'd.
1184 logfile_getname(pg_time_t timestamp
, char *suffix
)
1189 filename
= palloc(MAXPGPATH
);
1191 snprintf(filename
, MAXPGPATH
, "%s/", Log_directory
);
1193 len
= strlen(filename
);
1195 /* treat it as a strftime pattern */
1196 pg_strftime(filename
+ len
, MAXPGPATH
- len
, Log_filename
,
1197 pg_localtime(×tamp
, log_timezone
));
1201 len
= strlen(filename
);
1202 if (len
> 4 && (strcmp(filename
+ (len
- 4), ".log") == 0))
1204 strncpy(filename
+ len
, suffix
, MAXPGPATH
- len
);
1211 * Determine the next planned rotation time, and store in next_rotation_time.
1214 set_next_rotation_time(void)
1220 /* nothing to do if time-based rotation is disabled */
1221 if (Log_RotationAge
<= 0)
1225 * The requirements here are to choose the next time > now that is a
1226 * "multiple" of the log rotation interval. "Multiple" can be interpreted
1227 * fairly loosely. In this version we align to log_timezone rather than
1230 rotinterval
= Log_RotationAge
* SECS_PER_MINUTE
; /* convert to seconds */
1231 now
= (pg_time_t
) time(NULL
);
1232 tm
= pg_localtime(&now
, log_timezone
);
1233 now
+= tm
->tm_gmtoff
;
1234 now
-= now
% rotinterval
;
1236 now
-= tm
->tm_gmtoff
;
1237 next_rotation_time
= now
;
1240 /* --------------------------------
1241 * signal handler routines
1242 * --------------------------------
1245 /* SIGHUP: set flag to reload config file */
1247 sigHupHandler(SIGNAL_ARGS
)
1252 /* SIGUSR1: set flag to rotate logfile */
1254 sigUsr1Handler(SIGNAL_ARGS
)
1256 rotation_requested
= true;