OpenClonk
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
C4Log.cpp
Go to the documentation of this file.
1 /*
2  * OpenClonk, http://www.openclonk.org
3  *
4  * Copyright (c) 1998-2000, Matthes Bender
5  * Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de/
6  * Copyright (c) 2009-2016, The OpenClonk Team and contributors
7  *
8  * Distributed under the terms of the ISC license; see accompanying file
9  * "COPYING" for details.
10  *
11  * "Clonk" is a registered trademark of Matthes Bender, used with permission.
12  * See accompanying file "TRADEMARK" for details.
13  *
14  * To redistribute this file separately, substitute the full license texts
15  * for the above references.
16  */
17 
18 /* Log file handling */
19 
20 #include "C4Include.h"
21 #include "lib/C4Log.h"
22 
23 #include "c4group/C4Components.h"
24 #include "editor/C4Console.h"
25 #include "game/C4GraphicsSystem.h"
26 #include "graphics/C4Shader.h"
27 #include "gui/C4GameLobby.h"
28 #include "lib/C4LogBuf.h"
29 #include "network/C4Network2.h"
30 #include "platform/C4Window.h"
31 #include "script/C4AulDebug.h"
32 
33 #ifdef HAVE_SYS_FILE_H
34 #include <sys/file.h>
35 #endif
36 
37 #if defined(HAVE_SHARE_H) || defined(_WIN32)
38 #include <share.h>
39 #endif
40 
41 FILE *C4LogFile=nullptr;
42 FILE *C4ShaderLogFile = nullptr;
45 
47 
48 bool OpenLog()
49 {
50  // open
51  sLogFileName = C4CFN_Log; int iLog = 2;
52 #ifdef _WIN32
53  while (!(C4LogFile = _fsopen(Config.AtUserDataPath(sLogFileName.getData()), "wt", _SH_DENYWR)))
54 #elif defined(HAVE_SYS_FILE_H)
55  int fd = 0;
56  while (!(fd = open(Config.AtUserDataPath(sLogFileName.getData()), O_WRONLY | O_CREAT, 0644)) || flock(fd, LOCK_EX|LOCK_NB))
57 #else
58  while (!(C4LogFile = fopen(Config.AtUserDataPath(sLogFileName.getData()), "wb")))
59 #endif
60  {
61  // Already locked by another instance?
62 #if !defined(_WIN32) && defined(HAVE_SYS_FILE_H)
63  if (fd) close(fd);
64 #else
65  if (C4LogFile) fclose(C4LogFile);
66 #endif
67  // If the file does not yet exist, the directory is r/o
68  // don't go on then, or we have an infinite loop
69  if (access(Config.AtUserDataPath(sLogFileName.getData()), 0))
70  return false;
71  // try different name
72  sLogFileName.Format(C4CFN_LogEx, iLog++);
73  }
74 #if !defined(_WIN32) && defined(HAVE_SYS_FILE_H)
75  ftruncate(fd, 0);
76  C4LogFile = fdopen(fd, "wb");
77 #endif
78  // save start time
79  time(&C4LogStartTime);
80  return true;
81 }
82 
84 {
85  // shader log in editor mode (only one file)
86  bool success = true;
87  if (C4Shader::IsLogging())
88  {
89 #ifdef _WIN32
90  C4ShaderLogFile = _fsopen(Config.AtUserDataPath(C4CFN_LogShader), "wt", _SH_DENYWR);
91 #elif defined(HAVE_SYS_FILE_H)
93  if (C4ShaderLogFile && flock(fileno(C4ShaderLogFile), LOCK_EX | LOCK_NB) != 0)
94  {
95  DebugLog("Couldn't lock shader log file, closing.");
96  fclose(C4ShaderLogFile);
97  C4ShaderLogFile = nullptr;
98  }
99 #else
100  C4ShaderLogFile = fopen(Config.AtUserDataPath(C4CFN_LogShader), "wb");
101 #endif
102  if (!C4ShaderLogFile) success = false;
103  }
104  return success;
105 }
106 
107 bool CloseLog()
108 {
109  // close
110  if (C4ShaderLogFile) fclose(C4ShaderLogFile); C4ShaderLogFile = nullptr;
111  if (C4LogFile) fclose(C4LogFile); C4LogFile = nullptr;
112  // ok
113  return true;
114 }
115 
116 int GetLogFD()
117 {
118  if (C4LogFile)
119  return fileno(C4LogFile);
120  else
121  return -1;
122 }
123 
124 bool LogSilent(const char *szMessage, bool fConsole)
125 {
126  if (!Application.AssertMainThread()) return false;
127  // security
128  if (!szMessage) return false;
129 
130  // add timestamp
131  time_t timenow; time(&timenow);
132  StdStrBuf TimeMessage;
133  TimeMessage.SetLength(11 + SLen(szMessage) + 1);
134  strftime(TimeMessage.getMData(), 11 + 1, "[%H:%M:%S] ", localtime(&timenow));
135 
136  // output until all data is written
137  const char *pSrc = szMessage;
138  do
139  {
140  // timestamp will always be that length
141  char *pDest = TimeMessage.getMData() + 11;
142 
143  // copy rest of message, skip tags
144  C4Markup Markup(false);
145  while (*pSrc)
146  {
147  Markup.SkipTags(&pSrc);
148  // break on crlf
149  while (*pSrc == '\r') pSrc++;
150  if (*pSrc == '\n') { pSrc++; break; }
151  // copy otherwise
152  if (*pSrc) *pDest++ = *pSrc++;
153  }
154  *pDest++='\n'; *pDest = '\0';
155 
156  // Save into log file
157  if (C4LogFile)
158  {
159  fputs(TimeMessage.getData(),C4LogFile);
160  fflush(C4LogFile);
161  }
162 
163  // Save into record log file, if available
164  if(Control.GetRecord())
165  {
166  Control.GetRecord()->GetLogFile()->Write(TimeMessage.getData(), TimeMessage.getLength());
167  #ifdef IMMEDIATEREC
169  #endif
170  }
171 
172 
173  // Write to console
174  if (fConsole)
175  {
176 #if defined(_WIN32)
177  // debug: output to VC console when running with debugger
178  // Otherwise, print to stdout to allow capturing the log.
179  if (IsDebuggerPresent())
180  OutputDebugString(TimeMessage.GetWideChar());
181  else
182 #endif
183  {
184  fputs(TimeMessage.getData(),stdout);
185  fflush(stdout);
186  }
187  }
188 
189  }
190  while (*pSrc);
191 
192  return true;
193 }
194 
195 bool LogSilent(const char *szMessage)
196 {
197  return LogSilent(szMessage, false);
198 }
199 
200 int iDisableLog = 0;
201 
202 bool Log(const char *szMessage)
203 {
204  if (!Application.AssertMainThread()) return false;
205  if (iDisableLog) return true;
206  // security
207  if (!szMessage) return false;
208 
209 #ifndef NOAULDEBUG
210  // Pass on to debugger
211  if (C4AulDebug *pDebug = C4AulDebug::GetDebugger())
212  pDebug->OnLog(szMessage);
213 #endif
214  // Pass on to console
215  Console.Out(szMessage);
216  // pass on to lobby
218  if (pLobby) pLobby->OnLog(szMessage);
219 
220  // Add message to log buffer
221  bool fNotifyMsgBoard = false;
223  {
224  ::GraphicsSystem.MessageBoard->AddLog(szMessage);
225  fNotifyMsgBoard = true;
226  }
227 
228  // log
229  LogSilent(szMessage, true);
230 
231  // Notify message board
232  if (fNotifyMsgBoard) ::GraphicsSystem.MessageBoard->LogNotify();
233 
234  return true;
235 }
236 
237 bool LogFatal(const char *szMessage)
238 {
239  if (!szMessage) szMessage = "(null)";
240  // add to fatal error message stack - if not already in there (avoid duplication)
241  if (!SSearch(sFatalError.getData(), szMessage))
242  {
243  if (!sFatalError.isNull()) sFatalError.AppendChar('|');
244  sFatalError.Append(szMessage);
245  }
246  // write to log - note that Log might overwrite a static buffer also used in szMessage
247  return !!Log(FormatString(LoadResStr("IDS_ERR_FATAL"), szMessage).getData());
248 }
249 
251 {
252  sFatalError.Clear();
253 }
254 
255 const char *GetFatalError()
256 {
257  return sFatalError.getData();
258 }
259 
260 bool LogF(const char *strMessage, ...)
261 {
262  va_list args; va_start(args, strMessage);
263  // Compose formatted message
264  StdStrBuf Buf;
265  Buf.FormatV(strMessage, args);
266  // Log
267  return Log(Buf.getData());
268 }
269 
270 bool LogSilentF(const char *strMessage, ...)
271 {
272  va_list args; va_start(args, strMessage);
273  // Compose formatted message
274  StdStrBuf Buf;
275  Buf.FormatV(strMessage, args);
276  // Log
277  return LogSilent(Buf.getData());
278 }
279 
280 bool DebugLog(const char *strMessage)
281 {
282  if (Game.DebugMode)
283  return Log(strMessage);
284  else
285  return LogSilent(strMessage);
286 }
287 
288 bool DebugLogF(const char *strMessage ...)
289 {
290  va_list args; va_start(args, strMessage);
291  StdStrBuf Buf;
292  Buf.FormatV(strMessage, args);
293  return DebugLog(Buf.getData());
294 }
295 
296 size_t GetLogPos()
297 {
298  // get current log position
299  return FileSize(sLogFileName.getData());
300 }
301 
302 bool GetLogSection(size_t iStart, size_t iLength, StdStrBuf &rsOut)
303 {
304  if (!iLength) { rsOut.Clear(); return true; }
305  // read section from log file
306  StdStrBuf BufOrig;
307  if (!BufOrig.LoadFromFile(sLogFileName.getData())) return false;
308  char *szBuf = BufOrig.getMData();
309  size_t iSize = BufOrig.getSize(); // size excluding terminator
310  // reduce to desired buffer section
311  if (iStart > iSize) iStart = iSize;
312  if (iStart + iLength > iSize) iLength = iSize - iStart;
313  szBuf += iStart; szBuf[iLength] = '\0';
314  // strip timestamps; convert linebreaks to Clonk-linebreaks '|'
315  char *szPosWrite=szBuf; const char *szPosRead=szBuf;
316  while (*szPosRead)
317  {
318  // skip timestamp
319  if (*szPosRead == '[')
320  while (*szPosRead && *szPosRead != ']') { --iSize; ++szPosRead; }
321  // skip whitespace behind timestamp
322  if (!*szPosRead) break;
323  szPosRead++;
324  // copy data until linebreak
325  size_t iLen=0;
326  while (*szPosRead && *szPosRead != 0x0d && *szPosRead != 0x0a)
327  { ++szPosRead; ++iLen; }
328  if (iLen && szPosRead-iLen != szPosWrite) memmove(szPosWrite, szPosRead-iLen, iLen);
329  szPosWrite += iLen;
330  // skip additional linebreaks
331  while (*szPosRead == 0x0d || *szPosRead == 0x0a) ++szPosRead;
332  // write a Clonk-linebreak
333  if (*szPosRead) *szPosWrite++ = '|';
334  }
335  // done; create string buffer from data
336  rsOut.Copy(szBuf, szPosWrite - szBuf);
337  // done, success
338  return true;
339 }
340 
341 bool ShaderLog(const char *szMessage)
342 {
343  // security
344  if (!C4ShaderLogFile) return false;
345  if (!Application.AssertMainThread()) return false;
346  if (!szMessage) return false;
347  // output into shader log file
348  fputs(szMessage, C4ShaderLogFile);
349  fputs("\n", C4ShaderLogFile);
350  fflush(C4ShaderLogFile);
351  return true;
352 }
353 
354 bool ShaderLogF(const char *strMessage ...)
355 {
356  va_list args; va_start(args, strMessage);
357  StdStrBuf Buf;
358  Buf.FormatV(strMessage, args);
359  return ShaderLog(Buf.getData());
360 }
const char * getData() const
Definition: StdBuf.h:442
bool AssertMainThread()
Definition: C4App.h:123
FILE * C4ShaderLogFile
Definition: C4Log.cpp:42
bool ShaderLog(const char *szMessage)
Definition: C4Log.cpp:341
class C4GameLobby::MainDlg * GetLobby() const
Definition: C4Network2.h:216
C4Config Config
Definition: C4Config.cpp:833
time_t C4LogStartTime
Definition: C4Log.cpp:43
C4Console Console
Definition: C4Globals.cpp:45
bool LogSilent(const char *szMessage, bool fConsole)
Definition: C4Log.cpp:124
CStdFile * GetLogFile()
Definition: C4Record.h:278
C4Game Game
Definition: C4Globals.cpp:52
StdStrBuf sLogFileName
Definition: C4Log.cpp:44
StdStrBuf sFatalError
Definition: C4Log.cpp:46
void Clear()
Definition: StdBuf.h:466
bool DebugLog(const char *strMessage)
Definition: C4Log.cpp:280
const char * SSearch(const char *szString, const char *szIndex)
Definition: Standard.cpp:363
bool OpenExtraLogs()
Definition: C4Log.cpp:83
void Format(const char *szFmt,...) GNUC_FORMAT_ATTRIBUTE_O
Definition: StdBuf.cpp:174
C4Record * GetRecord()
size_t SLen(const char *sptr)
Definition: Standard.h:74
void OnLog(const char *szLogMsg, DWORD dwClr=C4GUI_LogFontClr)
const char * LoadResStr(const char *id)
Definition: C4Language.h:83
char * getMData()
Definition: StdBuf.h:443
void AppendChar(char cChar)
Definition: StdBuf.h:588
bool LoadFromFile(const char *szFile)
Definition: StdBuf.cpp:73
int GetLogFD()
Definition: C4Log.cpp:116
size_t FileSize(const char *fname)
bool Write(const void *pBuffer, int iSize)
Definition: CStdFile.cpp:240
bool LogSilentF(const char *strMessage,...)
Definition: C4Log.cpp:270
bool SkipTags(const char **ppText)
Definition: C4Markup.cpp:105
bool DebugLogF(const char *strMessage...)
Definition: C4Log.cpp:288
static bool IsLogging()
Definition: C4Shader.cpp:663
C4Network2 Network
Definition: C4Globals.cpp:53
static C4AulDebug * GetDebugger()
Definition: C4AulDebug.h:31
C4GameControl Control
C4GraphicsSystem GraphicsSystem
Definition: C4Globals.cpp:51
#define C4CFN_Log
Definition: C4Components.h:141
void Append(const char *pnData, size_t iChars)
Definition: StdBuf.h:519
void Out(const char *message)
Definition: C4Console.cpp:684
bool LogFatal(const char *szMessage)
Definition: C4Log.cpp:237
size_t GetLogPos()
Definition: C4Log.cpp:296
bool GetLogSection(size_t iStart, size_t iLength, StdStrBuf &rsOut)
Definition: C4Log.cpp:302
bool OpenLog()
Definition: C4Log.cpp:48
size_t getSize() const
Definition: StdBuf.h:444
const char * GetFatalError()
Definition: C4Log.cpp:255
bool isNull() const
Definition: StdBuf.h:441
std::unique_ptr< C4MessageBoard > MessageBoard
const char * AtUserDataPath(const char *szFilename)
Definition: C4Config.cpp:526
bool ShaderLogF(const char *strMessage...)
Definition: C4Log.cpp:354
FILE * C4LogFile
Definition: C4Log.cpp:41
bool Log(const char *szMessage)
Definition: C4Log.cpp:202
int iDisableLog
Definition: C4Log.cpp:200
void FormatV(const char *szFmt, va_list args)
Definition: StdBuf.cpp:182
#define C4CFN_LogEx
Definition: C4Components.h:142
size_t getLength() const
Definition: StdBuf.h:445
void SetLength(size_t iLength)
Definition: StdBuf.h:509
void ResetFatalError()
Definition: C4Log.cpp:250
bool CloseLog()
Definition: C4Log.cpp:107
bool LogF(const char *strMessage,...)
Definition: C4Log.cpp:260
void Copy()
Definition: StdBuf.h:467
bool Flush()
Definition: CStdFile.h:70
#define C4CFN_LogShader
Definition: C4Components.h:143
C4Application Application
Definition: C4Globals.cpp:44
bool DebugMode
Definition: C4Game.h:144
int iSize
Definition: TstC4NetIO.cpp:32
StdStrBuf FormatString(const char *szFmt,...)
Definition: StdBuf.cpp:270