File: LogOutput.cpp

package info (click to toggle)
spring 0.81.2.1%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 28,496 kB
  • ctags: 37,096
  • sloc: cpp: 238,659; ansic: 13,784; java: 12,175; awk: 3,428; python: 1,159; xml: 738; perl: 405; sh: 297; makefile: 267; pascal: 228; objc: 192
file content (444 lines) | stat: -rw-r--r-- 10,120 bytes parent folder | download
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#include "StdAfx.h"

#include "LogOutput.h"

#include <assert.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <boost/thread/recursive_mutex.hpp>

#ifdef _MSC_VER
#include <windows.h>
#endif

#include "lib/gml/gml.h"
#include "Util.h"
#include "float3.h"
#include "Sim/Misc/GlobalSynced.h"
#include "Game/GameVersion.h"
#include "ConfigHandler.h"
#include "FileSystem/FileSystemHandler.h"
#include "mmgr.h"

#include <string>
#include <vector>

using std::string;
using std::vector;

/******************************************************************************/
/******************************************************************************/

CLogSubsystem* CLogSubsystem::linkedList;
static CLogSubsystem LOG_DEFAULT("", true);


CLogSubsystem::CLogSubsystem(const char* name, bool enabled)
: name(name), next(linkedList), enabled(enabled)
{
	linkedList = this;
}

/******************************************************************************/
/******************************************************************************/

CLogOutput logOutput;

namespace
{
	struct PreInitLogEntry
	{
		PreInitLogEntry(const CLogSubsystem* subsystem, string text)
			: subsystem(subsystem), text(text) {}

		const CLogSubsystem* subsystem;
		string text;
	};
}

// wrapped in a function to prevent order of initialization problems
// when logOutput is used before main() is entered.
static vector<PreInitLogEntry>& preInitLog()
{
	static vector<PreInitLogEntry> preInitLog;
	return preInitLog;
}

static std::ofstream* filelog = 0;
static bool initialized = false;

static const int BUFFER_SIZE = 2048;


LogObject::LogObject(const CLogSubsystem& _subsys) : subsys(_subsys)
{
}

LogObject::LogObject() : subsys(LOG_DEFAULT)
{
}

LogObject::~LogObject()
{
	// LogOutput adds a newline if necessary
	logOutput.Prints(subsys, str.str());
}

CLogOutput::CLogOutput()
	: fileName("")
	, filePath("")
{
	// multiple infologs can't exist together!
	assert(this == &logOutput);
	assert(!filelog);

	SetFileName("infolog.txt");

	bool doRotateLogFiles = false;
	std::string rotatePolicy = "auto";
	if (configHandler != NULL) {
		rotatePolicy = configHandler->GetString("RotateLogFiles", "auto");
	}
	if (rotatePolicy == "always") {
		doRotateLogFiles = true;
	} else if (rotatePolicy == "never") {
		doRotateLogFiles = false;
	} else { // auto
#ifdef DEBUG
		doRotateLogFiles = true;
#else
		doRotateLogFiles = false;
#endif
	}
	SetLogFileRotating(doRotateLogFiles);
}


CLogOutput::~CLogOutput()
{
	End();
}


void CLogOutput::End()
{
	GML_STDMUTEX_LOCK_NOPROF(log); // End

	SafeDelete(filelog);
}

void CLogOutput::Flush()
{
	GML_STDMUTEX_LOCK_NOPROF(log); // Flush

	filelog->flush();
}

const std::string& CLogOutput::GetFileName() const
{
	return fileName;
}
const std::string& CLogOutput::GetFilePath() const
{
	assert(initialized);
	return filePath;
}
void CLogOutput::SetFileName(std::string fname)
{
	GML_STDMUTEX_LOCK(log); // SetFileName

	assert(!initialized);
	fileName = fname;
}

std::string CLogOutput::CreateFilePath(const std::string& fileName)
{
	return FileSystemHandler::GetCwd() + (char)FileSystemHandler::GetNativePathSeparator() + fileName;
}


