aboutsummaryrefslogtreecommitdiff
path: root/src/system-stats/logger.cpp
blob: 319e1841adc44f0f46a8d02c4e5f1cae6ceb5ffd (plain) (blame)
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
#include <iostream>
#include "common.h"
#include "date.h"

namespace fs = std::filesystem;

const std::string LogFile::date()
{
	namespace C = std::chrono;
	namespace D = date;

	std::ostringstream str;
	auto tp = C::system_clock::now();
	auto dp = D::floor<D::days>(tp);
	auto yd = D::year_month_day {dp};
	auto tm = D::make_time(
	              C::duration_cast<C::milliseconds>(tp - dp));

	str << yd.year() << "-"
	    << static_cast<unsigned>(yd.month()) << "-"
	    << yd.day() << "_"
	    << tm.hours().count();
	return str.str();
}

void demo_perms(std::filesystem::perms p)
{
	using std::filesystem::perms;
	auto show = [=](char op, perms perm) {
		std::cerr << (perms::none == (perm & p) ? '-' : op);
	};
	show('r', perms::owner_read);
	show('w', perms::owner_write);
	show('x', perms::owner_exec);
	show('r', perms::group_read);
	show('w', perms::group_write);
	show('x', perms::group_exec);
	show('r', perms::others_read);
	show('w', perms::others_write);
	show('x', perms::others_exec);
	std::cerr << '\n';
}

LogFile::LogFile()
{
	base = fs::path("/var/log/" APP_NAME);
	try {
		if(fs::exists(base))
			if(not fs::is_directory(base))
				fs::remove(base);

		if(not fs::exists(base))
			fs::create_directories(base);

		if(fs::create_directory(base / ".test"))
			fs::remove(base / ".test");
	} catch (const std::exception& e) {
		std::cerr << e.what() << std::endl;
		stdout = true;
	}
}

void LogFile::change(refstream& fstr)
{
	if(stdout)
		return;

	if(not (std::addressof(fstr.get()) == std::addressof(stream)))
		fstr = std::ref(stream);

	std::string now = date();

	if(not (date_ == now)) {
		if(stream.is_open())
			stream.close();
		date_ = now;
	}

	if(not stream.is_open())
		stream.open(base / (date_ + ".log"), std::ios::app);
}