File: FileSink.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (285 lines) | stat: -rwxr-xr-x 7,073 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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "FileSink.h"

#include "Backend.h"
#include "FramePrefixer.h"
#include "Level.h" // for LOG_LEVEL_*
#include "System/maindefines.h"
#include "System/Log/ILog.h"
#include "System/Log/Level.h"

#include <cassert>
#include <cstdio>
#include <string>
#include <list>
#include <map>


namespace {

	struct LogFileDetails {
		LogFileDetails(FILE* outStream = NULL, const std::string& sections = "",
				int minLevel = LOG_LEVEL_ALL)
			: outStream(outStream)
			, sections(sections)
			, minLevel(minLevel)
		{}

		FILE* GetOutStream() const {
			return outStream;
		}

		bool IsLogging(const char* section, int level) const {
			return ((level >= minLevel) && (sections.empty()
					|| (sections.find("," + std::string(section) + ",")
					!= std::string::npos)));
		}

	private:
		FILE* outStream;
		std::string sections;
		int minLevel;
	};
	typedef std::map<std::string, LogFileDetails> logFiles_t;

	/**
	 * This is only used to check whether some code tries to access the
	 * log-files contianer after it got deleted.
	 */
	bool logFilesValidTracker = true;

	/**
	 * This class allows us to stop logging cleanly, when the application exits,
	 * and while the container is still valid (not deleted yet).
	 */
	struct LogFilesContainer {
		~LogFilesContainer() {
			log_file_removeAllLogFiles();
			logFilesValidTracker = false;
		}
		logFiles_t& GetLogFiles() {
			return logFiles;
		}

	private:
		logFiles_t logFiles;
	};

	inline logFiles_t& log_file_getLogFiles() {
		static LogFilesContainer logFilesContainer;

		assert(logFilesValidTracker);
		return logFilesContainer.GetLogFiles();
	}

	/**
	 * This class allows us to stop logging cleanly, when the application exits,
	 * and while the container is still valid (not deleted yet).
	 */
	struct LogRecord {
		LogRecord(const std::string& section, int level,
				const std::string& record)
			: section(section)
			, level(level)
			, record(record)
		{}

		const std::string& GetSection() const { return section; }
		int GetLevel() const { return level; }
		const std::string& GetRecord() const { return record; }

	private:
		std::string section;
		int level;
		std::string record;
	};
	typedef std::list<LogRecord> logRecords_t;

	inline logRecords_t& log_file_getRecordBuffer() {
		static logRecords_t buffer;
		return buffer;
	}

	inline bool log_file_isActivelyLogging() {
		return (!log_file_getLogFiles().empty());
	}

	void log_file_writeToFile(FILE* outStream, const char* record) {

		char framePrefix[128] = {'\0'};
		log_framePrefixer_createPrefix(framePrefix, sizeof(framePrefix));

		FPRINTF(outStream, "%s%s\n", framePrefix, record);

		// We never flush, but only close the stream before process exit.
		// This decision was made in two engine dev meetings, the last one was
		// at 26. September 2011.
		//fflush(outStream);
	}

	/**
	 * Writes to the individual log files, if they do want to log the section.
	 */
	void log_file_writeToFiles(const char* section, int level,
			const char* record)
	{
		const logFiles_t& logFiles = log_file_getLogFiles();
		logFiles_t::const_iterator lfi;
		for (lfi = logFiles.begin(); lfi != logFiles.end(); ++lfi) {
			if (lfi->second.IsLogging(section, level)
					&& (lfi->second.GetOutStream() != NULL))
			{
				log_file_writeToFile(lfi->second.GetOutStream(), record);
			}
		}
	}

	/**
	 * Flushes the buffer of a single log file.
	 */
	void log_file_flushFile(FILE* outStream) {
		fflush(outStream);
	}