void CLogOutput::SetLogFileRotating(bool enabled)
{
	assert(!initialized);
	rotateLogFiles = enabled;
}
bool CLogOutput::IsLogFileRotating() const
{
	return rotateLogFiles;
}

void CLogOutput::RotateLogFile() const
{

	if (IsLogFileRotating()) {
		if (FileSystemHandler::FileExists(filePath)) {
			// logArchiveDir: /absolute/writeable/data/dir/log/
			std::string logArchiveDir = filePath.substr(0, filePath.find_last_of("/\\") + 1);
			logArchiveDir = logArchiveDir + "log" + (char)FileSystemHandler::GetNativePathSeparator();

			const std::string archivedLogFile = logArchiveDir + FileSystemHandler::GetFileModificationDate(filePath) + "_" + fileName;

			// create the log archive dir if it does nto exist yet
			if (!FileSystemHandler::DirExists(logArchiveDir)) {
				FileSystemHandler::mkdir(logArchiveDir);
			}

			// move the old log to the archive dir
			const int moveError = rename(filePath.c_str(), archivedLogFile.c_str());
			if (moveError != 0) {
				// no log here yet
				std::cout << "Failed rotating the log file" << std::endl;
			}
		}
	}
}

void CLogOutput::Initialize()
{
	if (initialized) return;

	filePath = CreateFilePath(fileName);
	RotateLogFile();

	filelog = new std::ofstream(filePath.c_str());
	if (filelog->bad())
		SafeDelete(filelog);

	initialized = true;
	Print("LogOutput initialized.\n");
	Print("Spring %s", SpringVersion::GetFull().c_str());
	logOutput.Print("Build date/time: %s", SpringVersion::BuildTime);

	InitializeSubsystems();

	for (vector<PreInitLogEntry>::iterator it = preInitLog().begin(); it != preInitLog().end(); ++it)
	{
		if (!it->subsystem->enabled) return;

		// Output to subscribers
		for(vector<ILogSubscriber*>::iterator lsi = subscribers.begin(); lsi != subscribers.end(); ++lsi)
			(*lsi)->NotifyLogMsg(*(it->subsystem), it->text);
		if (filelog)
			ToFile(*it->subsystem, it->text);
	}
	preInitLog().clear();
}

void CLogOutput::InitializeSubsystems()
{
	{
		LogObject lo;
		lo << "Available log subsystems: ";
		for (CLogSubsystem* sys = CLogSubsystem::GetList(); sys; sys = sys->next) {
			if (sys->name && *sys->name) {
				lo << sys->name;
				if (sys->next)
					lo << ", ";
			}
		}
	}
	// enabled subsystems is superset of the ones specified in environment
	// and the ones specified in the configuration file.
	// configHandler cannot be accessed here in unitsync since it may not exist.
#ifndef UNITSYNC
	string subsystems = "," + StringToLower(configHandler->GetString("LogSubsystems", "")) + ",";
#else
#  ifdef DEBUG
	// unitsync logging in debug mode always on
	string subsystems = ",unitsync,";
#  else
	string subsystems = ",";
#  endif
#endif

	const char* const env = getenv("SPRING_LOG_SUBSYSTEMS");
	if (env)
		subsystems += StringToLower(env) + ",";


	{
		LogObject lo;
		lo << "Enabled log subsystems: ";
		for (CLogSubsystem* sys = CLogSubsystem::GetList(); sys; sys = sys->next) {
			if (sys->name && *sys->name) {
				const string name = StringToLower(sys->name);
				const string::size_type index = subsystems.find("," + name + ",");

				// log subsystems which are enabled by default can not be disabled
				// ("enabled by default" wouldn't make sense otherwise...)
				if (!sys->enabled && index != string::npos)
					sys->enabled = true;

				if (sys->enabled) {
					lo << sys->name;
					if (sys->next)
						lo << ", ";
				}
			}
		}
	}

	Print("Enable or disable log subsystems using the LogSubsystems configuration key\n");
	Print("  or the SPRING_LOG_SUBSYSTEMS environment variable (both comma separated).\n");
}


