Writing Performance Data to a Log File
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <pdh.h>
#include <pdhmsg.h>
void
DisplayCommandLineHelp ()
{
_tprintf (TEXT("\n\nOne or more valid log names must be"));
_tprintf (TEXT("specified as a command line argument. The"));
_tprintf (TEXT("\nlog file will be in the CSV log file format."));
return;
}
int __cdecl _tmain (int argc, TCHAR **argv)
{
HQUERY hQuery;
HLOG hLog;
PDH_STATUS pdhStatus;
DWORD dwLogType = PDH_LOG_TYPE_CSV;
HCOUNTER hCounter;
CHAR szCounterPath[45] =
TEXT("\\Processor(0)\\% Processor Time");
DWORD dwCount;
if (argc != 2) {
DisplayCommandLineHelp ();
return -1;
}
// Open a query object.
pdhStatus = PdhOpenQuery (0,
0,
&hQuery);
// Add one counter that will provide the data.
pdhStatus = PdhAddCounter (hQuery,
szCounterPath,
0,
&hCounter);
// Open the log file for write access.
pdhStatus = PdhOpenLog (argv[1],
PDH_LOG_WRITE_ACCESS |
PDH_LOG_CREATE_ALWAYS,
&dwLogType,
hQuery,
0,
NULL,
&hLog);
// Write 50 records to the log file.
for (dwCount = 0; dwCount <= 50; dwCount++) {
pdhStatus = PdhUpdateLog (hLog, TEXT("This is a comment."));
Sleep(1000); // Wait one second between samples for
// the counter to be updated.
}
// Close the query object.
pdhStatus = PdhCloseQuery (hQuery);
// Close the log file.
pdhStatus = PdhCloseLog (hLog,
PDH_FLAGS_CLOSE_QUERY);
return 0;
}