aboutsummaryrefslogtreecommitdiff
path: root/src/zenutil/logging.cpp
blob: 54ac30c5db35147d22d6f33a993153040b12b718 (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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenutil/logging.h"

ZEN_THIRD_PARTY_INCLUDES_START
#include <spdlog/async.h>
#include <spdlog/async_logger.h>
#include <spdlog/sinks/ansicolor_sink.h>
#include <spdlog/sinks/msvc_sink.h>
#include <spdlog/spdlog.h>
ZEN_THIRD_PARTY_INCLUDES_END

#include <zencore/callstack.h>
#include <zencore/compactbinary.h>
#include <zencore/filesystem.h>
#include <zencore/logging.h>
#include <zencore/memory/llm.h>
#include <zencore/string.h>
#include <zencore/timer.h>
#include <zenutil/logging/fullformatter.h>
#include <zenutil/logging/jsonformatter.h>
#include <zenutil/logging/rotatingfilesink.h>

#include <chrono>
#include <memory>

namespace zen {

static bool		 g_IsLoggingInitialized;
spdlog::sink_ptr g_FileSink;

spdlog::sink_ptr
GetFileSink()
{
	return g_FileSink;
}

void
InitializeLogging(const LoggingOptions& LogOptions)
{
	BeginInitializeLogging(LogOptions);
	FinishInitializeLogging(LogOptions);
}

static std::terminate_handler OldTerminateHandler = nullptr;

void
BeginInitializeLogging(const LoggingOptions& LogOptions)
{
	ZEN_MEMSCOPE(ELLMTag::Logging);

	zen::logging::InitializeLogging();
	zen::logging::EnableVTMode();

	bool IsAsync = LogOptions.AllowAsync;

	if (LogOptions.IsDebug)
	{
		IsAsync = false;
	}

	if (LogOptions.IsTest)
	{
		IsAsync = false;
	}

	if (IsAsync)
	{
		const int QueueSize	  = 8192;
		const int ThreadCount = 1;
		spdlog::init_thread_pool(QueueSize, ThreadCount, [&] { SetCurrentThreadName("spdlog_async"); });

		auto AsyncSink = spdlog::create_async<spdlog::sinks::ansicolor_stdout_sink_mt>("main");
		zen::logging::SetDefault("main");
	}

	// Sinks

	spdlog::sink_ptr FileSink;

	// spdlog can't create directories that starts with `\\?\` so we make sure the folder exists before creating the logger instance

	if (!LogOptions.AbsLogFile.empty())
	{
		if (LogOptions.AbsLogFile.has_parent_path())
		{
			zen::CreateDirectories(LogOptions.AbsLogFile.parent_path());
		}

		FileSink = std::make_shared<zen::logging::RotatingFileSink>(LogOptions.AbsLogFile,
																	/* max size */ 128 * 1024 * 1024,
																	/* max files */ 16,
																	/* rotate on open */ true);
		if (LogOptions.AbsLogFile.extension() == ".json")
		{
			FileSink->set_formatter(std::make_unique<logging::json_formatter>(LogOptions.LogId));
		}
		else
		{
			FileSink->set_formatter(std::make_unique<logging::full_formatter>(LogOptions.LogId));  // this will have a date prefix
		}
	}

	OldTerminateHandler = std::set_terminate([]() {
		try
		{
			constexpr int	 SkipFrameCount = 4;
			constexpr int	 FrameCount		= 8;
			uint8_t			 CallstackBuffer[CallstackRawMemorySize(SkipFrameCount, FrameCount)];
			CallstackFrames* Callstack = GetCallstackRaw(&CallstackBuffer[0], SkipFrameCount, FrameCount);

			fmt::basic_memory_buffer<char, 2048> Message;
			auto								 Appender = fmt::appender(Message);
			fmt::format_to(Appender, "Program exited abnormally via std::terminate()");

			if (Callstack->FrameCount > 0)
			{
				fmt::format_to(Appender, "\n");

				CallstackToStringRaw(Callstack, &Message, [](void* UserData, uint32_t FrameIndex, const char* FrameText) {
					ZEN_UNUSED(FrameIndex);
					fmt::basic_memory_buffer<char, 2048>* Message  = (fmt::basic_memory_buffer<char, 2048>*)UserData;
					auto								  Appender = fmt::appender(*Message);
					fmt::format_to(Appender, "  {}\n", FrameText);
				});
			}
			Message.push_back('\0');

			// We use direct ZEN_LOG here instead of ZEN_ERROR as we don't care about *this* code location in the log
			ZEN_LOG(Log(), zen::logging::level::Critical, "{}", Message.data());
			zen::logging::FlushLogging();
		}
		catch (const std::exception&)
		{
			// Ignore any exceptions in terminate callback
		}
		if (OldTerminateHandler)
		{
			OldTerminateHandler();
		}
	});

	// Default

	LoggerRef DefaultLogger = zen::logging::Default();
	auto&	  Sinks			= DefaultLogger.SpdLogger->sinks();

	Sinks.clear();

	if (LogOptions.NoConsoleOutput)
	{
		zen::logging::SuppressConsoleLog();
	}
	else
	{
		auto ConsoleSink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();
		if (LogOptions.QuietConsole)
		{
			ConsoleSink->set_level(spdlog::level::warn);
		}
		Sinks.push_back(ConsoleSink);
	}

	if (FileSink)
	{
		Sinks.push_back(FileSink);
	}

#if ZEN_PLATFORM_WINDOWS
	if (zen::IsDebuggerPresent() && LogOptions.IsDebug)
	{
		auto DebugSink = std::make_shared<spdlog::sinks::msvc_sink_mt>();
		DebugSink->set_level(spdlog::level::debug);
		Sinks.push_back(DebugSink);
	}
#endif

	spdlog::set_error_handler([](const std::string& msg) {
		if (msg == std::bad_alloc().what())
		{
			// Don't report out of memory in spdlog as we usually log in response to errors which will cause another OOM crashing the
			// program
			return;
		}
		// Bypass zen logging wrapping to reduce potential other error sources
		if (auto ErrLogger = zen::logging::ErrorLog())
		{
			try
			{
				ErrLogger.SpdLogger->log(spdlog::level::err, msg);
			}
			catch (const std::exception&)
			{
				// Just ignore any errors when in error handler
			}
		}
		try
		{
			Log().SpdLogger->error(msg);
		}
		catch (const std::exception&)
		{
			// Just ignore any errors when in error handler
		}
	});

	g_FileSink = std::move(FileSink);
}

void
FinishInitializeLogging(const LoggingOptions& LogOptions)
{
	ZEN_MEMSCOPE(ELLMTag::Logging);

	logging::level::LogLevel LogLevel = logging::level::Info;

	if (LogOptions.IsDebug)
	{
		LogLevel = logging::level::Debug;
	}

	if (LogOptions.IsTest || LogOptions.IsVerbose)
	{
		LogLevel = logging::level::Trace;
	}

	// Configure all registered loggers according to settings

	logging::RefreshLogLevels(LogLevel);
	spdlog::flush_on(spdlog::level::err);
	spdlog::flush_every(std::chrono::seconds{2});
	spdlog::set_formatter(std::make_unique<logging::full_formatter>(
		LogOptions.LogId,
		std::chrono::system_clock::now() - std::chrono::milliseconds(GetTimeSinceProcessStart())));	 // default to duration prefix

	// If the console logger was initialized before, the above will change the output format
	// so we need to reset it

	logging::ResetConsoleLog();

	if (g_FileSink)
	{
		if (LogOptions.AbsLogFile.extension() == ".json")
		{
			g_FileSink->set_formatter(std::make_unique<logging::json_formatter>(LogOptions.LogId));
		}
		else
		{
			g_FileSink->set_formatter(std::make_unique<logging::full_formatter>(LogOptions.LogId));	 // this will have a date prefix
		}

		const std::string StartLogTime = zen::DateTime::Now().ToIso8601();

		spdlog::apply_all([&](auto Logger) { Logger->info("log starting at {}", StartLogTime); });
	}

	g_IsLoggingInitialized = true;
}

void
ShutdownLogging()
{
	if (g_IsLoggingInitialized && g_FileSink)
	{
		auto DefaultLogger = zen::logging::Default();
		ZEN_LOG_INFO(DefaultLogger, "log ending at {}", zen::DateTime::Now().ToIso8601());
	}

	zen::logging::ShutdownLogging();

	g_FileSink.reset();
}

}  // namespace zen