summaryrefslogtreecommitdiffstats
path: root/lib/base/filelogger.cpp
blob: c3da84a370098b90d1e7e56e6ea271bef1e85be0 (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
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "base/filelogger.hpp"
#include "base/filelogger-ti.cpp"
#include "base/configtype.hpp"
#include "base/statsfunction.hpp"
#include "base/application.hpp"
#include <fstream>

using namespace icinga;

REGISTER_TYPE(FileLogger);

REGISTER_STATSFUNCTION(FileLogger, &FileLogger::StatsFunc);

void FileLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
	DictionaryData nodes;

	for (const FileLogger::Ptr& filelogger : ConfigType::GetObjectsByType<FileLogger>()) {
		nodes.emplace_back(filelogger->GetName(), 1); //add more stats
	}

	status->Set("filelogger", new Dictionary(std::move(nodes)));
}

/**
 * Constructor for the FileLogger class.
 */
void FileLogger::Start(bool runtimeCreated)
{
	ReopenLogFile();

	Application::OnReopenLogs.connect([this]() { ReopenLogFile(); });

	ObjectImpl<FileLogger>::Start(runtimeCreated);

	Log(LogInformation, "FileLogger")
		<< "'" << GetName() << "' started.";
}

void FileLogger::ReopenLogFile()
{
	auto *stream = new std::ofstream();

	String path = GetPath();

	try {
		stream->open(path.CStr(), std::fstream::app | std::fstream::out);

		if (!stream->good())
			BOOST_THROW_EXCEPTION(std::runtime_error("Could not open logfile '" + path + "'"));
	} catch (...) {
		delete stream;
		throw;
	}

	BindStream(stream, true);
}