aboutsummaryrefslogtreecommitdiff
path: root/primedev/logging/logging.cpp
blob: 3416bb8cb75e25aeabcd2fe02083d42640246f0f (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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#include "logging.h"
#include "core/convar/convar.h"
#include "core/convar/concommand.h"
#include "config/profile.h"
#include "core/tier0.h"
#include "util/version.h"
#include "spdlog/sinks/basic_file_sink.h"

#include <winternl.h>
#include <cstdlib>
#include <iomanip>
#include <sstream>

AUTOHOOK_INIT()

std::vector<std::shared_ptr<ColoredLogger>> loggers {};

namespace NS::log
{
	std::shared_ptr<ColoredLogger> SCRIPT_UI;
	std::shared_ptr<ColoredLogger> SCRIPT_CL;
	std::shared_ptr<ColoredLogger> SCRIPT_SV;

	std::shared_ptr<ColoredLogger> NATIVE_UI;
	std::shared_ptr<ColoredLogger> NATIVE_CL;
	std::shared_ptr<ColoredLogger> NATIVE_SV;
	std::shared_ptr<ColoredLogger> NATIVE_EN;

	std::shared_ptr<ColoredLogger> fs;
	std::shared_ptr<ColoredLogger> rpak;
	std::shared_ptr<ColoredLogger> echo;

	std::shared_ptr<ColoredLogger> NORTHSTAR;
	std::shared_ptr<ColoredLogger> PLUGINSYS;
}; // namespace NS::log

// This needs to be called after hooks are loaded so we can access the command line args
void CreateLogFiles()
{
	if (strstr(GetCommandLineA(), "-disablelogs"))
	{
		spdlog::default_logger()->set_level(spdlog::level::off);
	}
	else
	{
		try
		{
			// todo: might be good to delete logs that are too old
			time_t time = std::time(nullptr);
			tm currentTime = *std::localtime(&time);
			std::stringstream stream;

			stream << std::put_time(&currentTime, (GetNorthstarPrefix() + "/logs/nslog%Y-%m-%d %H-%M-%S.txt").c_str());
			auto sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(stream.str(), false);
			sink->set_pattern("[%Y-%m-%d] [%H:%M:%S] [%n] [%l] %v");
			for (auto& logger : loggers)
			{
				logger->sinks().push_back(sink);
			}
			spdlog::flush_on(spdlog::level::info);
		}
		catch (...)
		{
			spdlog::error("Failed creating log file!");
			MessageBoxA(
				0, "Failed creating log file! Make sure the profile directory is writable.", "Northstar Warning", MB_ICONWARNING | MB_OK);
		}
	}
}

void ExternalConsoleSink::sink_it_(const spdlog::details::log_msg& msg)
{
	throw std::runtime_error("sink_it_ called on SourceConsoleSink with pure log_msg. This is an error!");
}

void ExternalConsoleSink::custom_sink_it_(const custom_log_msg& msg)
{
	spdlog::memory_buf_t formatted;
	spdlog::sinks::base_sink<std::mutex>::formatter_->format(msg, formatted);

	std::string out = "";
	// if ansi colour is turned off, just use WriteConsoleA and return
	if (!g_bSpdLog_UseAnsiColor)
	{
		out += fmt::to_string(formatted);
	}

	// print to the console with colours
	else
	{
		// get message string
		std::string str = fmt::to_string(formatted);

		std::string levelColor = m_LogColours[msg.level];
		std::string name {msg.logger_name.begin(), msg.logger_name.end()};

		std::string name_str = "[NAME]";
		int name_pos = str.find(name_str);
		str.replace(name_pos, name_str.length(), msg.origin->ANSIColor + "[" + name + "]" + default_color);

		std::string level_str = "[LVL]";
		int level_pos = str.find(level_str);
		str.replace(level_pos, level_str.length(), levelColor + "[" + std::string(level_names[msg.level]) + "]" + default_color);

		out += str;
	}
	// print the string to the console - this is definitely bad i think
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	auto ignored = WriteConsoleA(handle, out.c_str(), std::strlen(out.c_str()), nullptr, nullptr);
	(void)ignored;
}

void ExternalConsoleSink::flush_()
{
	std::cout << std::flush;
}

void CustomSink::custom_log(const custom_log_msg& msg)
{
	std::lock_guard<std::mutex> lock(mutex_);
	custom_sink_it_(msg);
}

void InitialiseConsole()
{
	if (AllocConsole() == FALSE)
	{
		std::cout << "[*] Failed to create a console window, maybe a console already exists?" << std::endl;
	}
	else
	{
		freopen("CONOUT$", "w", stdout);
		freopen("CONOUT$", "w", stderr);
	}

	// this if statement is adapted from r5sdk
	if (!strstr(GetCommandLineA(), "-noansiclr"))
	{
		g_bSpdLog_UseAnsiColor = true;
		DWORD dwMode = 0;
		HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);

		GetConsoleMode(hOutput, &dwMode);
		dwMode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;

		if (!SetConsoleMode(hOutput, dwMode)) // Some editions of Windows have 'VirtualTerminalLevel' disabled by default.
		{
			// If 'VirtualTerminalLevel' can't be set, just disable ANSI color, since it wouldnt work anyway.
			spdlog::warn("could not set VirtualTerminalLevel. Disabling color output");
			g_bSpdLog_UseAnsiColor = false;
		}
	}
}

