summaryrefslogtreecommitdiffstats
path: root/log.vala
blob: b0ddf0a7ff3010c19bdeb362256bb4e54333440f (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
namespace Log {
	private unowned FileStream file;
	private FileStream fileowner;
	private long start_timestamp;

	public void init() {
		TimeVal time = {0};
		time.get_current_time();

		try {
			set_file(cfg.get_string("config", "logfile"));
		} catch(Error e) {
			error("Please specify logfile in config.");
		}

		GLib.Log.set_default_handler(log_handler);
		start_timestamp = time.tv_sec;
	}

	private void log_handler(string? domain, LogLevelFlags flags, string message) {
		TimeVal time = {0};
		time.get_current_time();
		string s = "%.10ld | %15s | %s\n".printf(time.tv_sec - start_timestamp, domain, message);

		if(file != null) {
			file.printf(s);
			file.flush();
		}
	}

	public bool set_file(string filename) {
		switch(filename) {
			case "stdout":
				file = stdout;
				break;
			case "stderr":
				file = stderr;
				break;
			default:
				fileowner = FileStream.open(filename, "a");
				file = fileowner;
				break;
		}

		if(file == null)
			return false;
		return true;
	}
}