PageRenderTime 68ms CodeModel.GetById 48ms app.highlight 13ms RepoModel.GetById 2ms app.codeStats 0ms

/slog.c

http://github.com/nicolasff/webdis
C | 80 lines | 51 code | 18 blank | 11 comment | 7 complexity | cb0b6954232eb4cf8824f761a379a795 MD5 | raw file
 1#include <stdio.h>
 2#include <stdlib.h>
 3#include <stdarg.h>
 4#include <time.h>
 5#include <sys/types.h>
 6#include <unistd.h>
 7#include <string.h>
 8#include <sys/stat.h>
 9#include <fcntl.h>
10#include <errno.h>
11
12#include "slog.h"
13#include "server.h"
14#include "conf.h"
15
16/**
17 * Initialize log writer.
18 */
19void
20slog_init(struct server *s) {
21
22	s->log.self = getpid();
23
24	if(s->cfg->logfile) {
25
26		int old_fd = s->log.fd;
27
28		s->log.fd = open(s->cfg->logfile,
29			O_WRONLY | O_APPEND | O_CREAT, S_IRUSR|S_IWUSR);
30
31		/* close old log */
32		if (old_fd != -1) {
33			close(old_fd);
34		}
35
36		if (s->log.fd != -1)
37			return;
38
39		fprintf(stderr, "Could not open %s: %s\n", s->cfg->logfile,
40				strerror(errno));
41	}
42	s->log.fd = 2; /* stderr */
43}
44
45/**
46 * Write log message to disk, or stderr.
47 */
48void
49slog(struct server *s, log_level level,
50		const char *body, size_t sz) {
51
52	const char *c = ".-*#";
53	time_t now;
54	char time_buf[64];
55	char msg[124];
56	char line[256]; /* bounds are checked. */
57	int line_sz, ret;
58
59	if(level > s->cfg->verbosity) return; /* too verbose */
60
61	if(!s->log.fd) return;
62
63	/* limit message size */
64	sz = sz ? sz:strlen(body);
65	snprintf(msg, sz + 1 > sizeof(msg) ? sizeof(msg) : sz + 1, "%s", body);
66
67	/* get current time */
68	now = time(NULL);
69	strftime(time_buf, sizeof(time_buf), "%d %b %H:%M:%S", localtime(&now));
70
71	/* generate output line. */
72	line_sz = snprintf(line, sizeof(line),
73		"[%d] %s %d %s\n", (int)s->log.self, time_buf, c[level], msg);
74
75	/* write to log and flush to disk. */
76	ret = write(s->log.fd, line, line_sz);
77	ret = fsync(s->log.fd);
78
79	(void)ret;
80}