日志读写

来源:互联网 发布:免费数据恢复精灵 编辑:程序博客网 时间:2024/06/05 21:53

Step 1. Create a message file(.mc)
;// test.mc
; // ***** sample.mc *****

; // This is the header.

MessageIdTypedef=DWORD

SeverityNames=(Success=0x0:STATUS_SEVERITY_SUCCESS
    Informational=0x1:STATUS_SEVERITY_INFORMATIONAL
    Warning=0x2:STATUS_SEVERITY_WARNING
    Error=0x3:STATUS_SEVERITY_ERROR
    )


FacilityNames=(System=0x0:FACILITY_SYSTEM
    Runtime=0x2:FACILITY_RUNTIME
    Stubs=0x3:FACILITY_STUBS
    Io=0x4:FACILITY_IO_ERROR_CODE
)

LanguageNames=(English=0x409:MSG00409)

; // The following are message definitions.

MessageId=0x1
Severity=Error
Facility=Runtime
SymbolicName=TEST_START_ID
Language=English
This is simulate START event message.
.

MessageId=0x2
Severity=Warning
Facility=Runtime
SymbolicName=TEST_RUNNING_ID
Language=English
This is simulate RUNNING event message.
.

MessageId=0x3
Severity=Informational
Facility=Runtime
SymbolicName=TEST_STOP_ID
Language=English
This is simulate STOP event message.
.


Step 2. mc -U test.mc    // this will generate test.h, test.rc, ***.bin

Step 3. rc -r test.rc    // this will generate test.res

Step 4. link -dll -noentry /MACHINE:x86 -out:testevent.dll test.res

Step 5. Adding a Source to the Registry // can using under project to do that note: need run as Administrator

#include <windows.h>
#include <iostream>
#include <strsafe.h>

int __cdecl wmain(int argc, LPWSTR *argv)
{
    // Name of the event log.
    wchar_t *logName = L"Application";
    // Event Source name.
    wchar_t *sourceName = L"TestEventSourceName";
    // DLL that contains the event messages (descriptions).
    wchar_t *dllName = L"C:\\test\\testevent.dll";
    // This number of categories for the event source.
    DWORD dwCategoryNum = 1;
  
   HKEY hk;
   DWORD dwData, dwDisp;
   TCHAR szBuf[MAX_PATH];
   size_t cchSize = MAX_PATH;

   // Create the event source as a subkey of the log.
   HRESULT hr = StringCchPrintf(szBuf, cchSize,
      L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s",
      logName, sourceName);
 
   LONG  ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, szBuf,
          0, NULL, REG_OPTION_NON_VOLATILE,
          KEY_WRITE, NULL, &hk, &dwDisp);
   if (ret)
   {
      printf("Could not create the registry key.");
   DWORD lerr = GetLastError();
      return 0;
   }
 
   // Set the name of the message file.
 
   if (RegSetValueEx(hk,             // subkey handle
          L"EventMessageFile",        // value name
          0,                         // must be zero
          REG_EXPAND_SZ,             // value type
          (LPBYTE) dllName,          // pointer to value data
          (DWORD) (lstrlen(dllName)+1)*sizeof(TCHAR))) // data size
   {
      printf("Could not set the event message file.");
      RegCloseKey(hk);
      return 0;
   }
 
   // Set the supported event types.
 
   dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
        EVENTLOG_INFORMATION_TYPE;
 
   if (RegSetValueEx(hk,      // subkey handle
           L"TypesSupported",  // value name
           0,                 // must be zero
           REG_DWORD,         // value type
           (LPBYTE) &dwData,  // pointer to value data
           sizeof(DWORD)))    // length of value data
   {
      printf("Could not set the supported types.");
      RegCloseKey(hk);
      return 0;
   }
 
   // Set the category message file and number of categories.

   if (RegSetValueEx(hk,              // subkey handle
           L"CategoryMessageFile",     // value name
           0,                         // must be zero
           REG_EXPAND_SZ,             // value type
           (LPBYTE) dllName,          // pointer to value data
           (DWORD) (lstrlen(dllName)+1)*sizeof(TCHAR))) // data size
   {
      printf("Could not set the category message file.");
      RegCloseKey(hk);
      return 0;
   }
 
   if (RegSetValueEx(hk,            // subkey handle
           L"CategoryCount",         // value name
           0,                       // must be zero
           REG_DWORD,               // value type
           (LPBYTE) &dwCategoryNum, // pointer to value data
           sizeof(DWORD)))          // length of value data
   {
      printf("Could not set the category count.");
      RegCloseKey(hk);
      return 0;
   }

   RegCloseKey(hk);
   return 1;
}

//this project will create HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\TestEventSourceName key and content

