From f6d02b85d83f1718ab2decc6ad6393a53d1812b1 Mon Sep 17 00:00:00 2001 From: Ian Barwick Date: Tue, 15 Sep 2015 13:37:40 +0900 Subject: [PATCH] Better handling of situation where logfile can't be opened If freopen() fails, stderr is diverted to an undisclosed location and it's not clear what is going on. Also add an explicit notice announcing our intention to divert logging output to a file. Per #105. Note that it might make sense to disable logfile output when running the repmgr command line client as normally you'd expect immediate feedback. --- log.c | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/log.c b/log.c index f753328a..7d738b94 100644 --- a/log.c +++ b/log.c @@ -144,12 +144,32 @@ logger_init(t_configuration_options * opts, const char *ident, const char *level { FILE *fd; - fd = freopen(opts->logfile, "a", stderr); + /* Check if we can write to the specified file before redirecting + * stderr - if freopen() fails, stderr output will vanish into + * the ether and the user won't know what's going on. + */ + fd = fopen(opts->logfile, "a"); if (fd == NULL) { - fprintf(stderr, "error reopening stderr to '%s': %s", - opts->logfile, strerror(errno)); + stderr_log_err(_("Unable to open specified logfile '%s' for writing: %s\n"), opts->logfile, strerror(errno)); + stderr_log_err(_("Terminating\n")); + exit(ERR_BAD_CONFIG); + } + fclose(fd); + + stderr_log_notice(_("Redirecting logging output to '%s'\n"), opts->logfile); + fd = freopen(opts->logfile, "a", stderr); + + /* It's possible freopen() may still fail due to e.g. a race condition; + as it's not feasible to restore stderr after a failed freopen(), + we'll write to stdout as a last resort. + */ + if (fd == NULL) + { + printf(_("Unable to open specified logfile %s for writing: %s\n"), opts->logfile, strerror(errno)); + printf(_("Terminating\n")); + exit(ERR_BAD_CONFIG); } }