	/**
	 * Flushes the buffers of the individual log files.
	 */
	void log_file_flushFiles() {
		const logFiles_t& logFiles = log_file_getLogFiles();
		logFiles_t::const_iterator lfi;
		for (lfi = logFiles.begin(); lfi != logFiles.end(); ++lfi) {
			if (lfi->second.GetOutStream() != NULL) {
				log_file_flushFile(lfi->second.GetOutStream());
			}
		}
	}

	/**
	 * Writes the content of the buffer to all the currently registered log
	 * files.
	 */
	void log_file_writeBufferToFiles() {

		while (!log_file_getRecordBuffer().empty()) {
			logRecords_t& logRecords = log_file_getRecordBuffer();
			const logRecords_t::iterator lri = logRecords.begin();
			log_file_writeToFiles(lri->GetSection().c_str(), lri->GetLevel(),
					lri->GetRecord().c_str());
			logRecords.erase(lri);
		}
	}

	inline void log_file_writeToBuffer(const std::string& section, int level,
			const std::string& record)
	{
		log_file_getRecordBuffer().push_back(LogRecord(section, level, record));
	}
}


#ifdef __cplusplus
extern "C" {
#endif

void log_file_addLogFile(const char* filePath, const char* sections, int minLevel) {

	assert(filePath != NULL);

	logFiles_t& logFiles = log_file_getLogFiles();
	const std::string filePathStr = filePath;
	const logFiles_t::const_iterator lfi = logFiles.find(filePathStr);
	if (lfi != logFiles.end()) {
		// we are already logging to this file
		return;
	}
#ifdef WIN32
	// c (commit) makes fflush work on newer Windows like it should, see
	// http://msdn.microsoft.com/en-us/library/aa246392%28v=vs.60%29.aspx
	FILE* tmpStream = fopen(filePath, "wc");
#else
	FILE* tmpStream = fopen(filePath, "w");
#endif
	if (tmpStream == NULL) {
		LOG_L(L_ERROR, "Failed to open log file for writing: %s", filePath);
		return;
	}

	const std::string sectionsStr = (sections == NULL) ? "" : sections;
	logFiles[filePathStr] = LogFileDetails(tmpStream, sectionsStr, minLevel);
}

void log_file_removeLogFile(const char* filePath) {

	assert(filePath != NULL);

	logFiles_t& logFiles = log_file_getLogFiles();
	const std::string filePathStr = filePath;
	const logFiles_t::iterator lfi = logFiles.find(filePathStr);
	if (lfi == logFiles.end()) {
		// we are not logging to this file
		return;
	}

	// turn off logging to this file
	FILE* tmpStream = lfi->second.GetOutStream();
	logFiles.erase(lfi);
	fclose(tmpStream);
	tmpStream = NULL;
}

void log_file_removeAllLogFiles() {

	while (!log_file_getLogFiles().empty()) {
		const logFiles_t::const_iterator lfi = log_file_getLogFiles().begin();
		log_file_removeLogFile(lfi->first.c_str());
	}
}

/**
 * @name logging_sink_file
 * ILog.h sink implementation.
 */
///@{

/// Records a log entry
static void log_sink_record_file(const char* section, int level,
		const char* record)
{
	if (log_file_isActivelyLogging()) {
		// write buffer to log file
		log_file_writeBufferToFiles();

		// write current record to log file
		log_file_writeToFiles(section, level, record);
	} else {
		// buffer until a log file is ready for output
		log_file_writeToBuffer(section, level, record);
	}
}

/// Cleans up all log streams, by flushing them.
static void log_sink_cleanup_file() {
	if (log_file_isActivelyLogging()) {
		// flush the log buffers to files
		log_file_flushFiles();
	}
}

///@}


namespace {
	/// Auto-registers the sink defined in this file before main() is called
	struct FileSinkRegistrator {
		FileSinkRegistrator() {
			log_backend_registerSink(&log_sink_record_file);
			log_backend_registerCleanup(&log_sink_cleanup_file);
		}
	} fileSinkRegistrator;
}

#ifdef __cplusplus
} // extern "C"
#endif