aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/logging/logger.cpp
blob: 619de430766aafb1fb4b97e9da8cb181b3abbed6 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/logging/logger.h>

namespace zen::logging {

Logger::Logger(std::string InName, SinkPtr InSink) : m_Name(std::move(InName))
{
	m_Sinks.push_back(std::move(InSink));
}

Logger::Logger(std::string InName, std::vector<SinkPtr> InSinks) : m_Name(std::move(InName)), m_Sinks(std::move(InSinks))
{
}

void
Logger::Log(LogLevel InLevel, std::string_view Msg)
{
	if (!ShouldLog(InLevel))
	{
		return;
	}

	LogMessage LogMsg(m_Name, InLevel, Msg);
	SinkIt(LogMsg);
	FlushIfNeeded(InLevel);
}

void
Logger::Log(const SourceLocation& Loc, LogLevel InLevel, std::string_view Msg)
{
	if (!ShouldLog(InLevel))
	{
		return;
	}

	LogMessage LogMsg(Loc, m_Name, InLevel, Msg);
	SinkIt(LogMsg);
	FlushIfNeeded(InLevel);
}

void
Logger::SinkIt(const LogMessage& Msg)
{
	for (auto& CurrentSink : m_Sinks)
	{
		if (CurrentSink->ShouldLog(Msg.Level))
		{
			try
			{
				CurrentSink->Log(Msg);
			}
			catch (const std::exception&)
			{
				// Silently eat errors in sinks
			}
		}
	}
}

void
Logger::FlushIfNeeded(LogLevel InLevel)
{
	if (InLevel >= m_FlushLevel.load(std::memory_order_relaxed))
	{
		Flush();
	}
}

void
Logger::Flush()
{
	for (auto& CurrentSink : m_Sinks)
	{
		try
		{
			CurrentSink->Flush();
		}
		catch (const std::exception&)
		{
		}
	}
}

void
Logger::SetFormatter(std::unique_ptr<Formatter> InFormatter)
{
	for (auto& CurrentSink : m_Sinks)
	{
		CurrentSink->SetFormatter(InFormatter->Clone());
	}
}

std::shared_ptr<Logger>
Logger::Clone(std::string NewName) const
{
	auto Cloned = std::make_shared<Logger>(std::move(NewName), m_Sinks);
	Cloned->SetLevel(m_Level.load(std::memory_order_relaxed));
	Cloned->SetFlushLevel(m_FlushLevel.load(std::memory_order_relaxed));
	return Cloned;
}

}  // namespace zen::logging