summaryrefslogtreecommitdiff
path: root/lib/log.c
blob: a46afff4cd8a8f7eb0721b0ff72e5578ce707045 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
 * dpkg - main program for package management
 * log.c - logging related functions
 *
 * Copyright (C) 2005 Scott James Remnant <scott@netsplit.com>
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with dpkg; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <config.h>

#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>

#include <dpkg.h>
#include <dpkg-db.h>

const char *log_file = NULL;

void
log_message(const char *fmt, ...)
{
	static struct varbuf log;
	static FILE *logfd = NULL;
	char time_str[20];
	time_t now;
	va_list al;

	if (!log_file)
		return;

	if (!logfd) {
		logfd = fopen(log_file, "a");
		if (!logfd) {
			fprintf(stderr, _("couldn't open log `%s': %s\n"),
			        log_file, strerror(errno));
			log_file = NULL;
			return;
		}
		setlinebuf(logfd);
		setcloexec(fileno(logfd), log_file);
	}

	va_start(al, fmt);
	varbufreset(&log);
	varbufvprintf(&log, fmt, al);
	varbufaddc(&log, 0);
	va_end(al);

	time(&now);
	strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S",
	         localtime(&now));
	fprintf(logfd, "%s %s\n", time_str, log.buf);
}

struct pipef *status_pipes = NULL;

void
statusfd_send(const char *fmt, ...)
{
	static struct varbuf vb;
	struct pipef *pipef;
	const char *p;
	int r, l;
	va_list al;

	if (!status_pipes)
		return;

	va_start(al, fmt);
	varbufreset(&vb);
	varbufvprintf(&vb, fmt, al);
	varbufaddc(&vb, '\n');
	va_end(al);

	for (pipef = status_pipes; pipef; pipef = pipef->next) {
		for (p = vb.buf, l = vb.used; l;  p += r, l -= r) {
			r = write(pipef->fd, vb.buf, vb.used);
			if (r < 0)
				ohshite("unable to write to status fd %d",
				        pipef->fd);
			assert(r && r <= l);
		}
	}
}