【注】c++這塊的日志類,很容易因為編譯環境設定字符集,引數型別等問題帶來一些不方便呼叫的問題, 那么一開始可以在日志中提供寬位元組型別的傳參處理,否則可能會部分情況下可以,部分情況下會丟失資訊,
Log.h檔案內容
#pragma once #include "stdio.h" #include "windows.h" #include "tchar.h" #include "shlwapi.h" #pragma comment(lib,"shlwapi.lib") class Log { public: //這個WriteByW比較兼容,Write在遇到ansi時有時無法列印出來. static bool WriteByW(const wchar_t* logStr, TCHAR* logType = _T("log"), TCHAR * logDir = _T("log")); //引數如何區分目錄和檔案: //如果最后有\\肯定是目錄 //如果最后又后綴".",則肯定是檔案 //如果最后沒有\\,也沒有后綴'.",則認為是路徑 static bool CreateFolder(TCHAR* pszPath); private: Log(); ~Log(); static Log* InitInstance(); //當前路徑 static TCHAR s_curPath[MAX_PATH]; //日志目錄 static TCHAR s_logDir[MAX_PATH]; //日志的全目錄路徑 static TCHAR s_logPath[MAX_PATH]; static Log* s_instance; };
Log.cpp的檔案內容
/* 使用示例:
正常引入頭檔案 Log::WriteByW(L"呼叫了日志(byW)"); Log::WriteByW(AnsiToUNICODE(upload_id).c_str()); */ #include "stdafx.h" #include "Log.h" Log* Log::s_instance = NULL; TCHAR Log::s_curPath[MAX_PATH]; TCHAR Log::s_logPath[MAX_PATH]; TCHAR Log::s_logDir[MAX_PATH]; Log * Log::InitInstance() { if (s_instance == NULL) { s_instance = new Log(); } return s_instance; } bool Log::WriteByW(const wchar_t * logStr, TCHAR * logType, TCHAR * logDir) { wcscpy_s(s_logDir, logDir);//_tcscpy(s_logDir, logDir); InitInstance(); SYSTEMTIME time; GetLocalTime(&time); WCHAR date[128] = { 0 }, filename[128] = { 0 }, hh[50] = _T("\n"); swprintf_s(date, _T("%d-%02d-%02d %02d:%02d:%02d"), time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);//_stprintf swprintf_s(filename, _T("%s\\%s_%d-%02d-%02d.log"), s_logPath, logType, time.wYear, time.wMonth, time.wDay);//_stprintf FILE* fp; _tfopen_s(&fp, filename, _T("a,ccs=UTF-8"));//_stprintf WCHAR newstr[1024] = { 0 }; swprintf_s(newstr, _T("%s : %s\n"), date, logStr); if (fp) { fwrite(newstr, sizeof(WCHAR), _tcslen(newstr), fp); fclose(fp); return true; } else { return false; } } bool Log::CreateFolder(TCHAR* pszPath) { //如果后面有\\則是路徑,如果沒有,但有后綴,則是檔案,無后綴則也是路徑 TCHAR szPath[_MAX_PATH] = { 0 }; wcsncpy_s(szPath, pszPath, _MAX_PATH);//_tcsncpy szPath[_MAX_PATH - 1] = 0; TCHAR* pdot = _tcsrchr(szPath, _T('.')); TCHAR* psp = _tcsrchr(szPath, _T('\\')); if (psp && pdot && pdot > psp) { //在路徑最后找到上面兩個字符證明是檔案,去掉檔案名 psp[0] = 0; } else { //預設是個目錄,這個地方可能吧沒有后綴的檔案當作目錄,這里不做處理,默認當成目錄 } PathAddBackslash(szPath); if (PathIsDirectory(szPath)) return true; psp = _tcschr(szPath, _T('\\')); while (psp) { *psp = 0; if (!PathIsDirectory(szPath)) { if (!CreateDirectory(szPath, 0)) return false; } *psp = _T('\\'); psp = _tcschr(psp + 1, _T('\\')); } return true; }; Log::Log() { //取當前執行模塊的全路徑,如果此模塊是被其它程式呼叫的,回傳的路徑還是這個程式的路徑 ::GetModuleFileName(NULL, s_curPath, MAX_PATH); //從路徑中移除檔案名 PathRemoveFileSpec(s_curPath); swprintf_s(s_logPath, _T("%s\\%s"), s_curPath, s_logDir);//_stprintf if (!CreateFolder(s_logPath)) { MessageBox(NULL, _T("日志目錄創建失敗"), NULL, 0); } } Log::~Log() { }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/24307.html
標籤:C++
