基于事件写入日志文件

LogFileEventConsumer 类可以在指定事件发生时将预定义的文本写入日志文件。 此类是 WMI 提供的标准事件使用者。

使用标准使用者的基本过程始终相同,记录在使用标准使用者监视和响应事件中。

以下过程添加到基本过程中,且特定于 LogFileEventConsumer 类,描述了如何创建运行程序的事件使用者。

创建将内容写入日志文件的事件使用者

  1. 在托管对象格式 (MOF) 文件中,创建 LogFileEventConsumer 的实例以接收你在查询中请求的事件,在 Name 属性中命名该实例,然后将日志文件的路径放入 Filename 属性中。

    有关详细信息,请参阅设计托管对象格式 (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 指定的行:“日志文件事件所有者事件”。

// 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";  
};

使用标准使用者监视和响应事件