aboutsummaryrefslogtreecommitdiff
path: root/src/zencore/logging/msvcsink.cpp
blob: 457a4d6e1a0079d849454249aa83e13f88c5b0e7 (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
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zencore/zencore.h>

#if ZEN_PLATFORM_WINDOWS

#	include <zencore/logging/helpers.h>
#	include <zencore/logging/messageonlyformatter.h>
#	include <zencore/logging/msvcsink.h>

ZEN_THIRD_PARTY_INCLUDES_START
#	include <Windows.h>
ZEN_THIRD_PARTY_INCLUDES_END

namespace zen::logging {

// Default formatter for MSVC debug output: [level] message\n
// For error/critical messages with source info, prepends file(line): so that
// the message is clickable in the Visual Studio Output window.
class DefaultMsvcFormatter : public Formatter
{
public:
	void Format(const LogMessage& Msg, MemoryBuffer& Dest) override
	{
		const auto& Source = Msg.GetSource();
		if (Msg.GetLevel() >= LogLevel::Err && Source)
		{
			helpers::AppendStringView(Source.Filename, Dest);
			Dest.push_back('(');
			helpers::AppendInt(Source.Line, Dest);
			Dest.push_back(')');
			Dest.push_back(':');
			Dest.push_back(' ');
		}

		Dest.push_back('[');
		helpers::AppendStringView(helpers::LevelToShortString(Msg.GetLevel()), Dest);
		Dest.push_back(']');
		Dest.push_back(' ');
		helpers::AppendStringView(Msg.GetPayload(), Dest);
		Dest.push_back('\n');
	}

	std::unique_ptr<Formatter> Clone() const override { return std::make_unique<DefaultMsvcFormatter>(); }
};

MsvcSink::MsvcSink() : m_Formatter(std::make_unique<DefaultMsvcFormatter>())
{
}

void
MsvcSink::Log(const LogMessage& Msg)
{
	std::lock_guard<std::mutex> Lock(m_Mutex);

	MemoryBuffer Formatted;
	m_Formatter->Format(Msg, Formatted);

	// Null-terminate for OutputDebugStringA
	Formatted.push_back('\0');

	OutputDebugStringA(Formatted.data());
}

void
MsvcSink::Flush()
{
	// Nothing to flush for OutputDebugString
}

void
MsvcSink::SetFormatter(std::unique_ptr<Formatter> InFormatter)
{
	std::lock_guard<std::mutex> Lock(m_Mutex);
	m_Formatter = std::move(InFormatter);
}

}  // namespace zen::logging

#endif	// ZEN_PLATFORM_WINDOWS