aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/logging/jsonformatter.cpp
blob: 673a03c947f7bc0a176e48b4737474f904f1a75c (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright Epic Games, Inc. All Rights Reserved.

#include <zenutil/logging/jsonformatter.h>

#include <zencore/logging/helpers.h>
#include <zencore/memory/llm.h>
#include <zencore/thread.h>
#include <zencore/zencore.h>

#include <chrono>
#include <string>
#include <unordered_map>

namespace zen::logging {

using namespace std::literals;

static void
WriteEscapedString(MemoryBuffer& Dest, std::string_view Text)
{
	// Strip ANSI SGR sequences before escaping so they don't appear in JSON output
	static const auto IsEscapeStart = [](char C) { return C == '\033'; };

	const char* RangeStart = Text.data();
	const char* End		   = Text.data() + Text.size();

	static const std::unordered_map<char, std::string_view> SpecialCharacterMap{
		{'\b', "\\b"sv},
		{'\f', "\\f"sv},
		{'\n', "\\n"sv},
		{'\r', "\\r"sv},
		{'\t', "\\t"sv},
		{'"', "\\\""sv},
		{'\\', "\\\\"sv},
	};

	for (const char* It = RangeStart; It != End; ++It)
	{
		// Skip ANSI SGR escape sequences (\033[...m)
		if (*It == '\033' && (It + 1) < End && *(It + 1) == '[')
		{
			if (RangeStart != It)
			{
				Dest.append(RangeStart, It);
			}
			const char* Seq = It + 2;
			while (Seq < End && *Seq != 'm')
			{
				++Seq;
			}
			if (Seq < End)
			{
				++Seq;	// skip 'm'
			}
			It		   = Seq - 1;  // -1 because the for loop will ++It
			RangeStart = Seq;
			continue;
		}

		if (auto SpecialIt = SpecialCharacterMap.find(*It); SpecialIt != SpecialCharacterMap.end())
		{
			if (RangeStart != It)
			{
				Dest.append(RangeStart, It);
			}
			helpers::AppendStringView(SpecialIt->second, Dest);
			RangeStart = It + 1;
		}
	}
	if (RangeStart != End)
	{
		Dest.append(RangeStart, End);
	}
}

struct JsonFormatter::Impl
{
	explicit Impl(std::string_view LogId) : m_LogId(LogId) {}

	std::tm				 m_CachedTm{0, 0, 0, 0, 0, 0, 0, 0, 0};
	std::chrono::seconds m_LastLogSecs{0};
	MemoryBuffer		 m_CachedDatetime;
	std::string			 m_LogId;
	RwLock				 m_TimestampLock;
};

JsonFormatter::JsonFormatter(std::string_view LogId) : m_Impl(std::make_unique<Impl>(LogId))
{
}

JsonFormatter::~JsonFormatter() = default;

std::unique_ptr<Formatter>
JsonFormatter::Clone() const
{
	return std::make_unique<JsonFormatter>(m_Impl->m_LogId);
}

void
JsonFormatter::Format(const LogMessage& Msg, MemoryBuffer& Dest)
{
	ZEN_MEMSCOPE(ELLMTag::Logging);

	using std::chrono::duration_cast;
	using std::chrono::milliseconds;
	using std::chrono::seconds;

	auto Secs = duration_cast<seconds>(Msg.GetTime().time_since_epoch());
	if (Secs != m_Impl->m_LastLogSecs)
	{
		RwLock::ExclusiveLockScope _(m_Impl->m_TimestampLock);
		m_Impl->m_CachedTm	  = helpers::SafeLocaltime(LogClock::to_time_t(Msg.GetTime()));
		m_Impl->m_LastLogSecs = Secs;

		// cache the date/time part for the next second.
		m_Impl->m_CachedDatetime.clear();

		helpers::AppendInt(m_Impl->m_CachedTm.tm_year + 1900, m_Impl->m_CachedDatetime);
		m_Impl->m_CachedDatetime.push_back('-');

		helpers::Pad2(m_Impl->m_CachedTm.tm_mon + 1, m_Impl->m_CachedDatetime);
		m_Impl->m_CachedDatetime.push_back('-');

		helpers::Pad2(m_Impl->m_CachedTm.tm_mday, m_Impl->m_CachedDatetime);
		m_Impl->m_CachedDatetime.push_back(' ');

		helpers::Pad2(m_Impl->m_CachedTm.tm_hour, m_Impl->m_CachedDatetime);
		m_Impl->m_CachedDatetime.push_back(':');

		helpers::Pad2(m_Impl->m_CachedTm.tm_min, m_Impl->m_CachedDatetime);
		m_Impl->m_CachedDatetime.push_back(':');

		helpers::Pad2(m_Impl->m_CachedTm.tm_sec, m_Impl->m_CachedDatetime);

		m_Impl->m_CachedDatetime.push_back('.');
	}
	helpers::AppendStringView("{"sv, Dest);
	helpers::AppendStringView("\"time\": \""sv, Dest);
	{
		RwLock::SharedLockScope _(m_Impl->m_TimestampLock);
		Dest.append(m_Impl->m_CachedDatetime.begin(), m_Impl->m_CachedDatetime.end());
	}
	auto Millis = helpers::TimeFraction<milliseconds>(Msg.GetTime());
	helpers::Pad3(static_cast<uint32_t>(Millis.count()), Dest);
	helpers::AppendStringView("\", "sv, Dest);

	helpers::AppendStringView("\"status\": \""sv, Dest);
	helpers::AppendStringView(helpers::LevelToShortString(Msg.GetLevel()), Dest);
	helpers::AppendStringView("\", "sv, Dest);

	helpers::AppendStringView("\"source\": \""sv, Dest);
	helpers::AppendStringView("zenserver"sv, Dest);
	helpers::AppendStringView("\", "sv, Dest);

	helpers::AppendStringView("\"service\": \""sv, Dest);
	helpers::AppendStringView("zencache"sv, Dest);
	helpers::AppendStringView("\", "sv, Dest);

	if (!m_Impl->m_LogId.empty())
	{
		helpers::AppendStringView("\"id\": \""sv, Dest);
		helpers::AppendStringView(m_Impl->m_LogId, Dest);
		helpers::AppendStringView("\", "sv, Dest);
	}

	if (Msg.GetLoggerName().size() > 0)
	{
		helpers::AppendStringView("\"logger.name\": \""sv, Dest);
		helpers::AppendStringView(Msg.GetLoggerName(), Dest);
		helpers::AppendStringView("\", "sv, Dest);
	}

	if (Msg.GetThreadId() != 0)
	{
		helpers::AppendStringView("\"logger.thread_name\": \""sv, Dest);
		helpers::PadUint(Msg.GetThreadId(), 0, Dest);
		helpers::AppendStringView("\", "sv, Dest);
	}

	if (Msg.GetSource())
	{
		helpers::AppendStringView("\"file\": \""sv, Dest);
		WriteEscapedString(Dest, helpers::ShortFilename(Msg.GetSource().Filename));
		helpers::AppendStringView("\","sv, Dest);

		helpers::AppendStringView("\"line\": \""sv, Dest);
		helpers::AppendInt(Msg.GetSource().Line, Dest);
		helpers::AppendStringView("\","sv, Dest);
	}

	helpers::AppendStringView("\"message\": \""sv, Dest);
	WriteEscapedString(Dest, Msg.GetPayload());
	helpers::AppendStringView("\""sv, Dest);

	helpers::AppendStringView("}\n"sv, Dest);
}

}  // namespace zen::logging