共用方式為


根據事件寫入記錄檔

當發生指定的事件時 ,LogFileEventConsumer 類別可以將預先定義的文字寫入記錄檔。 這個類別是 WMI 提供的標準事件取用者。

使用標準取用者的基本程式一律相同,且位於 使用標準取用者的監視和回應事件中。

下列程式會新增至基本程式,專屬於 LogFileEventConsumer 類別,並說明如何建立執行程式的事件取用者。

建立寫入記錄檔的事件取用者

  1. 在 Managed 物件格式 (MOF) 檔案中,建立 LogFileEventConsumer 的實例以接收您在查詢中要求的事件、將實例命名為 Name 屬性,然後將記錄檔的路徑放在 Filename 屬性中。

    如需詳細資訊,請參閱 設計 Managed 物件格式 (MOF) 類別

  2. 提供文字模板,以寫入 Text 屬性中的記錄檔。

    如需詳細資訊,請參閱 使用標準字串範本

  3. 建立 __EventFilter 的實例 並定義查詢以指定將啟動取用者的事件。

    如需詳細資訊,請參閱 使用 WQL 查詢

  4. 建立 __FilterToConsumerBinding 實例,將篩選準則與 LogFileEventConsumer實例產生關聯。

  5. 若要控制誰讀取或寫入您的記錄檔,請將記錄檔所在目錄的安全性設定為所需的層級。

  6. 使用 Mofcomp.exe編譯 MOF 檔案。

範例

本節中的範例位於 MOF 程式碼中,但您可以使用 適用于 WMI 的腳本 APIWMI 的 COM API,以程式設計方式建立實例。 此範例會使用標準 LogFileEventConsumer 建立名為 LogFileEvent 的取用者類別,以在建立 LogFileEvent 類別的實例時,將一行寫入檔案 c:\Logfile.log。

下列程式描述如何使用 範例。

若要使用範例

  1. 將下面的 MOF 清單複製到文字檔中,並以 .mof 副檔名儲存。

  2. 在命令視窗中,使用下列命令編譯 MOF 檔案。

    Mofcompfilename**.mof**

  3. 開啟 Logfile.log 以查看 LogFileEvent.Name 所指定的行:「Logfile 事件取用者事件」。

// Set the namespace as root\subscription.
// The LogFileEventConsumer is already compiled 
//     in the root\subscription namespace. 

#pragma namespace ("\\\\.\\Root\\subscription")

class LogFileEvent
{
    [key]string Name;
};

// Create an instance of the standard log
// file consumer and give it the alias $CONSUMER

instance of LogFileEventConsumer as $CONSUMER
{
    // If the file does not already exist, it is created.
    Filename = "c:\\Logfile.log";  
    IsUnicode = FALSE;
    // Name of this instance of LogFileEventConsumer
    Name = "LogfileEventConsumer_Example";  
    // See "Using Standard String Templates"; 
    Text = "%TargetInstance.Name%"; 
    // TargetInstance is the instance of LogFileEvent 
    //    requested in the filter        
                                         
};

// Create an instance of the event filter 
// and give it the alias $FILTER
// Query for any instance operation type,
// such as instance creation, for LogFileEvent class

instance of __EventFilter as $FILTER
{
    Name = "LogFileFilter";
    Query = "SELECT * FROM __InstanceOperationEvent "
        "WHERE TargetInstance.__class = \"LogFileEvent\"";
    QueryLanguage = "WQL";
};

// Create an instance of the binding.

instance of __FilterToConsumerBinding
{
    Consumer=$CONSUMER;
    Filter=$FILTER;
 DeliverSynchronously=FALSE;
};

// Create an instance of this class right now
// Look at the file c:\Logfile.log to see
// that a line has been written.

instance of LogFileEvent
{
 Name = "Logfile Event Consumer event";  
};

使用標準取用者監視和回應事件