Step 6. Report event message // can using under project
#include <iostream>
#include <windows.h>

#include "test.h"


void __cdecl wmain(int argc, LPWSTR *argv)
{
    wchar_t *sourceName = L"TestEventSourceName";  // The event source name.
    DWORD dwEventID = TEST_START_ID;               // The event identifier.
    WORD cInserts = 1;                               // The count of insert strings.
    LPCWSTR szMsg = L"start";                 // The insert strings.

    HANDLE h;

    // Get a handle to the event log.
    h = RegisterEventSource(NULL,  // Use local computer.
            sourceName);           // Event source name.
    if (h == NULL)
    {
        printf("Cannot register the event source.");
        return;
    }
    DWORD dwPID = GetCurrentProcessId();             // Get current process id
 DWORD dwTID = GetCurrentThreadId();        // Get current thread id
       
 wchar_t buf[1000] =  {0};
 wsprintfW(buf,L"Process ID: %d\nThead ID: %d\nMessage: \n%s\n",GetCurrentProcessId(),GetCurrentThreadId(),szMsg);
 std::wstring ds = buf;
 const wchar_t *p = ds.c_str();
    // Report the event.
 
    if (!ReportEvent(h,           // Event log handle.
            EVENTLOG_ERROR_TYPE,  // Event type.
            NULL,                 // Event category. 
            dwEventID,            // Event identifier.
            NULL,                 // No user security identifier.
            cInserts,             // Number of substitution strings.
            0,                    // No data.
            &p,               // Pointer to strings.
            NULL))                // No data.
    {
        printf("Cannot report the event.");
    }
 
 dwEventID = TEST_RUNNING_ID;
 LPCWSTR szMsg2 = L"running";
 if (!ReportEvent(h,           // Event log handle.
            EVENTLOG_WARNING_TYPE,  // Event type.
            NULL,                 // Event category. 
            dwEventID,            // Event identifier.
            NULL,                 // No user security identifier.
            cInserts,             // Number of substitution strings.
            0,                    // No data.
            &szMsg2,               // Pointer to strings.
            NULL))                // No data.
    {
        printf("Cannot report the event.");
    }

 dwEventID = TEST_STOP_ID;
 LPCWSTR szMsg3 = L"information";
 if (!ReportEvent(h,           // Event log handle.
            EVENTLOG_INFORMATION_TYPE,  // Event type.
            NULL,                 // Event category. 
            dwEventID,            // Event identifier.
            NULL,                 // No user security identifier.
            cInserts,             // Number of substitution strings.
            0,                    // No data.
            &szMsg3,               // Pointer to strings.
            NULL))                // No data.
    {
        printf("Cannot report the event.");
    }

    DeregisterEventSource(h);
    return;
}

 

Step 7. parser event message

#include <windows.h>
#include <tchar.h>
#include <iostream>

#include "test.h"

#define BUFFER_SIZE 512

