xref: /plan9/sys/src/libc/9sys/syslog.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 
4 static int
5 _syslogopen(char *logname, int logfd)
6 {
7 	char buf[1024];
8 
9 	if(logfd >= 0)
10 		close(logfd);
11 	snprint(buf, sizeof(buf), "/sys/log/%s", logname);
12 	return open(buf, OWRITE);
13 }
14 
15 /*
16  * Print
17  *  sysname: time: mesg
18  * on /sys/log/logname.
19  * If cons or log file can't be opened, print on the system console, too.
20  */
21 void
22 syslog(int cons, char *logname, char *fmt, ...)
23 {
24 	char buf[1024];
25 	char *ctim, *p, *ebuf, *t;
26 	int f, n;
27 	static char name[NAMELEN];
28 	static char sysname[NAMELEN];
29 	static int logfd = -1;
30 	static int consfd = -1;
31 
32 	if(logfd<0 || strcmp(name, logname)!=0){
33 		strncpy(name, logname, NAMELEN-1);
34 		logfd = _syslogopen(logname, logfd);
35 		if(logfd < 0)
36 			cons = 1;
37 	}
38 	if(cons && consfd<0)
39 		consfd = open("#c/cons", OWRITE);
40 	if(sysname[0] == 0){
41 		strcpy(sysname, "gnot");
42 		f = open("/env/sysname", OREAD);
43 		if(f >= 0){
44 			read(f, sysname, NAMELEN-1);
45 			close(f);
46 		}
47 	}
48 	ctim = ctime(time(0));
49 	ebuf = buf+sizeof(buf)-1; /* leave room for newline */
50 	t = sysname;
51 	p = doprint(buf, ebuf, "%s ", &t);
52 	strncpy(p, ctim+4, 12);
53 	p += 12;
54 	*p++ = ' ';
55 	p = doprint(p, ebuf, fmt, (&fmt+1));
56 	*p++ = '\n';
57 	n = p - buf;
58 	if(logfd >= 0){
59 		if(seek(logfd, 0, 2) < 0 || write(logfd, buf, n) < 0){
60 			logfd = _syslogopen(logname, logfd);
61 			if(logfd >= 0){
62 				seek(logfd, 0, 2);
63 				write(logfd, buf, n);
64 			}
65 		}
66 	}
67 	if(cons && consfd >=0)
68 		write(consfd, buf, n);
69 }
70