void RegisterLogger(std::shared_ptr<ColoredLogger> logger)
{
	loggers.push_back(logger);
}

void RegisterCustomSink(std::shared_ptr<CustomSink> sink)
{
	for (auto& logger : loggers)
	{
		logger->custom_sinks_.push_back(sink);
	}
};

void InitialiseLogging()
{
	// create a logger, and set it to default
	NS::log::NORTHSTAR = std::make_shared<ColoredLogger>("NORTHSTAR", NS::Colors::NORTHSTAR, true);
	NS::log::NORTHSTAR->sinks().clear();
	loggers.push_back(NS::log::NORTHSTAR);
	spdlog::set_default_logger(NS::log::NORTHSTAR);

	// create our console sink
	auto sink = std::make_shared<ExternalConsoleSink>();
	// set the pattern
	if (g_bSpdLog_UseAnsiColor)
		// dont put the log level in the pattern if we are using colours, as the colour will show the log level
		sink->set_pattern("[%H:%M:%S] [NAME] [LVL] %v");
	else
		sink->set_pattern("[%H:%M:%S] [%n] [%l] %v");

	// add our sink to the logger
	NS::log::NORTHSTAR->custom_sinks_.push_back(sink);

	NS::log::SCRIPT_UI = std::make_shared<ColoredLogger>("SCRIPT UI", NS::Colors::SCRIPT_UI);
	NS::log::SCRIPT_CL = std::make_shared<ColoredLogger>("SCRIPT CL", NS::Colors::SCRIPT_CL);
	NS::log::SCRIPT_SV = std::make_shared<ColoredLogger>("SCRIPT SV", NS::Colors::SCRIPT_SV);

	NS::log::NATIVE_UI = std::make_shared<ColoredLogger>("NATIVE UI", NS::Colors::NATIVE_UI);
	NS::log::NATIVE_CL = std::make_shared<ColoredLogger>("NATIVE CL", NS::Colors::NATIVE_CL);
	NS::log::NATIVE_SV = std::make_shared<ColoredLogger>("NATIVE SV", NS::Colors::NATIVE_SV);
	NS::log::NATIVE_EN = std::make_shared<ColoredLogger>("NATIVE EN", NS::Colors::NATIVE_ENGINE);

	NS::log::fs = std::make_shared<ColoredLogger>("FILESYSTM", NS::Colors::FILESYSTEM);
	NS::log::rpak = std::make_shared<ColoredLogger>("RPAK_FSYS", NS::Colors::RPAK);
	NS::log::echo = std::make_shared<ColoredLogger>("ECHO", NS::Colors::ECHO);

	NS::log::PLUGINSYS = std::make_shared<ColoredLogger>("PLUGINSYS", NS::Colors::PLUGINSYS);

	loggers.push_back(NS::log::SCRIPT_UI);
	loggers.push_back(NS::log::SCRIPT_CL);
	loggers.push_back(NS::log::SCRIPT_SV);

	loggers.push_back(NS::log::NATIVE_UI);
	loggers.push_back(NS::log::NATIVE_CL);
	loggers.push_back(NS::log::NATIVE_SV);
	loggers.push_back(NS::log::NATIVE_EN);

	loggers.push_back(NS::log::PLUGINSYS);

	loggers.push_back(NS::log::fs);
	loggers.push_back(NS::log::rpak);
	loggers.push_back(NS::log::echo);
}