void __cdecl wmain(int argc, LPWSTR *argv)
{
    // Name of the event log.
    wchar_t *logName = L"Application";
    // Event Source name.
    wchar_t *sourceName = L"TestEventSourceName";
    // This is the event ID that you are querying for.
    DWORD dwMessageID = TEST_START_ID; 
    // DLL that contains the event messages (descriptions).
    wchar_t *dllName = L"C:\\test\\testevent.dll";
   
  
    HANDLE h, ghResDll;
    char lpMsgBuf1[BUFFER_SIZE];
    EVENTLOGRECORD *pevlr;
    BYTE bBuffer[BUFFER_SIZE];
    DWORD dwRead, dwNeeded, dwThisRecord;
    LPCTSTR lpSourceName;

    // Step 1: ---------------------------------------------------------
    // Open the event log. ---------------------------------------------
    h = OpenEventLog( NULL,               // Use the local computer.
        logName);
    if (h == NULL)
    {
        std::wcout << L"Could not open the event log." << std::endl;;
        return;
    }
   
    // Step 2: ---------------------------------------------------------
    // Initialize the event record buffer. -----------------------------
    pevlr = (EVENTLOGRECORD *) &bBuffer;

    // Step 3: ---------------------------------------------------------
    // Load the message DLL file. --------------------------------------
    ghResDll =  LoadLibrary(dllName);

    // Step 4: ---------------------------------------------------------
    // Get the record number of the oldest event log record. -----------
    //BOOL bRet = GetOldestEventLogRecord(h, &dwThisRecord);
 BOOL bRet = GetNumberOfEventLogRecords(h, &dwThisRecord);
    // Step 5: ---------------------------------------------------------
    // When the event log is opened, the position of the file pointer
    // is at the beginning of the log. Read the event log records
    // sequentially until the last record has been read.
    while (ReadEventLog(h,                // Event log handle
        EVENTLOG_FORWARDS_READ |          // Reads forward
        EVENTLOG_SEQUENTIAL_READ,         // Sequential read
        0,                                // Ignored for sequential read
        pevlr,                            // Pointer to buffer
        BUFFER_SIZE,                      // Size of buffer
        &dwRead,                          // Number of bytes read
        &dwNeeded))                       // Bytes in the next record
    {
        while (dwRead > 0)
        {
            // Get the event source name.
            lpSourceName = (LPCTSTR) ((LPBYTE) pevlr + sizeof(EVENTLOGRECORD));       

            // Print the information if the event source and the message
            // match the parameters
           
            if ((lstrcmp(lpSourceName,sourceName) == 0)/* &&
                (dwMessageID == pevlr->EventID)*/)
            {
                // Step 6: ----------------------------------------------
                // Retrieve the message string. -------------------------
                FormatMessage(
                    FORMAT_MESSAGE_FROM_HMODULE, // Format of message
                    ghResDll,                    // Handle to the DLL file
                    pevlr->EventID,              // Event message identifier
                    MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
                    (LPTSTR) &lpMsgBuf1,         // Buffer that contains message
                    BUFFER_SIZE,                 // Size of buffer
                    NULL);                       // Array of insert values
               
                // Print the event identifier, event type, event category,
                // event source, and event message.
                std::wcout << dwThisRecord++ <<
                    L"  Event ID: " << pevlr->EventID << L" Event Type: " <<
                    std::endl;

                switch(pevlr->EventType)
                {
                    case EVENTLOG_ERROR_TYPE:
                        std::wcout << L"EVENTLOG_ERROR_TYPE  " << std::endl;
                        break;
                    case EVENTLOG_WARNING_TYPE:
                        std::wcout << L"EVENTLOG_WARNING_TYPE  " << std::endl;
                        break;
                    case EVENTLOG_INFORMATION_TYPE:
                        std::wcout << L"EVENTLOG_INFORMATION_TYPE  " << std::endl;
                        break;
                    case EVENTLOG_AUDIT_SUCCESS:
                        std::wcout << L"EVENTLOG_AUDIT_SUCCESS  " << std::endl;
                        break;
                    case EVENTLOG_AUDIT_FAILURE:
                        std::wcout << L"EVENTLOG_AUDIT_FAILURE  " << std::endl;
                        break;
                    default:
                        std::wcout << L"Unknown  " << std::endl;
                        break;
                }  

                std::wcout << L"  Event Category: " <<
                    pevlr->EventCategory << L" Event Source: " <<
                    lpSourceName << L" Message: " << (LPTSTR) lpMsgBuf1 <<
                    std::endl;
            }
        
            dwRead -= pevlr->Length;
            pevlr = (EVENTLOGRECORD *) ((LPBYTE) pevlr + pevlr->Length);
        }

        pevlr = (EVENTLOGRECORD *) &bBuffer;
    }
  
    // Step 7: -------------------------------------------------------------
    // Close the event log.
    CloseEventLog(h);

 

 

 

 

 

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 前田香织侵犯中文字幕 佐佐木明希上司中文字幕迅雷 医生d淫孕妇 公公一晚上要8次 公公现在就想要白关婷中文字幕 丈夫上司侵犯系列在线 义父犯美媳嫁樱花叶菜在线播放 儿子的妻子在线中文字幕云播 老公去世公公每天晚上抱着我睡 被水电工掠夺的妻子在线播放b 佐佐木明希大嫂中文字幕全集 善良的小妻子字幕 公公在我洗碗时在厨房要了我 大嫂被肉翻了天佐佐木明希1 教师蕾丝短裙中文字幕 瓜棚里和大嫂乱禽 强睡大嫂中文字 免费 佐佐木明希 房东中文字幕 与父亲干柴烈火 中文字幕丈夫不在 9大嫂被禽翻中文字幕 侵犯你的贞洁 中文字幕 年轻的妻子在线观中文字幕 大嫂被翻天了佐佐木b希中文7 美丽的大嫂中文字幕影迅雷下载 邻居的妻子中文字幕下载 神马电影院电影中文 神马电影院理论中文 女儿的朋友5中文神马电影院 97手机2019电影院专用版中文 厨房里进入朋友的老婆 中文版电影院 神马电影院 中文 儿子的妻子中文字幕 下载 樱桃中文版电影院 大富豪电影院韩国中文 老婆的闺蜜们喝醉了在家 中文潮人影院您手中的电影院 朋友不在晚上去他家干 趁兄弟喝醉上他女朋友在线播放 神马电影院午伦中文