Log.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. //
  2. // Copyright (c) 2008-2022 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Container/Str.h"
  24. #include "../Core/Context.h"
  25. #include "../Core/CoreEvents.h"
  26. #include "../Core/ProcessUtils.h"
  27. #include "../Core/Thread.h"
  28. #include "../Core/Timer.h"
  29. #include "../IO/File.h"
  30. #include "../IO/IOEvents.h"
  31. #include "../IO/Log.h"
  32. #include <cstdio>
  33. #ifdef __ANDROID__
  34. #include <android/log.h>
  35. #endif
  36. #if defined(IOS) || defined(TVOS)
  37. extern "C" void SDL_IOS_LogMessage(const char* message);
  38. #endif
  39. #include "../DebugNew.h"
  40. namespace Urho3D
  41. {
  42. const char* logLevelPrefixes[] =
  43. {
  44. "TRACE",
  45. "DEBUG",
  46. "INFO",
  47. "WARNING",
  48. "ERROR",
  49. nullptr
  50. };
  51. static Log* logInstance = nullptr;
  52. static bool threadErrorDisplayed = false;
  53. Log::Log(Context* context) :
  54. Object(context),
  55. #ifdef _DEBUG
  56. level_(LOG_DEBUG),
  57. #else
  58. level_(LOG_INFO),
  59. #endif
  60. timeStamp_(true),
  61. inWrite_(false),
  62. quiet_(false)
  63. {
  64. logInstance = this;
  65. SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Log, HandleEndFrame));
  66. }
  67. Log::~Log()
  68. {
  69. logInstance = nullptr;
  70. }
  71. void Log::Open(const String& fileName)
  72. {
  73. #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS)
  74. if (fileName.Empty())
  75. return;
  76. if (logFile_ && logFile_->IsOpen())
  77. {
  78. if (logFile_->GetName() == fileName)
  79. return;
  80. else
  81. Close();
  82. }
  83. logFile_ = new File(context_);
  84. if (logFile_->Open(fileName, FILE_WRITE))
  85. Write(LOG_INFO, "Opened log file " + fileName);
  86. else
  87. {
  88. logFile_.Reset();
  89. Write(LOG_ERROR, "Failed to create log file " + fileName);
  90. }
  91. #endif
  92. }
  93. void Log::Close()
  94. {
  95. #if !defined(__ANDROID__) && !defined(IOS) && !defined(TVOS)
  96. if (logFile_ && logFile_->IsOpen())
  97. {
  98. logFile_->Close();
  99. logFile_.Reset();
  100. }
  101. #endif
  102. }
  103. void Log::SetLevel(int level)
  104. {
  105. if (level < LOG_TRACE || level > LOG_NONE)
  106. {
  107. URHO3D_LOGERRORF("Attempted to set erroneous log level %d", level);
  108. return;
  109. }
  110. level_ = level;
  111. }
  112. void Log::SetTimeStamp(bool enable)
  113. {
  114. timeStamp_ = enable;
  115. }
  116. void Log::SetQuiet(bool quiet)
  117. {
  118. quiet_ = quiet;
  119. }
  120. void Log::WriteFormat(int level, const char* format, ...)
  121. {
  122. if (!logInstance || logInstance->level_ > level)
  123. return;
  124. // Forward to normal Write() after formatting the input
  125. String message;
  126. va_list args;
  127. va_start(args, format);
  128. message.AppendWithFormatArgs(format, args);
  129. va_end(args);
  130. Write(level, message);
  131. }
  132. void Log::Write(int level, const String& message)
  133. {
  134. // Special case for LOG_RAW level
  135. if (level == LOG_RAW)
  136. {
  137. WriteRaw(message, false);
  138. return;
  139. }
  140. // No-op if illegal level
  141. if (level < LOG_TRACE || level >= LOG_NONE)
  142. return;
  143. // If not in the main thread, store message for later processing
  144. if (!Thread::IsMainThread())
  145. {
  146. if (logInstance)
  147. {
  148. MutexLock lock(logInstance->logMutex_);
  149. logInstance->threadMessages_.Push(StoredLogMessage(message, level, false));
  150. }
  151. return;
  152. }
  153. // Do not log if message level excluded or if currently sending a log event
  154. if (!logInstance || logInstance->level_ > level || logInstance->inWrite_)
  155. return;
  156. String formattedMessage = logLevelPrefixes[level];
  157. formattedMessage += ": " + message;
  158. logInstance->lastMessage_ = message;
  159. if (logInstance->timeStamp_)
  160. formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage;
  161. #if defined(__ANDROID__)
  162. int androidLevel = ANDROID_LOG_VERBOSE + level;
  163. __android_log_print(androidLevel, "Urho3D", "%s", message.CString());
  164. #elif defined(IOS) || defined(TVOS)
  165. SDL_IOS_LogMessage(message.CString());
  166. #else
  167. if (logInstance->quiet_)
  168. {
  169. // If in quiet mode, still print the error message to the standard error stream
  170. if (level == LOG_ERROR)
  171. PrintUnicodeLine(formattedMessage, true);
  172. }
  173. else
  174. PrintUnicodeLine(formattedMessage, level == LOG_ERROR);
  175. #endif
  176. if (logInstance->logFile_)
  177. {
  178. logInstance->logFile_->WriteLine(formattedMessage);
  179. logInstance->logFile_->Flush();
  180. }
  181. logInstance->inWrite_ = true;
  182. using namespace LogMessage;
  183. VariantMap& eventData = logInstance->GetEventDataMap();
  184. eventData[P_MESSAGE] = formattedMessage;
  185. eventData[P_LEVEL] = level;
  186. logInstance->SendEvent(E_LOGMESSAGE, eventData);
  187. logInstance->inWrite_ = false;
  188. }
  189. void Log::WriteRaw(const String& message, bool error)
  190. {
  191. // If not in the main thread, store message for later processing
  192. if (!Thread::IsMainThread())
  193. {
  194. if (logInstance)
  195. {
  196. MutexLock lock(logInstance->logMutex_);
  197. logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error));
  198. }
  199. return;
  200. }
  201. // Prevent recursion during log event
  202. if (!logInstance || logInstance->inWrite_)
  203. return;
  204. logInstance->lastMessage_ = message;
  205. #if defined(__ANDROID__)
  206. if (logInstance->quiet_)
  207. {
  208. if (error)
  209. __android_log_print(ANDROID_LOG_ERROR, "Urho3D", "%s", message.CString());
  210. }
  211. else
  212. __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", "%s", message.CString());
  213. #elif defined(IOS) || defined(TVOS)
  214. SDL_IOS_LogMessage(message.CString());
  215. #else
  216. if (logInstance->quiet_)
  217. {
  218. // If in quiet mode, still print the error message to the standard error stream
  219. if (error)
  220. PrintUnicode(message, true);
  221. }
  222. else
  223. PrintUnicode(message, error);
  224. #endif
  225. if (logInstance->logFile_)
  226. {
  227. logInstance->logFile_->Write(message.CString(), message.Length());
  228. logInstance->logFile_->Flush();
  229. }
  230. logInstance->inWrite_ = true;
  231. using namespace LogMessage;
  232. VariantMap& eventData = logInstance->GetEventDataMap();
  233. eventData[P_MESSAGE] = message;
  234. eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO;
  235. logInstance->SendEvent(E_LOGMESSAGE, eventData);
  236. logInstance->inWrite_ = false;
  237. }
  238. void Log::HandleEndFrame(StringHash eventType, VariantMap& eventData)
  239. {
  240. // If the MainThreadID is not valid, processing this loop can potentially be endless
  241. if (!Thread::IsMainThread())
  242. {
  243. if (!threadErrorDisplayed)
  244. {
  245. fprintf(stderr, "Thread::mainThreadID is not setup correctly! Threaded log handling disabled\n");
  246. threadErrorDisplayed = true;
  247. }
  248. return;
  249. }
  250. MutexLock lock(logMutex_);
  251. // Process messages accumulated from other threads (if any)
  252. while (!threadMessages_.Empty())
  253. {
  254. const StoredLogMessage& stored = threadMessages_.Front();
  255. if (stored.level_ != LOG_RAW)
  256. Write(stored.level_, stored.message_);
  257. else
  258. WriteRaw(stored.message_, stored.error_);
  259. threadMessages_.PopFront();
  260. }
  261. }
  262. }