Fix log writer

This commit is contained in:
topjohnwu 2021-09-19 13:41:45 -07:00
parent 46e8f0779f
commit 0ab31ab0df

View File

@ -38,7 +38,7 @@ void setup_logfile(bool reset) {
#define MAX_MSG_LEN (PIPE_BUF - sizeof(log_meta)) #define MAX_MSG_LEN (PIPE_BUF - sizeof(log_meta))
static void logfile_writer(int pipefd) { static void logfile_writer(int pipefd) {
run_finally close_socket([=] { run_finally close_pipes([=] {
// Close up all logging pipes when thread dies // Close up all logging pipes when thread dies
close(pipefd); close(pipefd);
close(logd_fd.exchange(-1)); close(logd_fd.exchange(-1));
@ -47,8 +47,9 @@ static void logfile_writer(int pipefd) {
struct { struct {
void *data; void *data;
size_t len; size_t len;
} tmp_buf{}; } tmp{};
stream *strm = new byte_stream(tmp_buf.data, tmp_buf.len); stream_ptr strm = make_unique<byte_stream>(tmp.data, tmp.len);
bool switched = false;
log_meta meta{}; log_meta meta{};
char buf[MAX_MSG_LEN]; char buf[MAX_MSG_LEN];
@ -60,32 +61,32 @@ static void logfile_writer(int pipefd) {
for (;;) { for (;;) {
// Read meta data // Read meta data
if (xread(pipefd, &meta, sizeof(meta)) != sizeof(meta)) if (read(pipefd, &meta, sizeof(meta)) != sizeof(meta))
return; return;
if (meta.prio < 0 && tmp_buf.len >= 0) { if (meta.prio < 0) {
run_finally free_buf([&] { if (!switched) {
free(tmp_buf.data); run_finally free_tmp([&] {
tmp_buf.data = nullptr; free(tmp.data);
tmp_buf.len = -1; tmp.data = nullptr;
tmp.len = 0;
}); });
if (meta.len)
rename(LOGFILE, LOGFILE ".bak"); rename(LOGFILE, LOGFILE ".bak");
int fd = open(LOGFILE, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644); int fd = open(LOGFILE, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0644);
if (fd < 0) if (fd < 0)
return; return;
if (tmp_buf.data) if (tmp.data)
write(fd, tmp_buf.data, tmp_buf.len); write(fd, tmp.data, tmp.len);
delete strm; strm = make_unique<fd_stream>(fd);
strm = new fd_stream(fd); switched = true;
}
continue; continue;
} }
// Read message // Read message
if (xread(pipefd, buf, meta.len) != meta.len) if (read(pipefd, buf, meta.len) != meta.len)
return; return;
timeval tv; timeval tv;
@ -109,10 +110,10 @@ static void logfile_writer(int pipefd) {
type = 'E'; type = 'E';
break; break;
} }
int ms = tv.tv_usec / 1000; long ms = tv.tv_usec / 1000;
size_t off = strftime(aux, sizeof(aux), "%m-%d %T", &tm); size_t off = strftime(aux, sizeof(aux), "%m-%d %T", &tm);
off += snprintf(aux + off, sizeof(aux) - off, off += snprintf(aux + off, sizeof(aux) - off,
".%03d %5d %5d %c : ", ms, meta.pid, meta.tid, type); ".%03ld %5d %5d %c : ", ms, meta.pid, meta.tid, type);
iov[0].iov_len = off; iov[0].iov_len = off;
iov[1].iov_len = meta.len; iov[1].iov_len = meta.len;