2017-12-27 1450 views
-1

我正在嘗試使用C++ Builder 6做一個簡單的服務,在那裏我記錄下所有服務的所有事件:OnStart,OnStop,OnCreate ...但是OnExecute,OnStart和OnStop事件從不記錄。我錯過了什麼?在C++ Builder中的服務應用程序6

OnExecute,的OnStart和調用OnStop事件:

void __fastcall TServiceDump::ServiceExecute(TService *Sender) 
{ 
    doSaveLog("ServiceExecute"); 
    while(!Terminated) 
    { 
     ServiceThread->ProcessRequests(true); 
    } 
} 
//--------------------------------------------------------------------------- 
void __fastcall TServiceDump::ServiceStart(TService *Sender, bool &Started) 
{ 
    doSaveLog("ServiceStart"); 
} 
//--------------------------------------------------------------------------- 
void __fastcall TServiceDump::ServiceStop(TService *Sender, bool &Stopped) 
{ 
    doSaveLog("ServiceStop"); 
} 

服務的更多的事件:

void __fastcall TServiceDump::ServiceAfterInstall(TService *Sender) 
{ 
    doSaveLog("ServiceAfterInstall"); 
} 
//--------------------------------------------------------------------------- 

void __fastcall TServiceDump::ServiceAfterUninstall(TService *Sender) 
{ 
    doSaveLog("ServiceAfterUninstall"); 
} 
//--------------------------------------------------------------------------- 

void __fastcall TServiceDump::ServiceBeforeInstall(TService *Sender) 
{ 
    doSaveLog("ServiceBeforeInstall"); 
} 
//--------------------------------------------------------------------------- 

void __fastcall TServiceDump::ServiceBeforeUninstall(TService *Sender) 
{ 
    doSaveLog("ServiceBeforeUninstall"); 
} 

登錄功能(偉大的工作):

void __fastcall TServiceDump::doSaveLog(String msg) 
{ 
    TStrings* list = new TStringList; 
    try 
    { 
     if(FileExists("txt.log")) 
     { 
     list->LoadFromFile("txt.log"); 
     } 
     list->Add(TimeToStr(Now()) + " : " + msg); 
    } 
    catch(Exception& e) 
    { 
     list->Add(TimeToStr(Now()) + ": ERROR " + e.Message); 
    } 

    list->SaveToFile("txt.log"); 
    list->Free(); 
} 

我可以安裝和正確卸載服務,啓動,停止,暫停和重新啓動。

我的日誌文件後安裝:

17:14:16 : ServiceCreate 
17:14:16 : ServiceBeforeInstall 
17:14:16 : ServiceAfterInstall 
17:14:17 : ServiceDestroy 

我已經開始和停了幾次,沒有保存的日誌。卸載後

我的日誌文件:

17:15:44 : ServiceCreate 
17:15:44 : ServiceBeforeUninstall 
17:15:44 : ServiceAfterUninstall 
17:15:45 : ServiceDestroy 

回答

0

我發現了錯誤。在安裝/卸載服務時,如果我喜歡使用「txt.log」,則日誌將保留在項目文件夾中。當服務執行時,它轉到System32或SysWOW64(這是我的情況)。

我解決它移動日誌目錄爲 「C:\ txt.log」:

void __fastcall TServiceDump::doSaveLog(String msg) 
{ 
    TStrings* list = new TStringList; 
    try 
    { 
     if(FileExists("C:\\txt.log")) 
     { 
     list->LoadFromFile("C:\\txt.log"); 
     } 
     list->Add(TimeToStr(Now()) + " : " + msg); 
    } 
    catch(Exception& e) 
    { 
     list->Add(TimeToStr(Now()) + ": ERROR " + e.Message); 
    } 

    list->SaveToFile("C:\\txt.log"); 
    list->Free(); 
} 
相關問題