core/Logger.cpp
author David Anderson <dvander@alliedmods.net>
Sun Aug 19 18:34:36 2007 +0000 (2007-08-19)
changeset 1361 591f6d2fd11d
parent 1330 ab94316bb52b
child 1371 d207f0e17532
permissions -rw-r--r--
added helper function for panel text
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or modify it under
     9  * the terms of the GNU General Public License, version 3.0, as published by the
    10  * Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful, but WITHOUT
    13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    14  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    15  * details.
    16  *
    17  * You should have received a copy of the GNU General Public License along with
    18  * this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to link the
    21  * code of this program (as well as its derivative works) to "Half-Life 2," the
    22  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    23  * by the Valve Corporation.  You must obey the GNU General Public License in
    24  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    25  * this exception to all derivative works.  AlliedModders LLC defines further
    26  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    27  * or <http://www.sourcemod.net/license.php>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <time.h>
    33 #include "sourcemod.h"
    34 #include "sourcemm_api.h"
    35 #include "sm_stringutil.h"
    36 #include "Logger.h"
    37 #include "systems/LibrarySys.h"
    38 #include "sm_version.h"
    39 
    40 Logger g_Logger;
    41 
    42 /**
    43  * :TODO: This should be creating the log folder if it doesn't exist
    44  */
    45 
    46 ConfigResult Logger::OnSourceModConfigChanged(const char *key, 
    47 									  const char *value, 
    48 									  ConfigSource source,
    49 									  char *error, 
    50 									  size_t maxlength)
    51 {
    52 	if (strcasecmp(key, "Logging") == 0)
    53 	{
    54 		bool state;
    55 
    56 		if (strcasecmp(value, "on") == 0)
    57 		{
    58 			state = true;
    59 		} else if (strcasecmp(value, "off") == 0) {
    60 			state = false;
    61 		} else {
    62 			UTIL_Format(error, maxlength, "Invalid value: must be \"on\" or \"off\"");
    63 			return ConfigResult_Reject;
    64 		}
    65 
    66 		if (source == ConfigSource_Console)
    67 		{
    68 			state ? EnableLogging() : DisableLogging();
    69 		} else {
    70 			m_InitialState = state;
    71 		}
    72 
    73 		return ConfigResult_Accept;
    74 	} else if (strcasecmp(key, "LogMode") == 0) {
    75 		if (strcasecmp(value, "daily") == 0) 
    76 		{
    77 			m_Mode = LoggingMode_Daily;
    78 		} else if (strcasecmp(value, "map") == 0) {
    79 			m_Mode = LoggingMode_PerMap;
    80 		} else if (strcasecmp(value, "game") == 0) {
    81 			m_Mode = LoggingMode_Game;
    82 		} else {
    83 			UTIL_Format(error, maxlength, "Invalid value: must be [daily|map|game]");
    84 			return ConfigResult_Reject;
    85 		}
    86 
    87 		return ConfigResult_Accept;
    88 	}
    89 
    90 	return ConfigResult_Ignore;
    91 }
    92 
    93 void Logger::OnSourceModStartup(bool late)
    94 {
    95 	InitLogger(m_Mode);
    96 }
    97 
    98 void Logger::OnSourceModAllShutdown()
    99 {
   100 	CloseLogger();
   101 }
   102 
   103 void Logger::OnSourceModLevelChange(const char *mapName)
   104 {
   105 	MapChange(mapName);
   106 }
   107 
   108 void Logger::_NewMapFile()
   109 {
   110 	if (!m_Active)
   111 	{
   112 		return;
   113 	}
   114 
   115 	/* Append "Log file closed" to previous log file */
   116 	_CloseFile();
   117 	
   118 	char _filename[256];
   119 	int i = 0;
   120 
   121 	time_t t;
   122 	time(&t);
   123 	tm *curtime = localtime(&t);
   124 
   125 	while (true)
   126 	{
   127 		g_SourceMod.BuildPath(Path_SM, _filename, sizeof(_filename), "logs/L%02d%02d%03d.log", curtime->tm_mon + 1, curtime->tm_mday, i);
   128 		FILE *fp = fopen(_filename, "r");
   129 		if (!fp)
   130 		{
   131 			break;
   132 		}
   133 		fclose(fp);
   134 		i++;
   135 	}
   136 	m_NrmFileName.assign(_filename);
   137 
   138 	FILE *fp = fopen(m_NrmFileName.c_str(), "w");
   139 	if (!fp)
   140 	{
   141 		g_SMAPI->ConPrint("[SM] Unexpected fatal logging error. SourceMod logging disabled.\n");
   142 		m_Active = false;
   143 		return;
   144 	} else {
   145 		char date[32];
   146 		strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
   147 		fprintf(fp, "L %s: SourceMod log file started (file \"L%02d%02d%03d.log\") (Version \"%s\")\n", date, curtime->tm_mon + 1, curtime->tm_mday, i, SVN_FULL_VERSION);
   148 		fclose(fp);
   149 	}
   150 }
   151 
   152 void Logger::_CloseFile()
   153 {
   154 	if (!m_Active)
   155 	{
   156 		return;
   157 	}
   158 
   159 	FILE *fp = NULL;
   160 	if (!m_NrmFileName.empty())
   161 	{
   162 		fp = fopen(m_NrmFileName.c_str(), "r+");
   163 		if (fp)
   164 		{
   165 			fseek(fp, 0, SEEK_END);
   166 			LogMessage("Log file closed.");
   167 			fclose(fp);
   168 		}
   169 		m_NrmFileName.clear();
   170 	}
   171 
   172 	if (!m_ErrMapStart)
   173 	{
   174 		return;
   175 	}
   176 	fp = fopen(m_ErrFileName.c_str(), "r+");
   177 	if (fp)
   178 	{
   179 		fseek(fp, 0, SEEK_END);
   180 		LogError("Error log file session closed.");
   181 		fclose(fp);
   182 	}
   183 	m_ErrFileName.clear();
   184 }
   185 
   186 void Logger::InitLogger(LoggingMode mode)
   187 {
   188 	m_Mode = mode;
   189 	m_Active = m_InitialState;
   190 
   191 	time_t t;
   192 	time(&t);
   193 	tm *curtime = localtime(&t);
   194 	m_CurDay = curtime->tm_mday;
   195 
   196 	char _filename[256];
   197 	g_SourceMod.BuildPath(Path_SM, _filename, sizeof(_filename), "logs/errors_%04d%02d%02d.log", curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday);
   198 	m_ErrFileName.assign(_filename);
   199 
   200 	switch (m_Mode)
   201 	{
   202 	case LoggingMode_PerMap:
   203 		{
   204 			if (!m_Active)
   205 			{
   206 				m_DelayedStart = true;
   207 			}
   208 			break;
   209 		}
   210 	case LoggingMode_Daily:
   211 		{
   212 			g_SourceMod.BuildPath(Path_SM, _filename, sizeof(_filename), "logs/L%04d%02d%02d.log", curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday);
   213 			m_NrmFileName.assign(_filename);
   214 			m_DailyPrintHdr = true;
   215 			break;
   216 		}
   217 	default:
   218 		{
   219 			/* do nothing... */
   220 			break;
   221 		}
   222 	}
   223 }
   224 
   225 void Logger::CloseLogger()
   226 {
   227 	_CloseFile();
   228 }
   229 
   230 void Logger::LogMessage(const char *vafmt, ...)
   231 {
   232 	if (!m_Active)
   233 	{
   234 		return;
   235 	}
   236 
   237 	if (m_Mode == LoggingMode_Game)
   238 	{
   239 		va_list ap;
   240 		va_start(ap, vafmt);
   241 		_PrintToGameLog(vafmt, ap);
   242 		va_end(ap);
   243 		return;
   244 	}
   245 
   246 	if (m_DelayedStart)
   247 	{
   248 		m_DelayedStart = false;
   249 		_NewMapFile();
   250 	}
   251 
   252 	char msg[3072];
   253 	va_list ap;
   254 	va_start(ap, vafmt);
   255 	vsnprintf(msg, sizeof(msg), vafmt, ap);
   256 	va_end(ap);
   257 
   258 	char date[32];
   259 	time_t t;
   260 	time(&t);
   261 	tm *curtime = localtime(&t);
   262 	strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
   263 
   264 	FILE *fp = NULL;
   265 	if (m_Mode == LoggingMode_PerMap)
   266 	{
   267 		fp = fopen(m_NrmFileName.c_str(), "a+");
   268 		if (!fp)
   269 		{
   270 			_NewMapFile();
   271 			fp = fopen(m_NrmFileName.c_str(), "a+");
   272 			if (!fp)
   273 			{
   274 				goto print_error;
   275 			}
   276 		}
   277 	} else {
   278 		if (m_CurDay != curtime->tm_mday)
   279 		{
   280 			char _filename[256];
   281 			g_SourceMod.BuildPath(Path_SM, _filename, sizeof(_filename), "logs/L%04d%02d%02d.log", curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday);
   282 			m_NrmFileName.assign(_filename);
   283 			m_CurDay = curtime->tm_mday;
   284 			m_DailyPrintHdr = true;
   285 		}
   286 		fp = fopen(m_NrmFileName.c_str(), "a+");
   287 	}
   288 
   289 	if (fp)
   290 	{
   291 		if (m_DailyPrintHdr)
   292 		{
   293 			m_DailyPrintHdr = false;
   294 			fprintf(fp, "L %s: SourceMod log file session started (file \"L%04d%02d%02d.log\") (Version \"%s\")\n", date, curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday, SVN_FULL_VERSION);
   295 	 	}
   296 		fprintf(fp, "L %s: %s\n", date, msg);
   297 		fclose(fp);
   298 	} else {
   299 		goto print_error;
   300 	}
   301 
   302 	g_SMAPI->ConPrintf("L %s: %s\n", date, msg);
   303 	return;
   304 print_error:
   305 	g_SMAPI->ConPrint("[SM] Unexpected fatal logging error. SourceMod logging disabled.\n");
   306 	m_Active = false;
   307 }
   308 
   309 void Logger::LogError(const char *vafmt, ...)
   310 {
   311 	if (!m_Active)
   312 	{
   313 		return;
   314 	}
   315 
   316 	time_t t;
   317 	time(&t);
   318 	tm *curtime = localtime(&t);
   319 
   320 	char date[32];
   321 	strftime(date, sizeof(date), "%m/%d/%Y - %H:%M:%S", curtime);
   322 
   323 	if (curtime->tm_mday != m_CurDay)
   324 	{
   325 		char _filename[256];
   326 		g_SourceMod.BuildPath(Path_SM, _filename, sizeof(_filename), "logs/errors_%04d%02d%02d.log", curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday);
   327 		m_ErrFileName.assign(_filename);
   328 		m_CurDay = curtime->tm_mday;
   329 		m_ErrMapStart = false;
   330 	}
   331 
   332 	char msg[3072];
   333 	va_list ap;
   334 	va_start(ap, vafmt);
   335 	vsnprintf(msg, sizeof(msg), vafmt, ap);
   336 	va_end(ap);
   337 
   338 	FILE *fp = fopen(m_ErrFileName.c_str(), "a+");
   339 	if (fp)
   340 	{
   341 		if (!m_ErrMapStart)
   342 		{
   343 			fprintf(fp, "L %s: SourceMod error session started\n", date);
   344 			fprintf(fp, "L %s: Info (map \"%s\") (file \"errors_%04d%02d%02d.log\")\n", date, m_CurMapName.c_str(), curtime->tm_year + 1900, curtime->tm_mon + 1, curtime->tm_mday);
   345 			m_ErrMapStart = true;
   346 		}
   347 		fprintf(fp, "L %s: %s\n", date, msg);
   348 		fclose(fp);
   349 	} else {
   350 		g_SMAPI->ConPrint("[SM] Unexpected fatal logging error. SourceMod logging disabled.\n");
   351 		m_Active = false;
   352 		return;
   353 	}
   354 
   355 	g_SMAPI->ConPrintf("L %s: %s\n", date, msg);
   356 }
   357 
   358 void Logger::MapChange(const char *mapname)
   359 {
   360 	m_CurMapName.assign(mapname);
   361 
   362 	switch (m_Mode)
   363 	{
   364 	case LoggingMode_Daily:
   365 		{
   366 			LogMessage("-------- Mapchange to %s --------", mapname);
   367 			break;
   368 		}
   369 	case LoggingMode_PerMap:
   370 		{
   371 			_NewMapFile();
   372 			break;
   373 		}
   374 	default:
   375 		{
   376 			/* Do nothing... */
   377 			break;
   378 		}
   379 	}
   380 
   381 	if (m_ErrMapStart)
   382 	{
   383 		LogError("Error log file session closed.");
   384 	}
   385 	m_ErrMapStart = false;
   386 }
   387 
   388 void Logger::_PrintToGameLog(const char *fmt, va_list ap)
   389 {
   390 	char msg[3072];
   391 	size_t len;
   392 
   393 	len = vsnprintf(msg, sizeof(msg)-2, fmt, ap);
   394 	len = (len >= sizeof(msg)) ? (sizeof(msg) - 2) : len;
   395 
   396 	msg[len++] = '\n';
   397 	msg[len] = '\0';
   398 
   399 	engine->LogPrint(msg);
   400 }
   401 
   402 const char *Logger::GetLogFileName(LogType type) const
   403 {
   404 	switch (type)
   405 	{
   406 	case LogType_Normal:
   407 		{
   408 			return m_NrmFileName.c_str();
   409 		}
   410 	case LogType_Error:
   411 		{
   412 			return m_ErrFileName.c_str();
   413 		}
   414 	default:
   415 		{
   416 			return "";
   417 		}
   418 	}
   419 }
   420 
   421 LoggingMode Logger::GetLoggingMode() const
   422 {
   423 	return m_Mode;
   424 }
   425 
   426 void Logger::EnableLogging()
   427 {
   428 	if (m_Active)
   429 	{
   430 		return;
   431 	}
   432 	m_Active = true;
   433 	LogMessage("[SM] Logging enabled manually by user.");
   434 }
   435 
   436 void Logger::DisableLogging()
   437 {
   438 	if (!m_Active)
   439 	{
   440 		return;
   441 	}
   442 	LogMessage("[SM] Logging disabled manually by user.");
   443 	m_Active = false;
   444 }
   445 
   446 void Logger::LogFatal(const char *msg, ...)
   447 {
   448 	/* :TODO: make this print all pretty-like
   449 	 * In fact, the pretty log printing function should be abstracted. 
   450 	 * It's already implemented twice which is bad.
   451 	 */
   452 
   453 	char path[PLATFORM_MAX_PATH];
   454 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "sourcemod_fatal.log");
   455 	FILE *fp = fopen(path, "at");
   456 	if (!fp)
   457 	{
   458 		/* We're just doomed, aren't we... */
   459 		return;
   460 	}
   461 
   462 	va_list ap;
   463 	va_start(ap, msg);
   464 	vfprintf(fp, msg, ap);
   465 	va_end(ap);
   466 
   467 	fputs("\n", fp);
   468 	
   469 	fclose(fp);
   470 }