diff --git a/Library/ConfigParser.cpp b/Library/ConfigParser.cpp index a530416e..1d9e7bbe 100644 --- a/Library/ConfigParser.cpp +++ b/Library/ConfigParser.cpp @@ -722,7 +722,7 @@ const std::wstring& CConfigParser::ReadString(LPCTSTR section, LPCTSTR key, LPCT { const std::wstring& strStyleValue = GetValue((*iter), strKey, strDefault); - //LogWithArgs(LOG_DEBUG, L"StyleTemplate: [%s] %s (from [%s]) : strDefault=%s (0x%p), strStyleValue=%s (0x%p)", + //CLogger_DebugF(L"StyleTemplate: [%s] %s (from [%s]) : strDefault=%s (0x%p), strStyleValue=%s (0x%p)", // section, key, (*iter).c_str(), strDefault.c_str(), &strDefault, strStyleValue.c_str(), &strStyleValue); if (&strStyleValue != &strDefault) @@ -850,7 +850,7 @@ int CConfigParser::ReadInt(LPCTSTR section, LPCTSTR key, int defValue) return (int)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); + CLogger_ErrorF(L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); } else if (*string) { @@ -882,7 +882,7 @@ uint32_t CConfigParser::ReadUInt(LPCTSTR section, LPCTSTR key, uint32_t defValue return (uint32_t)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); + CLogger_ErrorF(L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); } else if (*string) { @@ -914,7 +914,7 @@ uint64_t CConfigParser::ReadUInt64(LPCTSTR section, LPCTSTR key, uint64_t defVal return (uint64_t)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); + CLogger_ErrorF(L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); } else if (*string) { @@ -946,7 +946,7 @@ double CConfigParser::ReadFloat(LPCTSTR section, LPCTSTR key, double defValue) return value; } - LogWithArgs(LOG_ERROR, L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); + CLogger_ErrorF(L"Formula: %s in key \"%s\" in [%s]", errMsg, key, section); } else if (*string) { @@ -972,7 +972,7 @@ bool CConfigParser::ParseFormula(const std::wstring& formula, double* resultValu const WCHAR* errMsg = MathParser::CheckedParse(string, resultValue); if (errMsg != NULL) { - LogWithArgs(LOG_ERROR, L"Formula: %s: %s", errMsg, string); + CLogger_ErrorF(L"Formula: %s: %s", errMsg, string); return false; } @@ -1069,7 +1069,7 @@ double CConfigParser::ParseDouble(LPCTSTR string, double defValue) return value; } - LogWithArgs(LOG_ERROR, L"Formula: %s: %s", errMsg, string); + CLogger_ErrorF(L"Formula: %s: %s", errMsg, string); } else if (*string) { @@ -1102,7 +1102,7 @@ int CConfigParser::ParseInt(LPCTSTR string, int defValue) return (int)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s: %s", errMsg, string); + CLogger_ErrorF(L"Formula: %s: %s", errMsg, string); } else if (*string) { @@ -1135,7 +1135,7 @@ uint32_t CConfigParser::ParseUInt(LPCTSTR string, uint32_t defValue) return (uint32_t)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s: %s", errMsg, string); + CLogger_ErrorF(L"Formula: %s: %s", errMsg, string); } else if (*string) { @@ -1168,7 +1168,7 @@ uint64_t CConfigParser::ParseUInt64(LPCTSTR string, uint64_t defValue) return (uint64_t)dblValue; } - LogWithArgs(LOG_ERROR, L"Formula: %s: %s", errMsg, string); + CLogger_ErrorF(L"Formula: %s: %s", errMsg, string); } else if (*string) { @@ -1295,7 +1295,7 @@ void CConfigParser::ReadIniFile(const std::wstring& iniFile, LPCTSTR skinSection // Verify whether the file exists if (_waccess(iniFile.c_str(), 0) == -1) { - LogWithArgs(LOG_ERROR, L"Unable to read file: %s", iniFile.c_str()); + CLogger_ErrorF(L"Unable to read file: %s", iniFile.c_str()); return; } @@ -1305,11 +1305,11 @@ void CConfigParser::ReadIniFile(const std::wstring& iniFile, LPCTSTR skinSection if (temporary) { - if (Rainmeter->GetDebug()) LogWithArgs(LOG_DEBUG, L"Reading file: %s (Temp: %s)", iniFile.c_str(), iniRead.c_str()); + if (Rainmeter->GetDebug()) CLogger_DebugF(L"Reading file: %s (Temp: %s)", iniFile.c_str(), iniRead.c_str()); } else { - if (Rainmeter->GetDebug()) LogWithArgs(LOG_DEBUG, L"Reading file: %s", iniFile.c_str()); + if (Rainmeter->GetDebug()) CLogger_DebugF(L"Reading file: %s", iniFile.c_str()); iniRead = iniFile; } @@ -1513,7 +1513,7 @@ void CConfigParser::ReadIniFile(const std::wstring& iniFile, LPCTSTR skinSection */ void CConfigParser::SetValue(const std::wstring& strSection, const std::wstring& strKey, const std::wstring& strValue) { - // LogWithArgs(LOG_DEBUG, L"[%s] %s=%s (size: %i)", strSection.c_str(), strKey.c_str(), strValue.c_str(), (int)m_Values.size()); + // CLogger_DebugF(L"[%s] %s=%s (size: %i)", strSection.c_str(), strKey.c_str(), strValue.c_str(), (int)m_Values.size()); std::wstring strTmp; strTmp.reserve(strSection.size() + 1 + strKey.size()); diff --git a/Library/DialogAbout.cpp b/Library/DialogAbout.cpp index 20b6bf34..edfd53fc 100644 --- a/Library/DialogAbout.cpp +++ b/Library/DialogAbout.cpp @@ -114,7 +114,7 @@ void CDialogAbout::ShowAboutLog() } } -void CDialogAbout::AddLogItem(int level, LPCWSTR time, LPCWSTR message) +void CDialogAbout::AddLogItem(CLogger::Level level, LPCWSTR time, LPCWSTR message) { if (c_Dialog && c_Dialog->m_TabLog.IsInitialized()) { @@ -409,10 +409,9 @@ void CDialogAbout::CTabLog::Initialize() ListView_InsertColumn(item, 2, &lvc); // Add stored entires - std::list::const_iterator iter = Rainmeter->GetAboutLogData().begin(); - for ( ; iter != Rainmeter->GetAboutLogData().end(); ++iter) + for (const auto& entry : CLogger::GetInstance().GetEntries()) { - AddItem((*iter).level, (*iter).timestamp.c_str(), (*iter).message.c_str()); + AddItem(entry.level, entry.timestamp.c_str(), entry.message.c_str()); } item = GetControl(Id_ErrorCheckBox); @@ -467,7 +466,7 @@ void CDialogAbout::CTabLog::Resize(int w, int h) ** Adds item to log. ** */ -void CDialogAbout::CTabLog::AddItem(int level, LPCWSTR time, LPCWSTR message) +void CDialogAbout::CTabLog::AddItem(CLogger::Level level, LPCWSTR time, LPCWSTR message) { WCHAR buffer[32]; LVITEM vitem; @@ -479,25 +478,25 @@ void CDialogAbout::CTabLog::AddItem(int level, LPCWSTR time, LPCWSTR message) switch (level) { - case LOG_ERROR: + case CLogger::Level::Error: if (!m_Error) return; item = GetControl(Id_ErrorCheckBox); vitem.iImage = 0; break; - case LOG_WARNING: + case CLogger::Level::Warning: if (!m_Warning) return; item = GetControl(Id_WarningCheckBox); vitem.iImage = 1; break; - case LOG_NOTICE: + case CLogger::Level::Notice: if (!m_Notice) return; item = GetControl(Id_NoticeCheckBox); vitem.iImage = 2; break; - case LOG_DEBUG: + case CLogger::Level::Debug: if (!m_Debug) return; item = GetControl(Id_DebugCheckBox); vitem.iImage = I_IMAGENONE; @@ -1084,7 +1083,7 @@ void CDialogAbout::CTabPlugins::Initialize() } else { - LogWithArgs(LOG_ERROR, L"Unable to load plugin: %s (%u)", tmpSz.c_str(), err); + CLogger_ErrorF(L"Unable to load plugin: %s (%u)", tmpSz.c_str(), err); } } while (FindNextFile(hSearch, &fd)); diff --git a/Library/DialogAbout.h b/Library/DialogAbout.h index 1e6400ef..a244caf3 100644 --- a/Library/DialogAbout.h +++ b/Library/DialogAbout.h @@ -33,7 +33,7 @@ public: static void Open(const WCHAR* name); static void ShowAboutLog(); - static void AddLogItem(int level, LPCWSTR time, LPCWSTR message); + static void AddLogItem(CLogger::Level level, LPCWSTR time, LPCWSTR message); static void UpdateSkins(); static void UpdateMeasures(CMeterWindow* meterWindow); @@ -63,7 +63,7 @@ private: virtual void Initialize(); virtual void Resize(int w, int h); - void AddItem(int level, LPCWSTR time, LPCWSTR message); + void AddItem(CLogger::Level level, LPCWSTR time, LPCWSTR message); protected: virtual INT_PTR HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); diff --git a/Library/DialogManage.cpp b/Library/DialogManage.cpp index 69e576da..2bbdfd6c 100644 --- a/Library/DialogManage.cpp +++ b/Library/DialogManage.cpp @@ -1900,10 +1900,10 @@ void CDialogManage::CTabSettings::Initialize() Button_SetCheck(GetControl(Id_CheckForUpdatesCheckBox), !Rainmeter->GetDisableVersionCheck()); Button_SetCheck(GetControl(Id_LockSkinsCheckBox), Rainmeter->GetDisableDragging()); - Button_SetCheck(GetControl(Id_LogToFileCheckBox), Rainmeter->GetLogging()); + Button_SetCheck(GetControl(Id_LogToFileCheckBox), CLogger::GetInstance().IsLogToFile()); Button_SetCheck(GetControl(Id_VerboseLoggingCheckbox), Rainmeter->GetDebug()); - BOOL isLogFile = (_waccess(Rainmeter->GetLogFile().c_str(), 0) != -1); + BOOL isLogFile = (_waccess(CLogger::GetInstance().GetLogFilePath().c_str(), 0) != -1); EnableWindow(GetControl(Id_ShowLogFileButton), isLogFile); EnableWindow(GetControl(Id_DeleteLogFileButton), isLogFile); @@ -1998,8 +1998,8 @@ INT_PTR CDialogManage::CTabSettings::OnCommand(WPARAM wParam, LPARAM lParam) break; case Id_DeleteLogFileButton: - Rainmeter->DeleteLogFile(); - if (_waccess(Rainmeter->GetLogFile().c_str(), 0) == -1) + CLogger::GetInstance().DeleteLogFile(); + if (_waccess(CLogger::GetInstance().GetLogFilePath().c_str(), 0) == -1) { Button_SetCheck(GetControl(Id_LogToFileCheckBox), BST_UNCHECKED); EnableWindow(GetControl(Id_ShowLogFileButton), FALSE); @@ -2008,14 +2008,14 @@ INT_PTR CDialogManage::CTabSettings::OnCommand(WPARAM wParam, LPARAM lParam) break; case Id_LogToFileCheckBox: - if (Rainmeter->GetLogging()) + if (CLogger::GetInstance().IsLogToFile()) { - Rainmeter->StopLogging(); + CLogger::GetInstance().StopLogFile(); } else { - Rainmeter->StartLogging(); - if (_waccess(Rainmeter->GetLogFile().c_str(), 0) != -1) + CLogger::GetInstance().StartLogFile(); + if (_waccess(CLogger::GetInstance().GetLogFilePath().c_str(), 0) != -1) { EnableWindow(GetControl(Id_ShowLogFileButton), TRUE); EnableWindow(GetControl(Id_DeleteLogFileButton), TRUE); diff --git a/Library/Export.cpp b/Library/Export.cpp index e4b58e2a..a34babe1 100644 --- a/Library/Export.cpp +++ b/Library/Export.cpp @@ -111,10 +111,10 @@ BOOL LSLog(int nLevel, LPCWSTR unused, LPCWSTR pszMessage) { NULLCHECK(pszMessage); - // Ignore LOG_DEBUG messages from plugins unless in debug mode - if (nLevel != LOG_DEBUG || Rainmeter->GetDebug()) + // Ignore Level::Debug messages from plugins unless in debug mode + if (nLevel != (int)CLogger::Level::Debug || Rainmeter->GetDebug()) { - Log(nLevel, pszMessage); + CLogger::GetInstance().Log((CLogger::Level)nLevel, pszMessage); } return TRUE; diff --git a/Library/Library.vcxproj b/Library/Library.vcxproj index de641c0f..0bd18030 100644 --- a/Library/Library.vcxproj +++ b/Library/Library.vcxproj @@ -99,6 +99,9 @@ Use + + Use + Use @@ -316,6 +319,7 @@ + diff --git a/Library/Library.vcxproj.filters b/Library/Library.vcxproj.filters index f89fbae3..961e53d7 100644 --- a/Library/Library.vcxproj.filters +++ b/Library/Library.vcxproj.filters @@ -390,6 +390,9 @@ Common\Gfx\Util + + Source Files + @@ -680,6 +683,9 @@ Common\Gfx\Util + + Header Files + diff --git a/Library/Litestep.cpp b/Library/Litestep.cpp index d2131612..ddd8f01a 100644 --- a/Library/Litestep.cpp +++ b/Library/Litestep.cpp @@ -24,21 +24,6 @@ extern CRainmeter* Rainmeter; -static CRITICAL_SECTION g_CsLog = {0}; -static CRITICAL_SECTION g_CsLogDelay = {0}; - -void InitalizeLitestep() -{ - CSystem::InitializeCriticalSection(&g_CsLog); - CSystem::InitializeCriticalSection(&g_CsLogDelay); -} - -void FinalizeLitestep() -{ - DeleteCriticalSection(&g_CsLog); - DeleteCriticalSection(&g_CsLogDelay); -} - UINT GetUniqueID() { static UINT id = 0; @@ -104,142 +89,6 @@ void RunFile(const WCHAR* file, const WCHAR* args) } } -void LogInternal(int nLevel, ULONGLONG elapsed, LPCTSTR pszMessage) -{ - // Add timestamp - WCHAR buffer[128]; - size_t len = _snwprintf_s(buffer, _TRUNCATE, L"%02llu:%02llu:%02llu.%03llu", elapsed / (1000 * 60 * 60), (elapsed / (1000 * 60)) % 60, (elapsed / 1000) % 60, elapsed % 1000); - - Rainmeter->AddAboutLogInfo(nLevel, buffer, pszMessage); - -#ifndef _DEBUG - if (!Rainmeter->GetLogging()) return; -#endif - - std::wstring message; - switch (nLevel) - { - case LOG_ERROR: - message = L"ERRO"; - break; - - case LOG_WARNING: - message = L"WARN"; - break; - - case LOG_NOTICE: - message = L"NOTE"; - break; - - case LOG_DEBUG: - message = L"DBUG"; - break; - } - - message += L" ("; - message.append(buffer, len); - message += L") "; - message += pszMessage; - message += L'\n'; - -#ifdef _DEBUG - _RPT0(_CRT_WARN, StringUtil::Narrow(message).c_str()); - if (!Rainmeter->GetLogging()) return; -#endif - - const WCHAR* logFile = Rainmeter->GetLogFile().c_str(); - if (_waccess(logFile, 0) == -1) - { - // Disable logging if the file was deleted manually - Rainmeter->StopLogging(); - } - else - { - FILE* file = _wfopen(logFile, L"a+, ccs=UTF-8"); - if (file) - { - fputws(message.c_str(), file); - fclose(file); - } - } -} - -void Log(int nLevel, const WCHAR* message) -{ - struct DelayedLogInfo - { - int level; - ULONGLONG elapsed; - std::wstring message; - }; - static std::list c_LogDelay; - - static ULONGLONG startTime = CSystem::GetTickCount64(); - ULONGLONG elapsed = CSystem::GetTickCount64() - startTime; - - if (TryEnterCriticalSection(&g_CsLog)) - { - // Log the queued messages first - EnterCriticalSection(&g_CsLogDelay); - - while (!c_LogDelay.empty()) - { - DelayedLogInfo& logInfo = c_LogDelay.front(); - LogInternal(logInfo.level, logInfo.elapsed, logInfo.message.c_str()); - - c_LogDelay.erase(c_LogDelay.begin()); - } - - LeaveCriticalSection(&g_CsLogDelay); - - // Log the message - LogInternal(nLevel, elapsed, message); - - LeaveCriticalSection(&g_CsLog); - } - else - { - // Queue the message - EnterCriticalSection(&g_CsLogDelay); - - DelayedLogInfo logInfo = {nLevel, elapsed, message}; - c_LogDelay.push_back(logInfo); - - LeaveCriticalSection(&g_CsLogDelay); - } -} - -void LogWithArgs(int nLevel, const WCHAR* format, ...) -{ - WCHAR* buffer = new WCHAR[1024]; - va_list args; - va_start(args, format); - - _invalid_parameter_handler oldHandler = _set_invalid_parameter_handler(RmNullCRTInvalidParameterHandler); - _CrtSetReportMode(_CRT_ASSERT, 0); - - errno = 0; - _vsnwprintf_s(buffer, 1024, _TRUNCATE, format, args); - if (errno != 0) - { - nLevel = LOG_ERROR; - _snwprintf_s(buffer, 1024, _TRUNCATE, L"Internal error: %s", format); - } - - _set_invalid_parameter_handler(oldHandler); - - Log(nLevel, buffer); - va_end(args); - - delete [] buffer; -} - -void LogError(CError& error) -{ - Log(LOG_ERROR, error.GetString().c_str()); - CDialogAbout::ShowAboutLog(); -} - WCHAR* GetString(UINT id) { LPWSTR pData; diff --git a/Library/Litestep.h b/Library/Litestep.h index a5b54eaa..c4b42879 100644 --- a/Library/Litestep.h +++ b/Library/Litestep.h @@ -25,26 +25,11 @@ #include "../Common/StringUtil.h" #include "Error.h" -enum LOGLEVEL -{ - LOG_ERROR = 1, - LOG_WARNING = 2, - LOG_NOTICE = 3, - LOG_DEBUG = 4 -}; - -void InitalizeLitestep(); -void FinalizeLitestep(); - UINT GetUniqueID(); template UINT TypeID() { static UINT id = GetUniqueID(); return id; } -void Log(int nLevel, const WCHAR* message); -void LogWithArgs(int nLevel, const WCHAR* format, ...); -void LogError(CError& error); - void RunCommand(std::wstring command); void RunFile(const WCHAR* file, const WCHAR* args = NULL); diff --git a/Library/Logger.cpp b/Library/Logger.cpp new file mode 100644 index 00000000..be19c26c --- /dev/null +++ b/Library/Logger.cpp @@ -0,0 +1,235 @@ +/* + Copyright (C) 2013 Birunthan Mohanathas + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include "StdAfx.h" +#include "Logger.h" +#include "Rainmeter.h" +#include "DialogAbout.h" +#include "System.h" +#include "resource.h" + +extern CRainmeter* Rainmeter; + +namespace { + +const size_t MAX_LOG_ENTIRES = 20; + +} // namespace + +CLogger::CLogger() : + m_LogToFile(false) +{ + CSystem::InitializeCriticalSection(&m_CsLog); + CSystem::InitializeCriticalSection(&m_CsLogDelay); +} + +CLogger::~CLogger() +{ + DeleteCriticalSection(&m_CsLog); + DeleteCriticalSection(&m_CsLogDelay); +} + +CLogger& CLogger::GetInstance() +{ + static CLogger s_CLogger; + return s_CLogger; +} + +void CLogger::StartLogFile() +{ + const WCHAR* filePath = m_LogFilePath.c_str(); + if (_waccess(filePath, 0) == -1) + { + // Create empty log file. + HANDLE file = CreateFile(filePath, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); + if (file != INVALID_HANDLE_VALUE) + { + CloseHandle(file); + } + else + { + const std::wstring text = GetFormattedString(ID_STR_LOGFILECREATEFAIL, filePath); + Rainmeter->ShowMessage(NULL, text.c_str(), MB_OK | MB_ICONERROR); + SetLogToFile(false); + return; + } + } + + SetLogToFile(true); +} + +void CLogger::StopLogFile() +{ + SetLogToFile(false); +} + +void CLogger::DeleteLogFile() +{ + const WCHAR* filePath = m_LogFilePath.c_str(); + if (_waccess(filePath, 0) != -1) + { + const std::wstring text = GetFormattedString(ID_STR_LOGFILEDELETE, filePath); + const int res = Rainmeter->ShowMessage(NULL, text.c_str(), MB_YESNO | MB_ICONQUESTION); + if (res == IDYES) + { + SetLogToFile(false); + CSystem::RemoveFile(m_LogFilePath); + } + } +} + +void CLogger::SetLogToFile(bool logToFile) +{ + m_LogToFile = logToFile; + WritePrivateProfileString( + L"Rainmeter", L"Logging", logToFile ? L"1" : L"0", Rainmeter->GetIniFile().c_str()); +} + +void CLogger::LogInternal(Level level, ULONGLONG timestamp, const WCHAR* msg) +{ + WCHAR timestampSz[128]; + size_t len = _snwprintf_s( + timestampSz, + _TRUNCATE, + L"%02llu:%02llu:%02llu.%03llu", + timestamp / (1000 * 60 * 60), + (timestamp / (1000 * 60)) % 60, + (timestamp / 1000) % 60, + timestamp % 1000); + + // Store up to MAX_LOG_ENTIRES entries. + Entry entry = {level, std::wstring(timestampSz, len), msg}; + m_Entries.push_back(entry); + if (m_Entries.size() > MAX_LOG_ENTIRES) + { + m_Entries.pop_front(); + } + + CDialogAbout::AddLogItem(level, timestampSz, msg); +} + +void CLogger::WriteToLogFile(Entry& entry) +{ +#ifndef _DEBUG + if (!m_LogToFile) return; +#endif + + const WCHAR* levelSz = + (entry.level == Level::Error) ? L"ERRO" : + (entry.level == Level::Warning) ? L"WARN" : + (entry.level == Level::Notice) ? L"NOTE" : + L"DBUG"; + + std::wstring message = levelSz; + message += L" ("; + message.append(entry.timestamp); + message += L") "; + message += entry.message; + message += L'\n'; + +#ifdef _DEBUG + _RPT0(_CRT_WARN, StringUtil::Narrow(message).c_str()); + if (!m_LogToFile) return; +#endif + + const WCHAR* filePath = m_LogFilePath.c_str(); + if (_waccess(filePath, 0) == -1) + { + // The file has been deleted manually. + StopLogFile(); + } + else + { + FILE* file = _wfopen(filePath, L"a+, ccs=UTF-8"); + if (file) + { + fputws(message.c_str(), file); + fclose(file); + } + } +} + +void CLogger::Log(Level level, const WCHAR* msg) +{ + struct DelayedEntry + { + Level level; + ULONGLONG elapsed; + std::wstring message; + }; + static std::list s_DelayedEntries; + + static ULONGLONG s_StartTime = CSystem::GetTickCount64(); + ULONGLONG elapsed = CSystem::GetTickCount64() - s_StartTime; + + if (TryEnterCriticalSection(&m_CsLog)) + { + // Log queued messages first. + EnterCriticalSection(&m_CsLogDelay); + + while (!s_DelayedEntries.empty()) + { + DelayedEntry& entry = s_DelayedEntries.front(); + LogInternal(entry.level, entry.elapsed, entry.message.c_str()); + + s_DelayedEntries.erase(s_DelayedEntries.begin()); + } + + LeaveCriticalSection(&m_CsLogDelay); + + // Log the actual message. + LogInternal(level, elapsed, msg); + + LeaveCriticalSection(&m_CsLog); + } + else + { + // Queue message. + EnterCriticalSection(&m_CsLogDelay); + + DelayedEntry entry = {level, elapsed, msg}; + s_DelayedEntries.push_back(entry); + + LeaveCriticalSection(&m_CsLogDelay); + } +} + +void CLogger::LogF(Level level, const WCHAR* format, ...) +{ + WCHAR* buffer = new WCHAR[1024]; + va_list args; + va_start(args, format); + + _invalid_parameter_handler oldHandler = _set_invalid_parameter_handler(RmNullCRTInvalidParameterHandler); + _CrtSetReportMode(_CRT_ASSERT, 0); + + errno = 0; + _vsnwprintf_s(buffer, 1024, _TRUNCATE, format, args); + if (errno != 0) + { + level = Level::Error; + _snwprintf_s(buffer, 1024, _TRUNCATE, L"Internal error: %s", format); + } + + _set_invalid_parameter_handler(oldHandler); + + Log(level, buffer); + va_end(args); + + delete [] buffer; +} diff --git a/Library/Logger.h b/Library/Logger.h new file mode 100644 index 00000000..e7e0dc91 --- /dev/null +++ b/Library/Logger.h @@ -0,0 +1,110 @@ +/* + Copyright (C) 2013 Birunthan Mohanathas + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#ifndef RM_LOGGER_H_ +#define RM_LOGGER_H_ + +#include +#include +#include + +// Singleton class to handle and store log messages and control the log file. +class CLogger +{ +public: + enum class Level + { + Error, + Warning, + Notice, + Debug + }; + + struct Entry + { + Level level; + std::wstring timestamp; + std::wstring message; + }; + + static CLogger& GetInstance(); + + void SetLogFilePath(std::wstring path) { m_LogFilePath = path; } + + void StartLogFile(); + void StopLogFile(); + void DeleteLogFile(); + + bool IsLogToFile() { return m_LogToFile; } + void SetLogToFile(bool logToFile); + + void Log(Level level, const WCHAR* msg); + void LogF(Level level, const WCHAR* format, ...); + + // Convenience functions. + static void Error(const WCHAR* msg) { GetInstance().Log(Level::Error, msg); } + static void Warning(const WCHAR* msg) { GetInstance().Log(Level::Warning, msg); } + static void Notice(const WCHAR* msg) { GetInstance().Log(Level::Notice, msg); } + static void Debug(const WCHAR* msg) { GetInstance().Log(Level::Debug, msg); } + + // TODO: Uncomment when VS supports variadic templates. + /* + template + static void ErrorF(const WCHAR* format, Args... args) { GetInstance().LogF(Level::Error, args...); } + + template + static void WarningF(const WCHAR* format, Args... args) { GetInstance().LogF(Level::Warning, args...); } + + template + static void NoticeF(const WCHAR* format, Args... args) { GetInstance().LogF(Level::Notice, args...); } + + template + static void DebugF(const WCHAR* format, Args... args) { GetInstance().LogF(Level::Debug, args...); } + */ + + const std::wstring& GetLogFilePath() { return m_LogFilePath; } + + const std::list& GetEntries() { return m_Entries; } + +private: + void LogInternal(Level level, ULONGLONG timestamp, const WCHAR* msg); + + // Appends |entry| to the log file. + void WriteToLogFile(Entry& entry); + + CLogger(); + ~CLogger(); + + bool m_LogToFile; + std::wstring m_LogFilePath; + + std::list m_Entries; + + CRITICAL_SECTION m_CsLog; + CRITICAL_SECTION m_CsLogDelay; +}; + +// FIXME: Temporary solution until VS support variadic macros. +#define RM_LOGGER_LOGF_HELPER(name, format, ...) \ + CLogger::GetInstance().LogF(CLogger::Level::name, format, __VA_ARGS__); +#define CLogger_ErrorF(format, ...) RM_LOGGER_LOGF_HELPER(Error, format, __VA_ARGS__) +#define CLogger_WarningF(format, ...) RM_LOGGER_LOGF_HELPER(Warning, format, __VA_ARGS__) +#define CLogger_NoticeF(format, ...) RM_LOGGER_LOGF_HELPER(Notice, format, __VA_ARGS__) +#define CLogger_DebugF(format, ...) RM_LOGGER_LOGF_HELPER(Debug, format, __VA_ARGS__) + +#endif \ No newline at end of file diff --git a/Library/Measure.cpp b/Library/Measure.cpp index aee513ba..0a34cfe3 100644 --- a/Library/Measure.cpp +++ b/Library/Measure.cpp @@ -162,7 +162,7 @@ void CMeasure::ReadOptions(CConfigParser& parser, const WCHAR* section) } if (!ParseSubstitute(subs)) { - LogWithArgs(LOG_ERROR, L"Measure: Invalid Substitute=%s", subs.c_str()); + CLogger_ErrorF(L"Measure: Invalid Substitute=%s", subs.c_str()); } } @@ -260,7 +260,7 @@ const WCHAR* CMeasure::CheckSubstitute(const WCHAR* buffer) if (re == NULL) { MakePlainSubstitute(str, i); - LogWithArgs(LOG_NOTICE, L"Substitute: %S", error); + CLogger_NoticeF(L"Substitute: %S", error); } else { @@ -847,7 +847,7 @@ CMeasure* CMeasure::Create(const WCHAR* measure, CMeterWindow* meterWindow, cons return new CMeasureScript(meterWindow, name); } - LogWithArgs(LOG_ERROR, L"Measure=%s is not valid in [%s]", measure, name); + CLogger_ErrorF(L"Measure=%s is not valid in [%s]", measure, name); return NULL; } @@ -858,5 +858,5 @@ CMeasure* CMeasure::Create(const WCHAR* measure, CMeterWindow* meterWindow, cons */ void CMeasure::Command(const std::wstring& command) { - LogWithArgs(LOG_WARNING, L"!CommandMeasure: Not supported by [%s]", m_Name.c_str()); + CLogger_WarningF(L"!CommandMeasure: Not supported by [%s]", m_Name.c_str()); } diff --git a/Library/MeasureCPU.cpp b/Library/MeasureCPU.cpp index 5ce1487d..8f437936 100644 --- a/Library/MeasureCPU.cpp +++ b/Library/MeasureCPU.cpp @@ -91,7 +91,7 @@ void CMeasureCPU::ReadOptions(CConfigParser& parser, const WCHAR* section) if (processor < 0 || processor > c_NumOfProcessors) { - LogWithArgs(LOG_WARNING, L"CPU: Processor=%i invalid in [%s]", processor, section); + CLogger_WarningF(L"CPU: Processor=%i invalid in [%s]", processor, section); processor = 0; } diff --git a/Library/MeasureCalc.cpp b/Library/MeasureCalc.cpp index 2b787990..e0e9eebd 100644 --- a/Library/MeasureCalc.cpp +++ b/Library/MeasureCalc.cpp @@ -61,7 +61,7 @@ void CMeasureCalc::UpdateValue() { if (!m_ParseError) { - LogWithArgs(LOG_ERROR, L"Calc: %s in [%s]", errMsg, m_Name.c_str()); + CLogger_ErrorF(L"Calc: %s in [%s]", errMsg, m_Name.c_str()); m_ParseError = true; } } @@ -105,7 +105,7 @@ void CMeasureCalc::ReadOptions(CConfigParser& parser, const WCHAR* section) const WCHAR* errMsg = MathParser::Check(m_Formula.c_str()); if (errMsg != NULL) { - LogWithArgs(LOG_ERROR, L"Calc: %s in [%s]", errMsg, m_Name.c_str()); + CLogger_ErrorF(L"Calc: %s in [%s]", errMsg, m_Name.c_str()); m_Formula.clear(); } } diff --git a/Library/MeasureDiskSpace.cpp b/Library/MeasureDiskSpace.cpp index 7105aea1..3a27a116 100644 --- a/Library/MeasureDiskSpace.cpp +++ b/Library/MeasureDiskSpace.cpp @@ -182,7 +182,7 @@ void CMeasureDiskSpace::ReadOptions(CConfigParser& parser, const WCHAR* section) m_Drive = parser.ReadString(section, L"Drive", L"C:\\"); if (m_Drive.empty()) { - Log(LOG_WARNING, L"FreeDiskSpace: Drive= empty"); + CLogger::Warning(L"FreeDiskSpace: Drive= empty"); m_Value = 0.0; m_MaxValue = 0.0; m_OldTotalBytes = 0; diff --git a/Library/MeasureNet.cpp b/Library/MeasureNet.cpp index 039b5b83..11edaeb7 100644 --- a/Library/MeasureNet.cpp +++ b/Library/MeasureNet.cpp @@ -80,8 +80,8 @@ void CMeasureNet::UpdateIFTable() if (Rainmeter->GetDebug() && logging) { - Log(LOG_DEBUG, L"------------------------------"); - LogWithArgs(LOG_DEBUG, L"* NETWORK-INTERFACE: Count=%i", c_NumOfTables); + CLogger::Debug(L"------------------------------"); + CLogger_DebugF(L"* NETWORK-INTERFACE: Count=%i", c_NumOfTables); for (size_t i = 0; i < c_NumOfTables; ++i) { @@ -108,14 +108,14 @@ void CMeasureNet::UpdateIFTable() break; } - LogWithArgs(LOG_DEBUG, L"%i: %s", (int)i + 1, ifTable->Table[i].Description); - LogWithArgs(LOG_DEBUG, L" Alias: %s", ifTable->Table[i].Alias); - LogWithArgs(LOG_DEBUG, L" Type=%s(%i), Hardware=%s, Filter=%s", + CLogger_DebugF(L"%i: %s", (int)i + 1, ifTable->Table[i].Description); + CLogger_DebugF(L" Alias: %s", ifTable->Table[i].Alias); + CLogger_DebugF(L" Type=%s(%i), Hardware=%s, Filter=%s", type, ifTable->Table[i].Type, (ifTable->Table[i].InterfaceAndOperStatusFlags.HardwareInterface == 1) ? L"Yes" : L"No", (ifTable->Table[i].InterfaceAndOperStatusFlags.FilterInterface == 1) ? L"Yes" : L"No"); } - Log(LOG_DEBUG, L"------------------------------"); + CLogger::Debug(L"------------------------------"); } } else @@ -173,8 +173,8 @@ void CMeasureNet::UpdateIFTable() if (Rainmeter->GetDebug() && logging) { - Log(LOG_DEBUG, L"------------------------------"); - LogWithArgs(LOG_DEBUG, L"* NETWORK-INTERFACE: Count=%i", c_NumOfTables); + CLogger::Debug(L"------------------------------"); + CLogger_DebugF(L"* NETWORK-INTERFACE: Count=%i", c_NumOfTables); for (size_t i = 0; i < c_NumOfTables; ++i) { @@ -204,10 +204,10 @@ void CMeasureNet::UpdateIFTable() break; } - LogWithArgs(LOG_DEBUG, L"%i: %.*S", (int)i + 1, ifTable->table[i].dwDescrLen, (char*)ifTable->table[i].bDescr); - LogWithArgs(LOG_DEBUG, L" Type=%s(%i)", type, ifTable->table[i].dwType); + CLogger_DebugF(L"%i: %.*S", (int)i + 1, ifTable->table[i].dwDescrLen, (char*)ifTable->table[i].bDescr); + CLogger_DebugF(L" Type=%s(%i)", type, ifTable->table[i].dwType); } - Log(LOG_DEBUG, L"------------------------------"); + CLogger::Debug(L"------------------------------"); } } else diff --git a/Library/MeasurePlugin.cpp b/Library/MeasurePlugin.cpp index 48729378..0a3593c2 100644 --- a/Library/MeasurePlugin.cpp +++ b/Library/MeasurePlugin.cpp @@ -143,7 +143,7 @@ void CMeasurePlugin::ReadOptions(CConfigParser& parser, const WCHAR* section) } if (!m_Plugin) { - LogWithArgs(LOG_ERROR, L"Plugin: \"%s\" not found", pluginName.c_str()); + CLogger_ErrorF(L"Plugin: \"%s\" not found", pluginName.c_str()); return; } } diff --git a/Library/MeasureRegistry.cpp b/Library/MeasureRegistry.cpp index 5390cb19..5bf63b87 100644 --- a/Library/MeasureRegistry.cpp +++ b/Library/MeasureRegistry.cpp @@ -135,7 +135,7 @@ void CMeasureRegistry::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"RegHKey=%s is not valid in [%s]", keyname, m_Name.c_str()); + CLogger_ErrorF(L"RegHKey=%s is not valid in [%s]", keyname, m_Name.c_str()); } m_RegKeyName = parser.ReadString(section, L"RegKey", L""); diff --git a/Library/MeasureScript.cpp b/Library/MeasureScript.cpp index bb90afb6..14e8484c 100644 --- a/Library/MeasureScript.cpp +++ b/Library/MeasureScript.cpp @@ -111,7 +111,7 @@ void CMeasureScript::ReadOptions(CConfigParser& parser, const WCHAR* section) if (m_HasGetStringFunction) { - LogWithArgs(LOG_WARNING, L"Script: Using deprecated GetStringValue() in [%s]", m_Name.c_str()); + CLogger_WarningF(L"Script: Using deprecated GetStringValue() in [%s]", m_Name.c_str()); } lua_rawgeti(L, LUA_GLOBALSINDEX, m_LuaScript.GetRef()); @@ -171,7 +171,7 @@ void CMeasureScript::ReadOptions(CConfigParser& parser, const WCHAR* section) } } - LogWithArgs(LOG_ERROR, L"Script: File not valid in [%s]", m_Name.c_str()); + CLogger_ErrorF(L"Script: File not valid in [%s]", m_Name.c_str()); UninitializeLuaScript(); } @@ -187,28 +187,28 @@ void CMeasureScript::Command(const std::wstring& command) //static void stackDump(lua_State *L) //{ -// LuaManager::LuaLog(LOG_DEBUG, " ---------------- Stack Dump ----------------" ); +// LuaManager::LuaLogger::Debug(" ---------------- Stack Dump ----------------" ); // for (int i = lua_gettop(L); i > 0; --i) // { // int t = lua_type(L, i); // switch (t) // { // case LUA_TSTRING: -// LuaManager::LuaLog(LOG_DEBUG, "%d:'%s'", i, lua_tostring(L, i)); +// LuaManager::LuaLogger::Debug("%d:'%s'", i, lua_tostring(L, i)); // break; // // case LUA_TBOOLEAN: -// LuaManager::LuaLog(LOG_DEBUG, "%d: %s", i, lua_toboolean(L, i) ? "true" : "false"); +// LuaManager::LuaLogger::Debug("%d: %s", i, lua_toboolean(L, i) ? "true" : "false"); // break; // // case LUA_TNUMBER: -// LuaManager::LuaLog(LOG_DEBUG, "%d: %g", i, lua_tonumber(L, i)); +// LuaManager::LuaLogger::Debug("%d: %g", i, lua_tonumber(L, i)); // break; // // default: -// LuaManager::LuaLog(LOG_DEBUG, "%d: %s", i, lua_typename(L, t)); +// LuaManager::LuaLogger::Debug("%d: %s", i, lua_typename(L, t)); // break; // } // } -// LuaManager::LuaLog(LOG_DEBUG, "--------------- Stack Dump Finished ---------------" ); +// LuaManager::LuaLogger::Debug("--------------- Stack Dump Finished ---------------" ); //} diff --git a/Library/MeasureTime.cpp b/Library/MeasureTime.cpp index ba2a917f..7b68169a 100644 --- a/Library/MeasureTime.cpp +++ b/Library/MeasureTime.cpp @@ -73,7 +73,7 @@ void CMeasureTime::TimeToString(WCHAR* buf, size_t bufLen, const WCHAR* format, wcsftime(buf, bufLen, format, time); if (errno == EINVAL) { - LogWithArgs(LOG_ERROR, L"Time: \"Format=%s\" invalid in [%s]", format, m_Name.c_str()); + CLogger_ErrorF(L"Time: \"Format=%s\" invalid in [%s]", format, m_Name.c_str()); buf[0] = 0; } diff --git a/Library/MeasureUptime.cpp b/Library/MeasureUptime.cpp index 0848abef..112f6db1 100644 --- a/Library/MeasureUptime.cpp +++ b/Library/MeasureUptime.cpp @@ -95,7 +95,7 @@ const WCHAR* CMeasureUptime::GetStringValue() } __except (EXCEPTION_EXECUTE_HANDLER) { - LogWithArgs(LOG_ERROR, L"Uptime: \"Format=%s\" invalid in [%s]", m_Format.c_str(), m_Name.c_str()); + CLogger_ErrorF(L"Uptime: \"Format=%s\" invalid in [%s]", m_Format.c_str(), m_Name.c_str()); buffer[0] = 0; } diff --git a/Library/Meter.cpp b/Library/Meter.cpp index 4dd8a0cb..6eec3b08 100644 --- a/Library/Meter.cpp +++ b/Library/Meter.cpp @@ -351,7 +351,7 @@ void CMeter::ReadOptions(CConfigParser& parser, const WCHAR* section) delete m_Transformation; m_Transformation = NULL; - LogWithArgs(LOG_ERROR, L"Meter: Incorrect number of values in TransformationMatrix=%s", parser.ReadString(section, L"TransformationMatrix", L"").c_str()); + CLogger_ErrorF(L"Meter: Incorrect number of values in TransformationMatrix=%s", parser.ReadString(section, L"TransformationMatrix", L"").c_str()); } } @@ -409,7 +409,7 @@ CMeter* CMeter::Create(const WCHAR* meter, CMeterWindow* meterWindow, const WCHA return new CMeterButton(meterWindow, name); } - LogWithArgs(LOG_ERROR, L"Meter=%s is not valid in [%s]", meter, name); + CLogger_ErrorF(L"Meter=%s is not valid in [%s]", meter, name); return NULL; } @@ -443,7 +443,7 @@ bool CMeter::BindPrimaryMeasure(CConfigParser& parser, const WCHAR* section, boo } else if (!optional) { - LogWithArgs(LOG_ERROR, L"MeasureName=%s is not valid in [%s]", measureName.c_str(), section); + CLogger_ErrorF(L"MeasureName=%s is not valid in [%s]", measureName.c_str(), section); } return false; @@ -473,7 +473,7 @@ void CMeter::BindSecondaryMeasures(CConfigParser& parser, const WCHAR* section) { if (!measureName.empty()) { - LogWithArgs(LOG_ERROR, L"MeasureName%i=%s is not valid in [%s]", i, measureName.c_str(), section); + CLogger_ErrorF(L"MeasureName%i=%s is not valid in [%s]", i, measureName.c_str(), section); } break; diff --git a/Library/MeterBar.cpp b/Library/MeterBar.cpp index 42fdd583..df2a46c9 100644 --- a/Library/MeterBar.cpp +++ b/Library/MeterBar.cpp @@ -122,7 +122,7 @@ void CMeterBar::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"BarOrientation=%s is not valid in [%s]", orientation, m_Name.c_str()); + CLogger_ErrorF(L"BarOrientation=%s is not valid in [%s]", orientation, m_Name.c_str()); } if (m_Initialized) diff --git a/Library/MeterBitmap.cpp b/Library/MeterBitmap.cpp index 47029b17..7061771f 100644 --- a/Library/MeterBitmap.cpp +++ b/Library/MeterBitmap.cpp @@ -201,7 +201,7 @@ void CMeterBitmap::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"BitmapAlign=%s is not valid in [%s]", align, m_Name.c_str()); + CLogger_ErrorF(L"BitmapAlign=%s is not valid in [%s]", align, m_Name.c_str()); } if (m_Initialized) @@ -363,7 +363,7 @@ bool CMeterBitmap::Draw(Gfx::Canvas& canvas) } } -// LogWithArgs(LOG_DEBUG, L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false"); +// CLogger_DebugF(L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false"); if (bitmap->GetHeight() > bitmap->GetWidth()) { @@ -432,7 +432,7 @@ bool CMeterBitmap::Draw(Gfx::Canvas& canvas) } } -// LogWithArgs(LOG_DEBUG, L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false"); +// CLogger_DebugF(L"[%u] Value: %f Frame: %i (Transition = %s)", GetTickCount(), m_Value, frame, m_TransitionStartTicks > 0 ? L"true" : L"false"); if (bitmap->GetHeight() > bitmap->GetWidth()) { diff --git a/Library/MeterHistogram.cpp b/Library/MeterHistogram.cpp index 1488eb37..e32c2257 100644 --- a/Library/MeterHistogram.cpp +++ b/Library/MeterHistogram.cpp @@ -120,7 +120,7 @@ void CMeterHistogram::Initialize() // A sanity check if (secondaryMeasure && !m_PrimaryImageName.empty() && (m_OverlapImageName.empty() || m_SecondaryImageName.empty())) { - Log(LOG_WARNING, L"Histogram: SecondaryImage and BothImage not defined"); + CLogger::Warning(L"Histogram: SecondaryImage and BothImage not defined"); m_PrimaryImage.DisposeImage(); m_SecondaryImage.DisposeImage(); @@ -262,7 +262,7 @@ void CMeterHistogram::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"GraphStart=%s is not valid in [%s]", graph, m_Name.c_str()); + CLogger_ErrorF(L"GraphStart=%s is not valid in [%s]", graph, m_Name.c_str()); } graph = parser.ReadString(section, L"GraphOrientation", L"VERTICAL").c_str(); @@ -276,7 +276,7 @@ void CMeterHistogram::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"GraphOrientation=%s is not valid in [%s]", graph, m_Name.c_str()); + CLogger_ErrorF(L"GraphOrientation=%s is not valid in [%s]", graph, m_Name.c_str()); } if (m_Initialized) diff --git a/Library/MeterLine.cpp b/Library/MeterLine.cpp index 6b85ba83..d65c3274 100644 --- a/Library/MeterLine.cpp +++ b/Library/MeterLine.cpp @@ -19,7 +19,7 @@ #include "StdAfx.h" #include "MeterLine.h" #include "Measure.h" -#include "Error.h" +#include "Logger.h" #include "../Common/Gfx/Canvas.h" using namespace Gdiplus; @@ -159,7 +159,7 @@ void CMeterLine::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"GraphStart=%s is not valid in [%s]", graph, m_Name.c_str()); + CLogger_ErrorF(L"GraphStart=%s is not valid in [%s]", graph, m_Name.c_str()); } graph = parser.ReadString(section, L"GraphOrientation", L"VERTICAL").c_str(); @@ -173,7 +173,7 @@ void CMeterLine::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"GraphOrientation=%s is not valid in [%s]", graph, m_Name.c_str()); + CLogger_ErrorF(L"GraphOrientation=%s is not valid in [%s]", graph, m_Name.c_str()); } if (m_Initialized) diff --git a/Library/MeterString.cpp b/Library/MeterString.cpp index 70fff6fe..389a0815 100644 --- a/Library/MeterString.cpp +++ b/Library/MeterString.cpp @@ -201,7 +201,7 @@ void CMeterString::ReadOptions(CConfigParser& parser, const WCHAR* section) break; default: - LogWithArgs(LOG_ERROR, L"ClipString=%s is not valid in [%s]", clipping, m_Name.c_str()); + CLogger_ErrorF(L"ClipString=%s is not valid in [%s]", clipping, m_Name.c_str()); } m_FontFace = parser.ReadString(section, L"FontFace", L"Arial"); @@ -292,7 +292,7 @@ void CMeterString::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"StringCase=%s is not valid in [%s]", stringCase, m_Name.c_str()); + CLogger_ErrorF(L"StringCase=%s is not valid in [%s]", stringCase, m_Name.c_str()); } const WCHAR* style = parser.ReadString(section, L"StringStyle", L"NORMAL").c_str(); @@ -314,7 +314,7 @@ void CMeterString::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"StringStyle=%s is not valid in [%s]", style, m_Name.c_str()); + CLogger_ErrorF(L"StringStyle=%s is not valid in [%s]", style, m_Name.c_str()); } const WCHAR* effect = parser.ReadString(section, L"StringEffect", L"NONE").c_str(); @@ -332,7 +332,7 @@ void CMeterString::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"StringEffect=%s is not valid in [%s]", effect, m_Name.c_str()); + CLogger_ErrorF(L"StringEffect=%s is not valid in [%s]", effect, m_Name.c_str()); } if (m_Initialized && @@ -627,23 +627,23 @@ void CMeterString::EnumerateInstalledFontFamilies() } fonts += L", "; } - Log(LOG_NOTICE, fonts.c_str()); + CLogger::Warning(fonts.c_str()); } else { - Log(LOG_ERROR, L"Font enumeration: GetFamilies failed"); + CLogger::Error(L"Font enumeration: GetFamilies failed"); } delete [] fontFamilies; } else { - Log(LOG_WARNING, L"No installed fonts"); + CLogger::Warning(L"No installed fonts"); } } else { - Log(LOG_ERROR, L"Font enumeration: InstalledFontCollection failed"); + CLogger::Error(L"Font enumeration: InstalledFontCollection failed"); } } @@ -651,10 +651,10 @@ void CMeterString::InitializeStatic() { if (Rainmeter->GetDebug()) { - Log(LOG_DEBUG, L"------------------------------"); - Log(LOG_DEBUG, L"* Font families:"); + CLogger::Debug(L"------------------------------"); + CLogger::Debug(L"* Font families:"); EnumerateInstalledFontFamilies(); - Log(LOG_DEBUG, L"------------------------------"); + CLogger::Debug(L"------------------------------"); } } diff --git a/Library/MeterWindow.cpp b/Library/MeterWindow.cpp index 1d9f6f71..ac79d3b0 100644 --- a/Library/MeterWindow.cpp +++ b/Library/MeterWindow.cpp @@ -410,7 +410,7 @@ void CMeterWindow::Refresh(bool init, bool all) notice += L'\\'; notice += m_FileName; notice += L'"'; - Log(LOG_NOTICE, notice.c_str()); + CLogger::Notice(notice.c_str()); SetResizeWindowMode(RESIZEMODE_RESET); @@ -911,7 +911,7 @@ void CMeterWindow::RunBang(BANGCOMMAND bang, const std::vector& ar } else { - LogWithArgs(LOG_WARNING, L"!CommandMeasure: [%s] not found", measure.c_str()); + CLogger_WarningF(L"!CommandMeasure: [%s] not found", measure.c_str()); } } break; @@ -947,11 +947,11 @@ void CMeterWindow::RunBang(BANGCOMMAND bang, const std::vector& ar return; } - LogWithArgs(LOG_WARNING, L"!PluginBang: [%s] not found", measure.c_str()); + CLogger_WarningF(L"!PluginBang: [%s] not found", measure.c_str()); } else { - Log(LOG_ERROR, L"!PluginBang: Invalid parameters"); + CLogger::Error(L"!PluginBang: Invalid parameters"); } } break; @@ -1127,7 +1127,7 @@ void CMeterWindow::ShowMeter(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!ShowMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!ShowMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); } /* @@ -1149,7 +1149,7 @@ void CMeterWindow::HideMeter(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!HideMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!HideMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); } /* @@ -1178,7 +1178,7 @@ void CMeterWindow::ToggleMeter(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!ToggleMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!ToggleMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); } /* @@ -1201,7 +1201,7 @@ void CMeterWindow::MoveMeter(const std::wstring& name, int x, int y) } } - LogWithArgs(LOG_ERROR, L"!MoveMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); + CLogger_ErrorF(L"!MoveMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); } /* @@ -1251,7 +1251,7 @@ void CMeterWindow::UpdateMeter(const std::wstring& name, bool group) // Post-updates PostUpdate(bActiveTransition); - if (!group && bContinue) LogWithArgs(LOG_ERROR, L"!UpdateMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); + if (!group && bContinue) CLogger_ErrorF(L"!UpdateMeter: [%s] not found in \"%s\"", meter, m_FolderPath.c_str()); } /* @@ -1272,7 +1272,7 @@ void CMeterWindow::EnableMeasure(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!EnableMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!EnableMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); } /* @@ -1293,7 +1293,7 @@ void CMeterWindow::DisableMeasure(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!DisableMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!DisableMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); } /* @@ -1321,7 +1321,7 @@ void CMeterWindow::ToggleMeasure(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!ToggleMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!ToggleMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); } /* @@ -1361,7 +1361,7 @@ void CMeterWindow::UpdateMeasure(const std::wstring& name, bool group) } } - if (!group) LogWithArgs(LOG_ERROR, L"!UpdateMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); + if (!group) CLogger_ErrorF(L"!UpdateMeasure: [%s] not found in \"%s\"", measure, m_FolderPath.c_str()); } /* @@ -2109,7 +2109,7 @@ bool CMeterWindow::ReadSkin() { std::wstring error = L"Unable to load font: "; error += file.c_str(); - Log(LOG_ERROR, error.c_str()); + CLogger::Error(error.c_str()); } } } @@ -2142,7 +2142,7 @@ bool CMeterWindow::ReadSkin() { std::wstring error = L"Unable to load font: "; error += localFont; - Log(LOG_ERROR, error.c_str()); + CLogger::Error(error.c_str()); } } @@ -4348,7 +4348,7 @@ bool CMeterWindow::DoMoveAction(int x, int y, MOUSEACTION action) if (!m_MouseOver) { // If the mouse is over a meter it's also over the main window - //LogWithArgs(LOG_DEBUG, L"@Enter: %s", m_FolderPath.c_str()); + //CLogger_DebugF(L"@Enter: %s", m_FolderPath.c_str()); m_MouseOver = true; SetMouseLeaveEvent(false); RegisterMouseInput(); @@ -4387,7 +4387,7 @@ bool CMeterWindow::DoMoveAction(int x, int y, MOUSEACTION action) !mouse.GetLeaveAction().empty() || button) { - //LogWithArgs(LOG_DEBUG, L"MeterEnter: %s - [%s]", m_FolderPath.c_str(), (*j)->GetName()); + //CLogger_DebugF(L"MeterEnter: %s - [%s]", m_FolderPath.c_str(), (*j)->GetName()); (*j)->SetMouseOver(true); if (!mouse.GetOverAction().empty()) @@ -4413,7 +4413,7 @@ bool CMeterWindow::DoMoveAction(int x, int y, MOUSEACTION action) button->SetFocus(false); } - //LogWithArgs(LOG_DEBUG, L"MeterLeave: %s - [%s]", m_FolderPath.c_str(), (*j)->GetName()); + //CLogger_DebugF(L"MeterLeave: %s - [%s]", m_FolderPath.c_str(), (*j)->GetName()); (*j)->SetMouseOver(false); const CMouse& mouse = (*j)->GetMouse(); @@ -4434,7 +4434,7 @@ bool CMeterWindow::DoMoveAction(int x, int y, MOUSEACTION action) { if (!m_MouseOver) { - //LogWithArgs(LOG_DEBUG, L"Enter: %s", m_FolderPath.c_str()); + //CLogger_DebugF(L"Enter: %s", m_FolderPath.c_str()); m_MouseOver = true; SetMouseLeaveEvent(false); RegisterMouseInput(); @@ -4455,7 +4455,7 @@ bool CMeterWindow::DoMoveAction(int x, int y, MOUSEACTION action) // Mouse leave happens when the mouse is outside the window if (m_MouseOver) { - //LogWithArgs(LOG_DEBUG, L"Leave: %s", m_FolderPath.c_str()); + //CLogger_DebugF(L"Leave: %s", m_FolderPath.c_str()); m_MouseOver = false; SetMouseLeaveEvent(true); UnregisterMouseInput(); @@ -4670,7 +4670,7 @@ LRESULT CMeterWindow::OnCopyData(UINT uMsg, WPARAM wParam, LPARAM lParam) else { // This meterwindow has been deactivated - Log(LOG_WARNING, L"Unable to bang unloaded skin"); + CLogger::Warning(L"Unable to bang unloaded skin"); } return TRUE; diff --git a/Library/Mouse.cpp b/Library/Mouse.cpp index 7a4aac11..9f036605 100644 --- a/Library/Mouse.cpp +++ b/Library/Mouse.cpp @@ -20,7 +20,7 @@ #include "ConfigParser.h" #include "MeterWindow.h" #include "Meter.h" -#include "Litestep.h" +#include "Logger.h" #include "Mouse.h" CMouse::CMouse(CMeterWindow* meterWindow, CMeter* meter) : m_MeterWindow(meterWindow), m_Meter(meter), @@ -130,7 +130,7 @@ void CMouse::ReadOptions(CConfigParser& parser, const WCHAR* section) if (!m_CustomCursor) { m_CursorType = MOUSECURSOR_ARROW; - LogWithArgs(LOG_ERROR, L"Invalid cursor: %s", cursorPath.c_str()); + CLogger_ErrorF(L"Invalid cursor: %s", cursorPath.c_str()); } } } diff --git a/Library/Rainmeter.cpp b/Library/Rainmeter.cpp index 5d1f657b..ea29fe39 100644 --- a/Library/Rainmeter.cpp +++ b/Library/Rainmeter.cpp @@ -238,7 +238,7 @@ void CRainmeter::BangWithArgs(BANGCOMMAND bang, std::vector& args, } else { - LogWithArgs(LOG_ERROR, L"Bang: Skin \"%s\" not found", folderPath.c_str()); + CLogger_ErrorF( L"Bang: Skin \"%s\" not found", folderPath.c_str()); } return; } @@ -265,13 +265,13 @@ void CRainmeter::BangWithArgs(BANGCOMMAND bang, std::vector& args, firstArg.erase(0, pos + 1); args.insert(args.begin(), newArg); - Log(LOG_WARNING, L"!CommandMeasure: Two parameters required, only one given"); + CLogger::Warning(L"!CommandMeasure: Two parameters required, only one given"); BangWithArgs(bang, args, numOfArgs, meterWindow); return; } } - Log(LOG_ERROR, L"Bang: Incorrect number of arguments"); + CLogger::Error(L"Bang: Incorrect number of arguments"); } } @@ -296,7 +296,7 @@ void CRainmeter::BangGroupWithArgs(BANGCOMMAND bang, std::vector& } else { - Log(LOG_ERROR, L"BangGroup: Incorrect number of arguments"); + CLogger::Error(L"BangGroup: Incorrect number of arguments"); } } @@ -330,7 +330,7 @@ void CRainmeter::Bang_ActivateSkin(std::vector& args) } } - Log(LOG_ERROR, L"!ActivateConfig: Invalid parameters"); + CLogger::Error(L"!ActivateConfig: Invalid parameters"); } /* @@ -344,7 +344,7 @@ void CRainmeter::Bang_DeactivateSkin(std::vector& args, CMeterWind meterWindow = GetMeterWindow(args[0]); if (!meterWindow) { - LogWithArgs(LOG_WARNING, L"!DeactivateConfig: \"%s\" not active", args[0].c_str()); + CLogger_WarningF(L"!DeactivateConfig: \"%s\" not active", args[0].c_str()); return; } } @@ -355,7 +355,7 @@ void CRainmeter::Bang_DeactivateSkin(std::vector& args, CMeterWind } else { - Log(LOG_ERROR, L"!DeactivateConfig: Invalid parameters"); + CLogger::Error(L"!DeactivateConfig: Invalid parameters"); } } @@ -379,7 +379,7 @@ void CRainmeter::Bang_ToggleSkin(std::vector& args) } else { - Log(LOG_ERROR, L"!ToggleConfig: Invalid parameters"); + CLogger::Error(L"!ToggleConfig: Invalid parameters"); } } @@ -402,7 +402,7 @@ void CRainmeter::Bang_DeactivateSkinGroup(std::vector& args) } else { - Log(LOG_ERROR, L"!DeactivateConfigGroup: Invalid parameters"); + CLogger::Error(L"!DeactivateConfigGroup: Invalid parameters"); } } @@ -442,7 +442,7 @@ void CRainmeter::Bang_SetClip(std::vector& args) } else { - Log(LOG_ERROR, L"!SetClip: Invalid parameter"); + CLogger::Error(L"!SetClip: Invalid parameter"); } } @@ -467,7 +467,7 @@ void CRainmeter::Bang_SetWallpaper(std::vector& args, CMeterWindow } else { - Log(LOG_ERROR, L"!SetWallpaper: Invalid parameters"); + CLogger::Error(L"!SetWallpaper: Invalid parameters"); } } @@ -482,7 +482,7 @@ void CRainmeter::Bang_SkinMenu(std::vector& args, CMeterWindow* me meterWindow = GetMeterWindow(args[0]); if (!meterWindow) { - LogWithArgs(LOG_WARNING, L"!SkinMenu: \"%s\" not active", args[0].c_str()); + CLogger_WarningF(L"!SkinMenu: \"%s\" not active", args[0].c_str()); return; } } @@ -494,7 +494,7 @@ void CRainmeter::Bang_SkinMenu(std::vector& args, CMeterWindow* me } else { - Log(LOG_ERROR, L"!SkinMenu: Invalid parameter"); + CLogger::Error(L"!SkinMenu: Invalid parameter"); } } @@ -521,7 +521,7 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo } else if (args.size() < 4) { - Log(LOG_ERROR, L"!WriteKeyValue: Invalid parameters"); + CLogger::Error(L"!WriteKeyValue: Invalid parameters"); return; } @@ -535,21 +535,21 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo if (strIniFile.find(L"..\\") != std::wstring::npos || strIniFile.find(L"../") != std::wstring::npos) { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: Illegal path: %s", iniFile); + CLogger_ErrorF(L"!WriteKeyValue: Illegal path: %s", iniFile); return; } if (_wcsnicmp(iniFile, m_SkinPath.c_str(), m_SkinPath.size()) != 0 && _wcsnicmp(iniFile, m_SettingsPath.c_str(), m_SettingsPath.size()) != 0) { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: Illegal path: %s", iniFile); + CLogger_ErrorF(L"!WriteKeyValue: Illegal path: %s", iniFile); return; } // Verify whether the file exists if (_waccess(iniFile, 0) == -1) { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: File not found: %s", iniFile); + CLogger_ErrorF(L"!WriteKeyValue: File not found: %s", iniFile); return; } @@ -557,7 +557,7 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo DWORD attr = GetFileAttributes(iniFile); if (attr == -1 || (attr & FILE_ATTRIBUTE_READONLY)) { - LogWithArgs(LOG_WARNING, L"!WriteKeyValue: File is read-only: %s", iniFile); + CLogger_WarningF(L"!WriteKeyValue: File is read-only: %s", iniFile); return; } @@ -573,11 +573,11 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo if (temporary) { - if (GetDebug()) LogWithArgs(LOG_DEBUG, L"!WriteKeyValue: Writing to: %s (Temp: %s)", iniFile, strIniWrite.c_str()); + if (GetDebug()) CLogger_DebugF(L"!WriteKeyValue: Writing to: %s (Temp: %s)", iniFile, strIniWrite.c_str()); } else { - if (GetDebug()) LogWithArgs(LOG_DEBUG, L"!WriteKeyValue: Writing to: %s", iniFile); + if (GetDebug()) CLogger_DebugF(L"!WriteKeyValue: Writing to: %s", iniFile); strIniWrite = strIniFile; } @@ -619,12 +619,12 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo // Copy the file back if (!CSystem::CopyFiles(strIniWrite, strIniFile)) { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: Failed to copy temporary file to original filepath: %s (Temp: %s)", iniFile, iniWrite); + CLogger_ErrorF(L"!WriteKeyValue: Failed to copy temporary file to original filepath: %s (Temp: %s)", iniFile, iniWrite); } } else // failed { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: Failed to write to: %s (Temp: %s)", iniFile, iniWrite); + CLogger_ErrorF(L"!WriteKeyValue: Failed to write to: %s (Temp: %s)", iniFile, iniWrite); } // Remove a temporary file @@ -634,7 +634,7 @@ void CRainmeter::Bang_WriteKeyValue(std::vector& args, CMeterWindo { if (write == 0) // failed { - LogWithArgs(LOG_ERROR, L"!WriteKeyValue: Failed to write to: %s", iniFile); + CLogger_ErrorF(L"!WriteKeyValue: Failed to write to: %s", iniFile); } } } @@ -647,31 +647,30 @@ void CRainmeter::Bang_Log(std::vector& args) { if (!args.empty()) { - int level = LOG_NOTICE; - + CLogger::Level level = CLogger::Level::Notice; if (args.size() > 1) { const WCHAR* type = args[1].c_str(); if (_wcsicmp(type, L"ERROR") == 0) { - level = LOG_ERROR; + level = CLogger::Level::Error; } else if (_wcsicmp(type, L"WARNING") == 0) { - level = LOG_WARNING; + level = CLogger::Level::Warning; } else if (_wcsicmp(type, L"DEBUG") == 0) { - level = LOG_DEBUG; + level = CLogger::Level::Debug; } else if (_wcsicmp(type, L"NOTICE") != 0) { - Log(LOG_ERROR, L"!Log: Invalid type"); + CLogger::Error(L"!Log: Invalid type"); return; } } - Log(level, args[0].c_str()); + CLogger::GetInstance().Log(level, args[0].c_str()); } } @@ -698,7 +697,6 @@ CRainmeter::CRainmeter() : m_MenuActive(false), m_DisableRDP(false), m_DisableDragging(false), - m_Logging(false), m_CurrentParser(), m_Window(), m_Mutex(), @@ -746,8 +744,6 @@ CRainmeter::~CRainmeter() UpdateDesktopWorkArea(true); } - FinalizeLitestep(); - if (m_ResourceInstance) FreeLibrary(m_ResourceInstance); if (m_Mutex) ReleaseMutex(m_Mutex); @@ -762,8 +758,6 @@ CRainmeter::~CRainmeter() */ int CRainmeter::Initialize(LPCWSTR iniPath, LPCWSTR layout) { - InitalizeLitestep(); - m_Instance = GetModuleHandle(L"Rainmeter"); WCHAR* buffer = new WCHAR[MAX_LINE_LENGTH]; @@ -840,6 +834,7 @@ int CRainmeter::Initialize(LPCWSTR iniPath, LPCWSTR layout) if (!m_Window) return 1; + CLogger& logger = CLogger::GetInstance(); const WCHAR* iniFile = m_IniFile.c_str(); // Set file locations @@ -852,11 +847,13 @@ int CRainmeter::Initialize(LPCWSTR iniPath, LPCWSTR layout) len -= 4; } - m_LogFile.assign(m_IniFile, 0, len); - m_DataFile = m_StatsFile = m_LogFile; - m_LogFile += L".log"; + std::wstring logFile(m_IniFile, 0, len); + m_DataFile = m_StatsFile = logFile; + logFile += L".log"; m_StatsFile += L".stats"; m_DataFile += L".data"; + + logger.SetLogFilePath(logFile); } // Create a default Rainmeter.ini file if needed @@ -873,14 +870,15 @@ int CRainmeter::Initialize(LPCWSTR iniPath, LPCWSTR layout) } // Reset log file - CSystem::RemoveFile(m_LogFile); + CSystem::RemoveFile(logger.GetLogFilePath()); m_Debug = 0!=GetPrivateProfileInt(L"Rainmeter", L"Debug", 0, iniFile); - m_Logging = 0!=GetPrivateProfileInt(L"Rainmeter", L"Logging", 0, iniFile); - if (m_Logging) + const bool logging = GetPrivateProfileInt(L"Rainmeter", L"Logging", 0, iniFile) != 0; + logger.SetLogToFile(logging); + if (logging) { - StartLogging(); + logger.StartLogFile(); } // Determine the language resource to load @@ -960,9 +958,9 @@ int CRainmeter::Initialize(LPCWSTR iniPath, LPCWSTR layout) delete [] buffer; buffer = NULL; - LogWithArgs(LOG_NOTICE, L"Path: %s", m_Path.c_str()); - LogWithArgs(LOG_NOTICE, L"IniFile: %s", iniFile); - LogWithArgs(LOG_NOTICE, L"SkinPath: %s", m_SkinPath.c_str()); + CLogger_NoticeF(L"Path: %s", m_Path.c_str()); + CLogger_NoticeF(L"IniFile: %s", iniFile); + CLogger_NoticeF(L"SkinPath: %s", m_SkinPath.c_str()); // Extract volume path from program path // E.g.: @@ -1418,7 +1416,7 @@ void CRainmeter::ActivateSkin(int folderIndex, int fileIndex) { if (wcscmp(((*iter).second)->GetFileName().c_str(), fileSz) == 0) { - LogWithArgs(LOG_WARNING, L"!ActivateConfig: \"%s\" already active", folderPath.c_str()); + CLogger_WarningF(L"!ActivateConfig: \"%s\" already active", folderPath.c_str()); return; } else @@ -2281,7 +2279,7 @@ void CRainmeter::ExecuteBang(const WCHAR* bang, std::vector& args, } else { - LogWithArgs(LOG_ERROR, L"Invalid bang: !%s", bang); + CLogger_ErrorF(L"Invalid bang: !%s", bang); } } @@ -2455,13 +2453,15 @@ void CRainmeter::ReadGeneralSettings(const std::wstring& iniFile) m_UseD2D = 0!=parser.ReadInt(L"Rainmeter", L"UseD2D", 0); - // Read Logging settings - m_Logging = 0!=parser.ReadInt(L"Rainmeter", L"Logging", 0); m_Debug = 0!=parser.ReadInt(L"Rainmeter", L"Debug", 0); - - if (m_Logging) + + // Read Logging settings + CLogger& logger = CLogger::GetInstance(); + const bool logging = parser.ReadInt(L"Rainmeter", L"Logging", 0) != 0; + logger.SetLogToFile(logging); + if (logging) { - StartLogging(); + logger.StartLogFile(); } if (m_TrayWindow) @@ -2486,7 +2486,7 @@ void CRainmeter::ReadGeneralSettings(const std::wstring& iniFile) if (m_Debug) { - LogWithArgs(LOG_NOTICE, L"ConfigEditor: %s", m_SkinEditor.c_str()); + CLogger_NoticeF(L"ConfigEditor: %s", m_SkinEditor.c_str()); } m_TrayExecuteR = parser.ReadString(L"Rainmeter", L"TrayExecuteR", L"", false); @@ -2731,7 +2731,7 @@ void CRainmeter::UpdateDesktopWorkArea(bool reset) { format += L" => FAIL"; } - LogWithArgs(LOG_DEBUG, format.c_str(), i, r.left, r.top, r.right, r.bottom, r.right - r.left, r.bottom - r.top); + CLogger_DebugF(format.c_str(), i, r.left, r.top, r.right, r.bottom, r.right - r.left, r.bottom - r.top); } } changed = true; @@ -2754,7 +2754,7 @@ void CRainmeter::UpdateDesktopWorkArea(bool reset) if (m_Debug) { - LogWithArgs(LOG_DEBUG, L"DesktopWorkAreaType: %s", m_DesktopWorkAreaType ? L"Margin" : L"Default"); + CLogger_DebugF(L"DesktopWorkAreaType: %s", m_DesktopWorkAreaType ? L"Margin" : L"Default"); } for (UINT i = 0; i <= numOfMonitors; ++i) @@ -2806,7 +2806,7 @@ void CRainmeter::UpdateDesktopWorkArea(bool reset) { format += L" => FAIL"; } - LogWithArgs(LOG_DEBUG, format.c_str(), r.left, r.top, r.right, r.bottom, r.right - r.left, r.bottom - r.top); + CLogger_DebugF(format.c_str(), r.left, r.top, r.right, r.bottom, r.right - r.left, r.bottom - r.top); } } } @@ -2951,7 +2951,7 @@ void CRainmeter::ShowContextMenu(POINT pos, CMeterWindow* meterWindow) { SetMenuDefaultItem(menu, IDM_MANAGE, MF_BYCOMMAND); - if (_waccess(m_LogFile.c_str(), 0) == -1) + if (_waccess(CLogger::GetInstance().GetLogFilePath().c_str(), 0) == -1) { EnableMenuItem(menu, IDM_SHOWLOGFILE, MF_BYCOMMAND | MF_GRAYED); EnableMenuItem(menu, IDM_DELETELOGFILE, MF_BYCOMMAND | MF_GRAYED); @@ -2959,7 +2959,10 @@ void CRainmeter::ShowContextMenu(POINT pos, CMeterWindow* meterWindow) } else { - EnableMenuItem(menu, (m_Logging) ? IDM_STARTLOG : IDM_STOPLOG, MF_BYCOMMAND | MF_GRAYED); + EnableMenuItem( + menu, + (CLogger::GetInstance().IsLogToFile()) ? IDM_STARTLOG : IDM_STOPLOG, + MF_BYCOMMAND | MF_GRAYED); } if (m_Debug) @@ -3512,83 +3515,14 @@ void CRainmeter::ChangeSkinIndex(HMENU menu, int index) } } -void CRainmeter::StartLogging() -{ - // Check if the file exists - const WCHAR* logFile = m_LogFile.c_str(); - if (_waccess(logFile, 0) == -1) - { - // Create log file - HANDLE file = CreateFile(logFile, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); - if (file != INVALID_HANDLE_VALUE) - { - CloseHandle(file); - SetLogging(true); - } - else - { - // Disable logging - SetLogging(false); - - std::wstring text = GetFormattedString(ID_STR_LOGFILECREATEFAIL, logFile); - ShowMessage(NULL, text.c_str(), MB_OK | MB_ICONERROR); - } - } - else - { - SetLogging(true); - } -} - -void CRainmeter::StopLogging() -{ - SetLogging(false); -} - void CRainmeter::ShowLogFile() { - std::wstring logFile = L'"' + m_LogFile; + std::wstring logFile = L'"' + CLogger::GetInstance().GetLogFilePath(); logFile += L'"'; RunFile(m_SkinEditor.c_str(), logFile.c_str()); } -void CRainmeter::DeleteLogFile() -{ - // Check if the file exists - const WCHAR* logFile = m_LogFile.c_str(); - if (_waccess(logFile, 0) != -1) - { - std::wstring text = GetFormattedString(ID_STR_LOGFILEDELETE, logFile); - int res = ShowMessage(NULL, text.c_str(), MB_YESNO | MB_ICONQUESTION); - if (res == IDYES) - { - // Disable logging - SetLogging(false); - CSystem::RemoveFile(m_LogFile); - } - } -} - -void CRainmeter::AddAboutLogInfo(int level, LPCWSTR time, LPCWSTR message) -{ - // Store 20 last items - LogInfo logInfo = {level, time, message}; - m_LogData.push_back(logInfo); - if (m_LogData.size() > 20) - { - m_LogData.pop_front(); - } - - CDialogAbout::AddLogItem(level, time, message); -} - -void CRainmeter::SetLogging(bool logging) -{ - m_Logging = logging; - WritePrivateProfileString(L"Rainmeter", L"Logging", logging ? L"1" : L"0", m_IniFile.c_str()); -} - void CRainmeter::SetDebug(bool debug) { m_Debug = debug; @@ -3675,7 +3609,7 @@ void CRainmeter::ExpandEnvironmentVariables(std::wstring& strPath) DWORD ret = ExpandEnvironmentStrings(strPath.c_str(), buffer, bufSize); if (ret == 0) // Error { - LogWithArgs(LOG_WARNING, L"Unable to expand environment strings in: %s", strPath.c_str()); + CLogger_WarningF(L"Unable to expand environment strings in: %s", strPath.c_str()); break; } if (ret <= bufSize) // Fits in the buffer diff --git a/Library/Rainmeter.h b/Library/Rainmeter.h index 6dc72d08..316e8e61 100644 --- a/Library/Rainmeter.h +++ b/Library/Rainmeter.h @@ -25,6 +25,7 @@ #include #include #include "Litestep.h" +#include "Logger.h" #include "MeterWindow.h" #define MAX_LINE_LENGTH 4096 @@ -89,13 +90,6 @@ public: } }; - struct LogInfo - { - int level; - std::wstring timestamp; - std::wstring message; - }; - CRainmeter(); ~CRainmeter(); @@ -139,7 +133,6 @@ public: const std::wstring& GetPath() { return m_Path; } const std::wstring& GetIniFile() { return m_IniFile; } const std::wstring& GetDataFile() { return m_DataFile; } - const std::wstring& GetLogFile() { return m_LogFile; } const std::wstring& GetSettingsPath() { return m_SettingsPath; } const std::wstring& GetSkinPath() { return m_SkinPath; } void SetSkinPath(const std::wstring& skinPath); @@ -188,11 +181,7 @@ public: bool GetNewVersion() { return m_NewVersion; } void SetNewVersion() { m_NewVersion = true; } - bool GetLogging() { return m_Logging; } - void StartLogging(); - void StopLogging(); void ShowLogFile(); - void DeleteLogFile(); bool GetDisableRDP() { return m_DisableRDP; } bool IsRedrawable() { return (!GetDisableRDP() || !GetSystemMetrics(SM_REMOTESESSION)); } @@ -202,9 +191,6 @@ public: bool IsNormalStayDesktop() { return m_NormalStayDesktop; } - void AddAboutLogInfo(int level, LPCWSTR time, LPCWSTR message); - const std::list& GetAboutLogData() { return m_LogData; } - void SetDebug(bool debug); int ShowMessage(HWND parent, const WCHAR* text, UINT type); @@ -229,7 +215,7 @@ public: static std::vector ParseString(LPCTSTR str, CConfigParser* parser = NULL); static std::wstring ExtractPath(const std::wstring& strFilePath); static void ExpandEnvironmentVariables(std::wstring& strPath); - + friend class CDialogManage; private: @@ -272,7 +258,6 @@ private: void CreateOptionsFile(); void CreateDataFile(); void CreateComponentFolders(bool defaultIniLocation); - void SetLogging(bool logging); void TestSettingsFile(bool bDefaultIniLocation); CTrayWindow* m_TrayWindow; @@ -287,7 +272,6 @@ private: std::wstring m_IniFile; std::wstring m_DataFile; std::wstring m_StatsFile; - std::wstring m_LogFile; std::wstring m_SettingsPath; std::wstring m_SkinPath; @@ -320,10 +304,6 @@ private: bool m_DisableDragging; - bool m_Logging; - - std::list m_LogData; - std::wstring m_SkinEditor; CConfigParser* m_CurrentParser; diff --git a/Library/System.cpp b/Library/System.cpp index 43d656a8..c5a36baf 100644 --- a/Library/System.cpp +++ b/Library/System.cpp @@ -161,13 +161,13 @@ BOOL CALLBACK MyInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonit if (Rainmeter->GetDebug()) { - Log(LOG_DEBUG, info.szDevice); - LogWithArgs(LOG_DEBUG, L" Flags : %s(0x%08X)", (info.dwFlags & MONITORINFOF_PRIMARY) ? L"PRIMARY " : L"", info.dwFlags); - LogWithArgs(LOG_DEBUG, L" Handle : 0x%p", hMonitor); - LogWithArgs(LOG_DEBUG, L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger::Debug(info.szDevice); + CLogger_DebugF(L" Flags : %s(0x%08X)", (info.dwFlags & MONITORINFOF_PRIMARY) ? L"PRIMARY " : L"", info.dwFlags); + CLogger_DebugF(L" Handle : 0x%p", hMonitor); + CLogger_DebugF(L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", lprcMonitor->left, lprcMonitor->top, lprcMonitor->right, lprcMonitor->bottom, lprcMonitor->right - lprcMonitor->left, lprcMonitor->bottom - lprcMonitor->top); - LogWithArgs(LOG_DEBUG, L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); } @@ -255,8 +255,8 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - Log(LOG_DEBUG, L"------------------------------"); - Log(LOG_DEBUG, L"* EnumDisplayDevices / EnumDisplaySettings API"); + CLogger::Debug(L"------------------------------"); + CLogger::Debug(L"* EnumDisplayDevices / EnumDisplaySettings API"); } DISPLAY_DEVICE dd = {sizeof(DISPLAY_DEVICE)}; @@ -276,7 +276,7 @@ void CSystem::SetMultiMonitorInfo() { deviceString.assign(dd.DeviceString, wcsnlen(dd.DeviceString, _countof(dd.DeviceString))); - Log(LOG_DEBUG, deviceName.c_str()); + CLogger::Debug(deviceName.c_str()); if (dd.StateFlags & DISPLAY_DEVICE_ACTIVE) { @@ -334,7 +334,7 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - LogWithArgs(LOG_DEBUG, L" Name : %s", monitor.monitorName.c_str()); + CLogger_DebugF(L" Name : %s", monitor.monitorName.c_str()); } break; } @@ -342,8 +342,8 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - LogWithArgs(LOG_DEBUG, L" Adapter : %s", deviceString.c_str()); - LogWithArgs(LOG_DEBUG, L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags); + CLogger_DebugF(L" Adapter : %s", deviceString.c_str()); + CLogger_DebugF(L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags); } if (dd.StateFlags & DISPLAY_DEVICE_ACTIVE) @@ -360,7 +360,7 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - LogWithArgs(LOG_DEBUG, L" Handle : 0x%p", monitor.handle); + CLogger_DebugF(L" Handle : 0x%p", monitor.handle); } } @@ -374,10 +374,10 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - LogWithArgs(LOG_DEBUG, L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L" ScrArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right, info.rcMonitor.bottom, info.rcMonitor.right - info.rcMonitor.left, info.rcMonitor.bottom - info.rcMonitor.top); - LogWithArgs(LOG_DEBUG, L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L" WorkArea : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); } @@ -404,8 +404,8 @@ void CSystem::SetMultiMonitorInfo() { if (logging) { - LogWithArgs(LOG_DEBUG, L" Adapter : %s", deviceString.c_str()); - LogWithArgs(LOG_DEBUG, L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags); + CLogger_DebugF(L" Adapter : %s", deviceString.c_str()); + CLogger_DebugF(L" Flags : %s(0x%08X)", msg.c_str(), dd.StateFlags); } } ++dwDevice; @@ -415,15 +415,15 @@ void CSystem::SetMultiMonitorInfo() if (monitors.empty()) // Failed to enumerate the non-mirroring monitors { - Log(LOG_WARNING, L"Failed to enumerate the non-mirroring monitors. Only EnumDisplayMonitors is used instead."); + CLogger::Warning(L"Failed to enumerate the non-mirroring monitors. Only EnumDisplayMonitors is used instead."); c_Monitors.useEnumDisplayDevices = false; c_Monitors.useEnumDisplayMonitors = true; } if (logging) { - Log(LOG_DEBUG, L"------------------------------"); - Log(LOG_DEBUG, L"* EnumDisplayMonitors API"); + CLogger::Debug(L"------------------------------"); + CLogger::Debug(L"* EnumDisplayMonitors API"); } if (c_Monitors.useEnumDisplayMonitors) @@ -432,7 +432,7 @@ void CSystem::SetMultiMonitorInfo() if (monitors.empty()) // Failed to enumerate the monitors { - Log(LOG_WARNING, L"Failed to enumerate monitors. Using dummy monitor info."); + CLogger::Warning(L"Failed to enumerate monitors. Using dummy monitor info."); c_Monitors.useEnumDisplayMonitors = false; MonitorInfo monitor; @@ -466,7 +466,7 @@ void CSystem::SetMultiMonitorInfo() if (logging) { - Log(LOG_DEBUG, L"------------------------------"); + CLogger::Debug(L"------------------------------"); std::wstring method = L"* METHOD: "; if (c_Monitors.useEnumDisplayDevices) @@ -478,11 +478,11 @@ void CSystem::SetMultiMonitorInfo() { method += c_Monitors.useEnumDisplayMonitors ? L"EnumDisplayMonitors Mode" : L"Dummy Mode"; } - Log(LOG_DEBUG, method.c_str()); + CLogger::Debug(method.c_str()); - LogWithArgs(LOG_DEBUG, L"* MONITORS: Count=%i, Primary=@%i", (int)monitors.size(), c_Monitors.primary); - Log(LOG_DEBUG, L"@0: Virtual screen"); - LogWithArgs(LOG_DEBUG, L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L"* MONITORS: Count=%i, Primary=@%i", (int)monitors.size(), c_Monitors.primary); + CLogger::Debug(L"@0: Virtual screen"); + CLogger_DebugF(L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", c_Monitors.vsL, c_Monitors.vsT, c_Monitors.vsL + c_Monitors.vsW, c_Monitors.vsT + c_Monitors.vsH, c_Monitors.vsW, c_Monitors.vsH); @@ -491,17 +491,17 @@ void CSystem::SetMultiMonitorInfo() { if ((*iter).active) { - LogWithArgs(LOG_DEBUG, L"@%i: %s (active), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str()); - LogWithArgs(LOG_DEBUG, L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L"@%i: %s (active), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str()); + CLogger_DebugF(L" L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", (*iter).screen.left, (*iter).screen.top, (*iter).screen.right, (*iter).screen.bottom, (*iter).screen.right - (*iter).screen.left, (*iter).screen.bottom - (*iter).screen.top); } else { - LogWithArgs(LOG_DEBUG, L"@%i: %s (inactive), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str()); + CLogger_DebugF(L"@%i: %s (inactive), MonitorName: %s", i, (*iter).deviceName.c_str(), (*iter).monitorName.c_str()); } } - Log(LOG_DEBUG, L"------------------------------"); + CLogger::Debug(L"------------------------------"); } } @@ -531,7 +531,7 @@ void CSystem::UpdateWorkareaInfo() if (Rainmeter->GetDebug()) { - LogWithArgs(LOG_DEBUG, L"WorkArea@%i : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", + CLogger_DebugF(L"WorkArea@%i : L=%i, T=%i, R=%i, B=%i (W=%i, H=%i)", i, info.rcWork.left, info.rcWork.top, info.rcWork.right, info.rcWork.bottom, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); @@ -696,7 +696,7 @@ BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lParam) if (logging) { - LogWithArgs(LOG_DEBUG, L"%c [%c] 0x%p : %s (Name: \"%s\", zPos=%i)", + CLogger_DebugF(L"%c [%c] 0x%p : %s (Name: \"%s\", zPos=%i)", flag, IsWindowVisible(hwnd) ? L'V' : L'H', hwnd, className, Window->GetFolderPath().c_str(), (int)zPos); } } @@ -705,7 +705,7 @@ BOOL CALLBACK MyEnumWindowsProc(HWND hwnd, LPARAM lParam) if (logging) { flag = (hwnd == CSystem::GetHelperWindow()) ? L'o' : ' '; - LogWithArgs(LOG_DEBUG, L"%c [%c] 0x%p : %s", flag, IsWindowVisible(hwnd) ? L'V' : L'H', hwnd, className); + CLogger_DebugF(L"%c [%c] 0x%p : %s", flag, IsWindowVisible(hwnd) ? L'V' : L'H', hwnd, className); } } @@ -721,7 +721,7 @@ void CSystem::ChangeZPosInOrder() bool logging = Rainmeter->GetDebug() && DEBUG_VERBOSE; std::vector windowsInZOrder; - if (logging) Log(LOG_DEBUG, L"1: ----- BEFORE -----"); + if (logging) CLogger::Debug(L"1: ----- BEFORE -----"); // Retrieve the Rainmeter's meter windows in Z-order EnumWindows(MyEnumWindowsProc, (LPARAM)(&windowsInZOrder)); @@ -753,7 +753,7 @@ void CSystem::ChangeZPosInOrder() if (logging) { - Log(LOG_DEBUG, L"2: ----- AFTER -----"); + CLogger::Debug(L"2: ----- AFTER -----"); // Log all windows in Z-order EnumWindows(MyEnumWindowsProc, (LPARAM)NULL); @@ -796,7 +796,7 @@ void CSystem::PrepareHelperWindow(HWND WorkerW) { if (logging) { - LogWithArgs(LOG_DEBUG, L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - %s", + CLogger_DebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - %s", c_HelperWindow, WorkerW, hwnd, windowText, className, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL"); } return; @@ -805,7 +805,7 @@ void CSystem::PrepareHelperWindow(HWND WorkerW) if (logging) { DWORD err = GetLastError(); - LogWithArgs(LOG_DEBUG, L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - FAILED (ErrorCode=0x%08X)", + CLogger_DebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=0x%p (\"%s\" %s) - FAILED (ErrorCode=0x%08X)", c_HelperWindow, WorkerW, hwnd, windowText, className, err); } } @@ -813,7 +813,7 @@ void CSystem::PrepareHelperWindow(HWND WorkerW) if (logging) { - LogWithArgs(LOG_DEBUG, L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_TOPMOST - %s", + CLogger_DebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_TOPMOST - %s", c_HelperWindow, WorkerW, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL"); } } @@ -824,7 +824,7 @@ void CSystem::PrepareHelperWindow(HWND WorkerW) if (logging) { - LogWithArgs(LOG_DEBUG, L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_BOTTOM - %s", + CLogger_DebugF(L"System: HelperWindow: hwnd=0x%p (WorkerW=0x%p), hwndInsertAfter=HWND_BOTTOM - %s", c_HelperWindow, WorkerW, (GetWindowLongPtr(c_HelperWindow, GWL_EXSTYLE) & WS_EX_TOPMOST) ? L"TOPMOST" : L"NORMAL"); } } @@ -851,7 +851,7 @@ bool CSystem::CheckDesktopState(HWND WorkerW) if (Rainmeter->GetDebug()) { - LogWithArgs(LOG_DEBUG, L"System: \"Show %s\" has been detected.", + CLogger_DebugF(L"System: \"Show %s\" has been detected.", c_ShowDesktop ? L"desktop" : L"open windows"); } @@ -957,7 +957,7 @@ LRESULT CALLBACK CSystem::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lP break; case WM_DISPLAYCHANGE: - Log(LOG_NOTICE, L"System: Display settings changed"); + CLogger::Notice(L"System: Display settings changed"); ClearMultiMonitorInfo(); CConfigParser::ClearMultiMonitorVariables(); case WM_SETTINGCHANGE: @@ -965,7 +965,7 @@ LRESULT CALLBACK CSystem::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lP { if (uMsg == WM_SETTINGCHANGE) // SPI_SETWORKAREA { - Log(LOG_NOTICE, L"System: Work area changed"); + CLogger::Notice(L"System: Work area changed"); UpdateWorkareaInfo(); CConfigParser::UpdateWorkareaVariables(); } @@ -1144,7 +1144,7 @@ void CSystem::SetWallpaper(const std::wstring& wallpaper, const std::wstring& st { if (_waccess(wallpaper.c_str(), 0) == -1) { - LogWithArgs(LOG_ERROR, L"!SetWallpaper: Unable to read file: %s", wallpaper.c_str()); + CLogger_ErrorF(L"!SetWallpaper: Unable to read file: %s", wallpaper.c_str()); return; } @@ -1197,7 +1197,7 @@ void CSystem::SetWallpaper(const std::wstring& wallpaper, const std::wstring& st } else { - Log(LOG_ERROR, L"!SetWallpaper: Invalid style"); + CLogger::Error(L"!SetWallpaper: Invalid style"); } RegCloseKey(hKey); @@ -1239,7 +1239,7 @@ bool CSystem::CopyFiles(std::wstring from, std::wstring to, bool bMove) int result = SHFileOperation(&fo); if (result != 0) { - LogWithArgs(LOG_ERROR, L"Copy error: From %s to %s (%i)", from.c_str(), to.c_str(), result); + CLogger_ErrorF(L"Copy error: From %s to %s (%i)", from.c_str(), to.c_str(), result); return false; } return true; @@ -1282,7 +1282,7 @@ bool CSystem::RemoveFolder(std::wstring folder) int result = SHFileOperation(&fo); if (result != 0) { - LogWithArgs(LOG_ERROR, L"Unable to delete folder %s (%i)", folder.c_str(), result); + CLogger_ErrorF(L"Unable to delete folder %s (%i)", folder.c_str(), result); return false; } return true; @@ -1307,7 +1307,7 @@ void CSystem::UpdateIniFileMappingList() ret = RegQueryInfoKey(hKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, (LPFILETIME)&ftLastWriteTime); if (ret == ERROR_SUCCESS) { - //LogWithArgs(LOG_DEBUG, L"IniFileMapping: numSubKeys=%u, ftLastWriteTime=%llu", numSubKeys, ftLastWriteTime); + //CLogger_DebugF(L"IniFileMapping: numSubKeys=%u, ftLastWriteTime=%llu", numSubKeys, ftLastWriteTime); if (ftLastWriteTime != s_LastWriteTime || numSubKeys != c_IniFileMappings.size()) @@ -1396,7 +1396,7 @@ std::wstring CSystem::GetTemporaryFile(const std::wstring& iniFile) } else // failed { - LogWithArgs(LOG_ERROR, L"Unable to create temporary file to: %s", temporary.c_str()); + CLogger_ErrorF(L"Unable to create temporary file to: %s", temporary.c_str()); temporary = L"?"; } diff --git a/Library/TintedImage.cpp b/Library/TintedImage.cpp index 5760d9b7..8362dfaf 100644 --- a/Library/TintedImage.cpp +++ b/Library/TintedImage.cpp @@ -21,7 +21,7 @@ #include "ConfigParser.h" #include "System.h" #include "Error.h" -#include "Litestep.h" +#include "Logger.h" using namespace Gdiplus; @@ -66,12 +66,12 @@ public: if (iter != c_CacheMap.end()) { (*iter).second->AddRef(); - //LogWithArgs(LOG_DEBUG, L"* ADD: key=%s, ref=%i", key.c_str(), (*iter).second->GetRef()); + //CLogger_DebugF(L"* ADD: key=%s, ref=%i", key.c_str(), (*iter).second->GetRef()); } else { c_CacheMap[key] = new ImageCache(bitmap, hBuffer); - //LogWithArgs(LOG_DEBUG, L"* ADD: key=%s, ref=new", key.c_str()); + //CLogger_DebugF(L"* ADD: key=%s, ref=new", key.c_str()); } } @@ -82,11 +82,11 @@ public: { ImageCache* cache = (*iter).second; cache->Release(); - //LogWithArgs(LOG_DEBUG, L"* REMOVE: key=%s, ref=%i", key.c_str(), cache->GetRef()); + //CLogger_DebugF(L"* REMOVE: key=%s, ref=%i", key.c_str(), cache->GetRef()); if (cache->IsInvalid()) { - //LogWithArgs(LOG_DEBUG, L"* EMPTY-ERASE: key=%s", key.c_str()); + //CLogger_DebugF(L"* EMPTY-ERASE: key=%s", key.c_str()); c_CacheMap.erase(iter); delete cache; } @@ -375,7 +375,7 @@ void CTintedImage::LoadImage(const std::wstring& imageName, bool bLoadAlways) } else { - LogWithArgs(LOG_ERROR, L"%s: Unable to load: %s", m_Name, filename.c_str()); + CLogger_ErrorF(L"%s: Unable to load: %s", m_Name, filename.c_str()); } } CloseHandle(fileHandle); @@ -407,7 +407,7 @@ void CTintedImage::LoadImage(const std::wstring& imageName, bool bLoadAlways) } else { - LogWithArgs(LOG_ERROR, L"%s: Unable to open: %s", m_Name, filename.c_str()); + CLogger_ErrorF(L"%s: Unable to open: %s", m_Name, filename.c_str()); if (fileHandle != INVALID_HANDLE_VALUE) { @@ -673,7 +673,7 @@ void CTintedImage::ReadOptions(CConfigParser& parser, const WCHAR* section) if (m_CropMode < CROPMODE_TL || m_CropMode > CROPMODE_C) { m_CropMode = CROPMODE_TL; - LogWithArgs(LOG_ERROR, L"%s=%s (origin) is not valid in [%s]", m_OptionArray[OptionIndexImageCrop], crop, section); + CLogger_ErrorF(L"%s=%s (origin) is not valid in [%s]", m_OptionArray[OptionIndexImageCrop], crop, section); } } } @@ -777,7 +777,7 @@ void CTintedImage::ReadOptions(CConfigParser& parser, const WCHAR* section) } else { - LogWithArgs(LOG_ERROR, L"%s=%s (origin) is not valid in [%s]", m_OptionArray[OptionIndexImageFlip], flip, section); + CLogger_ErrorF(L"%s=%s (origin) is not valid in [%s]", m_OptionArray[OptionIndexImageFlip], flip, section); } if (!m_DisableTransform) diff --git a/Library/TrayWindow.cpp b/Library/TrayWindow.cpp index 1d7c0836..809f672e 100644 --- a/Library/TrayWindow.cpp +++ b/Library/TrayWindow.cpp @@ -434,14 +434,14 @@ void CTrayWindow::ReadOptions(CConfigParser& parser) { delete m_Bitmap; m_Bitmap = NULL; - LogWithArgs(LOG_WARNING, L"Bitmap image not found: %s", imagePath); + CLogger_WarningF(L"Bitmap image not found: %s", imagePath); } } } } else { - LogWithArgs(LOG_ERROR, L"No such TrayMeter: %s", type); + CLogger_ErrorF(L"No such TrayMeter: %s", type); } TryAddTrayIcon(); @@ -491,15 +491,15 @@ LRESULT CALLBACK CTrayWindow::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA break; case IDM_STARTLOG: - Rainmeter->StartLogging(); + CLogger::GetInstance().StartLogFile(); break; case IDM_STOPLOG: - Rainmeter->StopLogging(); + CLogger::GetInstance().StopLogFile(); break; case IDM_DELETELOGFILE: - Rainmeter->DeleteLogFile(); + CLogger::GetInstance().DeleteLogFile(); break; case IDM_DEBUGLOG: @@ -678,7 +678,7 @@ LRESULT CALLBACK CTrayWindow::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA return 0; case RAINMETER_QUERY_ID_LOG_PATH: - sendCopyData(Rainmeter->GetLogFile()); + sendCopyData(CLogger::GetInstance().GetLogFilePath()); return 0; case RAINMETER_QUERY_ID_CONFIG_EDITOR: diff --git a/Library/lua/LuaManager.cpp b/Library/lua/LuaManager.cpp index b1e8b9b9..786a2ebc 100644 --- a/Library/lua/LuaManager.cpp +++ b/Library/lua/LuaManager.cpp @@ -70,7 +70,7 @@ void LuaManager::ReportErrors(lua_State* L, const std::wstring& file) std::wstring str(file, file.find_last_of(L'\\') + 1); str += StringUtil::Widen(error); - LogWithArgs(LOG_ERROR, L"Script: %s", str.c_str()); + CLogger_ErrorF(L"Script: %s", str.c_str()); } void LuaManager::PushWide(lua_State* L, const WCHAR* str) diff --git a/Library/lua/glue/LuaGlobal.cpp b/Library/lua/glue/LuaGlobal.cpp index e54515c9..a8b5bf61 100644 --- a/Library/lua/glue/LuaGlobal.cpp +++ b/Library/lua/glue/LuaGlobal.cpp @@ -18,7 +18,8 @@ #include "../../StdAfx.h" #include "../LuaManager.h" -#include "../../Litestep.h" +#include "../../Logger.h" +#include "../../../Common/StringUtil.h" static int Print(lua_State* L) { @@ -53,7 +54,7 @@ static int Print(lua_State* L) lua_pop(L, 1); } - Log(LOG_DEBUG, StringUtil::Widen(message).c_str()); + CLogger::Debug(StringUtil::Widen(message).c_str()); return 0; }