void CLogOutput::Output(const CLogSubsystem& subsystem, const std::string& str)
{
	GML_STDMUTEX_LOCK(log); // Output

	if (!initialized) {
		ToStdout(subsystem, str);
		preInitLog().push_back(PreInitLogEntry(&subsystem, str));
		return;
	}

	if (!subsystem.enabled) return;

	// Output to subscribers
	for(vector<ILogSubscriber*>::iterator lsi = subscribers.begin(); lsi != subscribers.end(); ++lsi)
		(*lsi)->NotifyLogMsg(subsystem, str);

#ifdef _MSC_VER
	int index = strlen(str.c_str()) - 1;
	bool newline = ((index < 0) || (str[index] != '\n'));
	OutputDebugString(str.c_str());
	if (newline)
		OutputDebugString("\n");
#endif // _MSC_VER


	if (filelog) {
		ToFile(subsystem, str);
	}

	ToStdout(subsystem, str);
}


void CLogOutput::SetLastMsgPos(const float3& pos)
{
	GML_STDMUTEX_LOCK(log); // SetLastMsgPos

	for(vector<ILogSubscriber*>::iterator lsi = subscribers.begin(); lsi != subscribers.end(); ++lsi)
		(*lsi)->SetLastMsgPos(pos);
}


void CLogOutput::AddSubscriber(ILogSubscriber* ls)
{
	GML_STDMUTEX_LOCK(log); // AddSubscriber

	subscribers.push_back(ls);
}


void CLogOutput::RemoveAllSubscribers()
{
	GML_STDMUTEX_LOCK(log); // RemoveAllSubscribers

	subscribers.clear();
}


void CLogOutput::RemoveSubscriber(ILogSubscriber *ls)
{
	GML_STDMUTEX_LOCK(log); // RemoveSubscriber

	subscribers.erase(std::find(subscribers.begin(), subscribers.end(), ls));
}


// ----------------------------------------------------------------------
// Printing functions
// ----------------------------------------------------------------------


void CLogOutput::Print(CLogSubsystem& subsystem, const char* fmt, ...)
{
	// if logOutput isn't initialized then subsystem.enabled still has it's default value
	if (initialized && !subsystem.enabled) return;

	va_list argp;

	va_start(argp, fmt);
	Printv(subsystem, fmt, argp);
	va_end(argp);
}


void CLogOutput::Printv(CLogSubsystem& subsystem, const char* fmt, va_list argp)
{
	// if logOutput isn't initialized then subsystem.enabled still has it's default value
	if (initialized && !subsystem.enabled) return;

	char text[BUFFER_SIZE];

	VSNPRINTF(text, sizeof(text), fmt, argp);
	Output(subsystem, std::string(text));
}


void CLogOutput::Print(const char* fmt, ...)
{
	va_list argp;

	va_start(argp, fmt);
	Printv(LOG_DEFAULT, fmt, argp);
	va_end(argp);
}


void CLogOutput::Print(const std::string& text)
{
	Output(LOG_DEFAULT, text);
}


void CLogOutput::Prints(const CLogSubsystem& subsystem, const std::string& text)
{
	Output(subsystem, text);
}


CLogSubsystem& CLogOutput::GetDefaultLogSubsystem()
{
	return LOG_DEFAULT;
}

void CLogOutput::ToStdout(const CLogSubsystem& subsystem, const std::string message)
{
	if (message.empty())
		return;
	const bool newline = (message.at(message.size() -1) != '\n');

	if (subsystem.name && *subsystem.name) {
		std::cout << subsystem.name << ": ";
	}
	std::cout << message;
	if (newline)
		std::cout << std::endl;
	else
		std::cout.flush();
}

void CLogOutput::ToFile(const CLogSubsystem& subsystem, const std::string message)
{
	if (message.empty())
		return;
	const bool newline = (message.at(message.size() -1) != '\n');

#if !defined UNITSYNC && !defined DEDICATED
	if (gs) {
		(*filelog) << IntToString(gs->frameNum, "[%7d] ");
	}
#endif
	if (subsystem.name && *subsystem.name)
		(*filelog) << subsystem.name << ": ";
	(*filelog) << message;
	if (newline)
		(*filelog) << std::endl;
	else
		filelog->flush();
}