virsh: use new method for easier log to file

Easier to maintain, and no longer an arbitrary line length limit.

* tools/virsh.c (vshOutputLogFile): Replace snprintf with
virBuffer.
This commit is contained in:
Eric Blake 2011-04-30 11:05:43 -06:00
parent f09acccfd7
commit f99e1389cc
1 changed files with 32 additions and 24 deletions

View File

@ -12231,7 +12231,9 @@ static void
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format, vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
va_list ap) va_list ap)
{ {
char *msg_buf; virBuffer buf = VIR_BUFFER_INITIALIZER;
char *str;
size_t len;
const char *lvl = ""; const char *lvl = "";
struct timeval stTimeval; struct timeval stTimeval;
struct tm *stTm; struct tm *stTm;
@ -12239,8 +12241,6 @@ vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
if (ctl->log_fd == -1) if (ctl->log_fd == -1)
return; return;
msg_buf = vshMalloc(ctl, MSG_BUFFER);
/** /**
* create log format * create log format
* *
@ -12248,16 +12248,14 @@ vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
*/ */
gettimeofday(&stTimeval, NULL); gettimeofday(&stTimeval, NULL);
stTm = localtime(&stTimeval.tv_sec); stTm = localtime(&stTimeval.tv_sec);
snprintf(msg_buf, MSG_BUFFER, virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s] ",
"[%d.%02d.%02d %02d:%02d:%02d ", (1900 + stTm->tm_year),
(1900 + stTm->tm_year), (1 + stTm->tm_mon),
(1 + stTm->tm_mon), stTm->tm_mday,
(stTm->tm_mday), stTm->tm_hour,
(stTm->tm_hour), stTm->tm_min,
(stTm->tm_min), stTm->tm_sec,
(stTm->tm_sec)); SIGN_NAME);
snprintf(msg_buf + strlen(msg_buf), MSG_BUFFER - strlen(msg_buf),
"%s] ", SIGN_NAME);
switch (log_level) { switch (log_level) {
case VSH_ERR_DEBUG: case VSH_ERR_DEBUG:
lvl = LVL_DEBUG; lvl = LVL_DEBUG;
@ -12278,21 +12276,31 @@ vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
lvl = LVL_DEBUG; lvl = LVL_DEBUG;
break; break;
} }
snprintf(msg_buf + strlen(msg_buf), MSG_BUFFER - strlen(msg_buf), virBufferAsprintf(&buf, "%s ", lvl);
"%s ", lvl); virBufferVasprintf(&buf, msg_format, ap);
vsnprintf(msg_buf + strlen(msg_buf), MSG_BUFFER - strlen(msg_buf), virBufferAddChar(&buf, '\n');
msg_format, ap);
if (msg_buf[strlen(msg_buf) - 1] != '\n') if (virBufferError(&buf))
snprintf(msg_buf + strlen(msg_buf), MSG_BUFFER - strlen(msg_buf), "\n"); goto error;
/* write log */ str = virBufferContentAndReset(&buf);
if (safewrite(ctl->log_fd, msg_buf, strlen(msg_buf)) < 0) { len = strlen(str);
vshCloseLogFile(ctl); if (len > 1 && str[len - 2] == '\n') {
vshError(ctl, "%s", _("failed to write the log file")); str[len - 1] = '\0';
len--;
} }
VIR_FREE(msg_buf); /* write log */
if (safewrite(ctl->log_fd, str, len) < 0)
goto error;
return;
error:
vshCloseLogFile(ctl);
vshError(ctl, "%s", _("failed to write the log file"));
virBufferFreeAndReset(&buf);
VIR_FREE(str);
} }
/** /**