void NS::log::FlushLoggers()
{
	for (auto& logger : loggers)
		logger->flush();

	spdlog::default_logger()->flush();
}

// Wine specific functions
typedef const char*(CDECL* wine_get_host_version_type)(const char**, const char**);
wine_get_host_version_type wine_get_host_version;

typedef const char*(CDECL* wine_get_build_id_type)(void);
wine_get_build_id_type wine_get_build_id;

// Not exported Winapi methods
typedef NTSTATUS(WINAPI* RtlGetVersion_type)(PRTL_OSVERSIONINFOW);
RtlGetVersion_type RtlGetVersion;

void StartupLog()
{
	spdlog::info("NorthstarLauncher version: {}", version);
	spdlog::info("Command line: {}", GetCommandLineA());
	spdlog::info("Using profile: {}", GetNorthstarPrefix());

	HMODULE ntdll = GetModuleHandleA("ntdll.dll");
	if (!ntdll)
	{
		// How did we get here
		spdlog::info("Operating System: Unknown");
		return;
	}

	wine_get_host_version = (wine_get_host_version_type)GetProcAddress(ntdll, "wine_get_host_version");
	if (wine_get_host_version)
	{
		// Load the rest of the functions we need
		wine_get_build_id = (wine_get_build_id_type)GetProcAddress(ntdll, "wine_get_build_id");

		const char* sysname;
		wine_get_host_version(&sysname, NULL);

		spdlog::info("Operating System: {} (Wine)", sysname);
		spdlog::info("Wine build: {}", wine_get_build_id());

		// STEAM_COMPAT_TOOL_PATHS is a colon separated lists of all compat tool paths used
		// The first one tends to be the Proton path itself
		// We extract the basename out of it to get the name used
		char* compatToolPtr = std::getenv("STEAM_COMPAT_TOOL_PATHS");
		if (compatToolPtr)
		{
			std::string_view compatToolPath(compatToolPtr);

			auto protonBasenameEnd = compatToolPath.find(":");
			if (protonBasenameEnd == std::string_view::npos)
				protonBasenameEnd = 0;
			auto protonBasenameStart = compatToolPath.rfind("/", protonBasenameEnd) + 1;
			if (protonBasenameStart == std::string_view::npos)
				protonBasenameStart = 0;

			spdlog::info("Proton build: {}", compatToolPath.substr(protonBasenameStart, protonBasenameEnd - protonBasenameStart));
		}
	}
	else
	{
		// We are real Windows (hopefully)
		const char* win_ver = "Unknown";

		RTL_OSVERSIONINFOW osvi;
		osvi.dwOSVersionInfoSize = sizeof(osvi);

		RtlGetVersion = (RtlGetVersion_type)GetProcAddress(ntdll, "RtlGetVersion");
		if (RtlGetVersion && !RtlGetVersion(&osvi))
		{
			// Version reference table
			// https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-osversioninfoa#remarks
			spdlog::info("Operating System: Windows (NT{}.{})", osvi.dwMajorVersion, osvi.dwMinorVersion);
		}
		else
		{
			spdlog::info("Operating System: Windows");
		}
	}
}