Одной из распространенных задач администрирования web-сайтов является анализ log-файлов и сбор данных из них. Поговорим об этой задаче на примере IIS 5.0 (Internet Information Service). В связи с тем, что данный HTTP сервер поддерживает несколько форматов таких файлов (формат W3C, формат NCSA, а также свой формат IIS), анализ log-файлов превращается в довольно трудоемкую задачу. Кроме того для формата W3C список полей может конфигурироваться, что задачу не облегчает.
Но к счастью вместе с IIS 5.0 в составе прочих компонентов, поставляется компонент MSWC.IISLog, который предназначен для получения данных из log-файлов и предоставляет для этой цели интерфейс ILogScripting. Находится он в файле %windir%system32inetsrvlogscrpt.dll. С помощью этого интерфейса можно читать данные из log-файла, записывать прочтенные данные в другой файл.
Перед тем как начать работу с какими-либо log-файлом, его нужно открыть. Дляэтогослужитметод OpenLogFile:
HRESULT OpenLogFile( [in] BSTR szLogFileName,
[in] IOMode Mode,
[in] BSTR szServiceName,
[in] long iServiceInstance,
[in] BSTR szOutputLogFileFormat),
где в параметре szLogFileName задается полный путь к файлу; параметр Mode может принимать следующие значения:
ForReading - файл будет открыт для чтения
ForWriting - файл будет открыт для записи;
в параметре szServiceName задается название службы, которой был создан данный файл (например "W3SVC"); парметр iServiceInstance указывает номер экземпляра сервера данной службы (напр. 1); в параметре szOutputLogFileFormat задается название формата, в котором будут читаться или записываться данные (например "W3C"). Если метод выполнился успешно то возвращается 0.
Для чтения данных из файла служит метод ReadLogRecord:
HRESULT ReadLogRecord(),
который читает строку из текущей файловой позиции и перемещает позиционер файла дальше. Мы можем получить эти данные в виде значений конкретных полей с помощью множества методов, которые возвращают эти значения:
get_DateTime |
Отображение даты и времени по Гринвичу (GMT) |
get_ServiceName |
Отображение имени службы |
get_ServerName |
Отображение имени сервера |
get_ClientIP |
Отображение имени узла клиента |
get_UserName |
Отображение имени пользователя |
get_ServerIP |
Отображение IP-адреса сервера |
get_Method |
Отображение типа операции |
get_URIStem |
Отображение адреса URL |
get_URIQuery |
Отображение всех параметров, передаваемых с запросом |
get_TimeTaken |
Отображение общего времени обработки |
get_BytesSent |
Отображение числа переданных байтов |
get_BytesReceived |
Отображение числа полученных байтов |
get_Win32Status |
Отображение кода состояния Win32 |
get_ProtocolStatus |
Отображение состояния протокола |
get_ServerPort |
Отображение номера порта |
get_ProtocolVersion |
Отображение строки версии |
get_UserAgent |
Отображение строки агента пользователя |
get_Cookie |
Отображение имени Cookie клиента |
get_Referer |
Отображение страницы источника ссылки |
get_CustomFields |
Отображение массива специальных заголовков |
Всеэтиметодыимеютодинформат: HRESULT get_MethodName(VARIANT *pValue). В параметре pValue будет возвращено интересующее нас значение. Если значение запрашиваемого параметра равно "-", то тип pValue будет VT_EMPTY. Если же по каким-то причинам параметр не будет найден в log-файле (напр. параметр отключен, или текущая строка - незначащая), то тип pValue будет VT_NULL.
Для того, чтобы мы сильно не увлеклись существует метод AtEndOfLog, который подобно привычному feof возвращает (или не возвращает :)) признак достижения конца файла и выглядит приблизительно так:
HRESULT AtEndOfLog([out, retval] VARIANT_BOOL* pfEndOfRead)
В параметре pfEndOfRead, собственно, и возвращается интересующий нас признак, что позволяет нам все таки когда-нибудь завершить обработку log-файла.
Помимо всего этого имеется еще метод WriteLogRecord, который позволяет записывать данные, полученные из одного log-файла в другой. Формат его следующий:
HRESULT WriteLogRecord([in] ILogScripting* pILogScripting),
где
pILogScripting - это указатель на экземпляр ILogScripting, в котором содержатся прочитанные данные. Этот метод похож на ReadLogRecord тем, что записывает в файл одну строку (напомню, что ReadLogRecord читает одну строку).
Для закрытия открытых файлов служит метод CloseLogFiles:
HRESULT CloseLogFiles([in] IOMode Mode),
в котором параметр Mode может принимать следующие значения:
ForReading - будут закрыты файлы, открытые для чтения
ForWriting - будут закрыты файлы, открытые для записи
AllOpenFiles - будут закрыты все открытые файлы
Чтобы доступиться к компоненту MSWC.IISLog из C++ надо иметь .h файл, описывающий интерфейс ILogScripting. Сделать его нам поможет утилита OLEViewer, которая входит в состав Visual Studio. В меню "File" этой утилиты выберем пункт "View TypeLib" и укажем файл logscrpt.dll (естественно полный путь к нему). В новом окне откроется библиотека типов нашего объекта, которую мы сохраним в качестве .idl файла.
Для этого в меню "File" выберем пункт "Save as", укажем тип файла "idl", и сохраним его в некое место (например туда, где находится проект), к примеру, назвав его "logscrpt.idl". Все бы хорошо, да только в новоиспеченном файле придется сделать косметические изменения. Во-первых в самое начало файла надо вставить следующие строчки:
cpp_quote("DEFINE_GUID(CLSID_LogScripting, 0x26B9ED02, 0xA3D8, 0x11D1, 0x8B, 0x9C, 0x08, 0x00, 0x09, 0xDC, 0xC2, 0xFA);")
cpp_quote("DEFINE_GUID(IID_ILogScripting, 0x26B9ECFF, 0xA3D8, 0x11D1, 0x8B, 0x9C, 0x08, 0x00, 0x09, 0xDC, 0xC2, 0xFA);")
Во-вторых строчки
typedef enum {
ForReading = 1,
ForWriting = 2,
AllOpenFiles = 32
} IOMode;
надо перенести так, чтобы они находились до определения ILogScripting интерфейса.
Теперь осталось только сгенерировать файл logscrpt.h с помощью команды midl.exe logscrpt.idl /h logscrpt.h (проверьте путь к компилятору midl).
В заключение приведу пример программы работы с интерфейсом, которая получает в качестве параметров командной строки путь к log-файлу, название службы, название формата файла, номер экземпляра сервера и выдает на экран список всех URL адресов, к которым были зафиксированы обращения в этом файле. Вот пример вызова этой программы:
logging.exe d:logsw3svc2ex01060515.log W3SVC W3C 2
#include
#include
#include
#include
#include "logscrpt.h"
#define SOME_ERROR(lpszErrorText, nErrorNum)
printf("%s: %X
", lpszErrorText, nErrorNum);
throw nErrorNum;
int main(int argc, char *argv[])
{
HRESULT hres;
VARIANT vParam;
short nEndOfFile;
_bstr_t bstrLogFile;
_bstr_t bstrServiceName;
_bstr_t bstrLogFormat;
long nServerInstance;
_bstr_t bstrUriStem;
// проверка наличия параметров
if (argc < 5)
{
printf("Usage: %s LogFileName ServiceNa
me LogFormatName ServerInstance
", argv[0]);
return 0;
}
// получаем параметры из коммандной строки
try {
bstrLogFile = argv[1];
bstrServiceName = argv[2];
bstrLogFormat = argv[3];
if (!(nServerInstance = atol(argv[4])))
// экземплярсерверанеможетбыть 0
nServerInstance = 1;
}
catch (...) {
printf("Something wrong in parameters!
");
return 0;
}
// это будет ссылка на интерфейс
ILogScripting *pLogScripting = NULL;
try {
// инициализируем COM
if (!SUCCEEDED(hres = CoInitialize(NULL)))
{
SOME_ERROR("CoInitialize error", hres);
}
// теперьсоздадимэкзепляринтерфейса
if (!SUCCEEDED(hres = CoCreateInstance(CLSID_LogScripting,
NULL, CLSCTX_ALL, IID_ILogScripting,
(void **)&pLogScripting)))
{
SOME_ERROR("CoCreateInstance error", hres);
}
// открываем log-файл bstrLogFile для чтения, указывая, что этот
// файл относится к первому экземляру сервера службы W3SVC, а //
// форматунего W3C
if (!SUCCEEDED(hres =
pLogScripting-OpenLogFile(BSTR(bstrLogFile), ForReading,
BSTR(bstrServiceName), 1, BSTR(bstrLogFormat))))
{
SOME_ERROR("OpenLogFile error", hres);
}
// теперь можно приступить к анализу содержимого файла
for ( ;; ) {
// проверим на достижение конца файла
if (!SUCCEEDED(hres =
pLogScripting-AtEndOfLog(&nEndOfFile)))
{
SOME_ERROR("AtEndOfLog error", hres);
}
if (nEndOfFile)
// счастливо выходим
break;
// читаемследующуюзаписьфайла
if (!SUCCEEDED(hres = pLogScripting-ReadLogRecord()))
{
SOME_ERROR("ReadLogRecord error", hres);
}
// получаем из нее параметр адрес URL
if (!SUCCEEDED(hres = pLogScripting-get_URIStem(&vParam)))
{
SOME_ERROR("ReadLogRecord error", hres);
}
if (vParam.vt == VT_BSTR)
{
// если параметр не пуст распечатаем его на экране
bstrUriStem = vParam.bstrVal;
printf("Uri-stem: %s
", LPSTR(bstrUriStem));
}
}
// закрываемфайл
if (!SUCCEEDED(hres = pLogScripting-CloseLogFiles(ForReading)))
{
SOME_ERROR("CloseLogFiles error", hres);
}
}
catch (...) {}
// последние действия по деинициализации
if (pLogScripting != NULL)
pLogScripting-Release();
CoUninitialize();
return hres;
}
Dima Mukalov
Другие работы по теме:
Завадостійке кодування на основі циклічних кодів
Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CRC32", "CRC32CRC32.csproj", "{EE28F805-6DA0-4E7B-89A5-A3B245E1441D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
Пример использования MFC в Visual C
В этой статье будет показано как включить потдержку MFC в Visual C++ на примере двух типов приложений: 1. Консольное приложение 2. Приложение типа Windows Application
Color Theory Essay Research Paper Color TheoryColor
Color Theory Essay, Research Paper Color Theory Color theory encompasses a multitude of definitions, concepts and design applications. All the information would fill several encyclopedias. As an introduction, here are a few basic concepts.
Light Matter Essay Research Paper Inner LightIn
Light Matter Essay, Research Paper Inner Light In order to understand what light is one has to understand how vision works. The process of visual perception is incredibly complex, involving many functions of the brain. In Arthur Zajonc’s book “Catching the Light,” he writes, “?vision requires far more than a functioning physical organ.
Memory Techniques Essay Research Paper Psychology 345Research
Memory Techniques Essay, Research Paper Psychology 345Research paperObjective: I will relate three memories from my experiences at Texas A&M University to three different memory techniques discussed in the book. One memory that I will remember occurred this semester. It involved a girl who was killed in a car accident.
Frege Against Idealism Essay Research Paper Frege
Frege Against Idealism Essay, Research Paper Frege vs. Idealism In a nut shell Idealism is the position that IDEAS, not objects, are the basis of reality. So for idealists the meaning of an expression is the idea associated with that expression. For example, if one were to think of a lamp , then under the idea theory of reference the visual image that we pull up would be the meaning of the expression lamp .
Visual Analysis Essay Research Paper A Tour
Visual Analysis Essay, Research Paper A Tour of the restaurantOn a casual day drive through Old Town Chicago, people may drive by a restaurant with a big sign with two large strange Chinese looking characters and on the bottom says Kamehachi. As one look more closely, the restaurant is pact with people. The valet parking is busy running around, and a line of people waiting to get in.
Musics Influence On People Essay Research Paper
Music is said to have a strong influence on how young impressionable minds live, think and act. However this can t be too much of a contreversy if tv. allows our minds not only be subject to the same ideas, but also it allows our young and innocent to have visual picture of what is going on. To the untrained this would seem like a crime, however this is just a process of growing up and we need to realize that kids will be kids and if we dont allow them to be explorative to what is going on in the world how will they ever be able to make rational grown decisions when their parents arent around?
Senseless A False Sense Of Perception Essay
, Research Paper Senseless: A False Sense of Perception I feel as though I have no choice but to be a skeptic about our ability to know the world on the sense experience given the information that is being
Convergence Of The Twain Essay Research Paper
“The Convergence of the Twain” Personification is “endowing inanimate objects or abstract ideas with life or human characteristics” (Kirszner 2058). In the poem “The Convergence of the Twain” the author?s use of personification allows the reader to make a more fluid transition from the past to the present.
Water Analysis Essay Research Paper Methods of
Water Analysis Essay, Research Paper Methods of Freshwater Analysis: Temperature pH Clarity Suspended Sediments Biotic Index Trent / BMWP Nitrate Level Phosphates Level Ammonia Concentration Visual Description Dissolved Oxygen Bacteria Counts Total Solids Chloride Concentration Iron Concentration Winkler Method of Oxygen Content 1.
Costa Sakellariou Essay Research Paper Costa Sakellariou
Costa Sakellariou Essay, Research Paper Costa Sakellariou Visual art can definitely be seen as a language. With every artist there is always some sort of meaning that they are trying to convey to the viewers of their work. The means of how they deliver that message is the language in which their work uses. In Costa Sakellariou?s work I especially felt there was some sort of language being spoken.
Learning Styles Essay Research Paper Every person
Learning Styles Essay, Research Paper Every person learns differently. From kindergartner to postgraduate levels, only students can do the earning, and they do it in their own particular, individual learning styles. Some children pick something up the first time they hear it. Others may not grasp a concept until they?ve had the chance to see it in print, or to write it themselves.
Learning Styles Compare
& Contrast Essay, Research Paper Learning Styles The purpose of this paper is to identify and compare the meaning as well as the differences of two learning styles as they relate to both the academic and professional realm. I have chosen these two styles because I believe the majority of people are either visual or auditory learners.
Tarzan Of The Apes Essay Research Paper
Tarzan of the Apes When I was reading the story, ?Tarzan of the Apes,? I realized that throughout the whole story he describes the characters very narrative. He describes specifically the characters feelings, movements and characteristics. On the following, I will write about how the author describes the characters to us readers and how it makes this story feel more realistic than what it is.
Visual Art Essay Research Paper VISUAL ARTS
Visual Art Essay, Research Paper VISUAL ARTS “The physical impossibility of death in the mind of someone living” By Damien Hirst (photo courtesy of the saatchi collection)
Visual Impairment Essay Research Paper Vision Impairments
Visual Impairment Essay, Research Paper Vision Impairments ” People catergorized as visually impaired range from individuals with mild visual losses to those with low vision to those who are totally blind” (Winzer,370). Vision impairments does not necessarily mean a total loss of sight. Some visually impaired person can detect light, others can see shapes and forms, and others can see nothing at all.
Presentation Skills Essay Research Paper Presentation SkillsEveryone
Presentation Skills Essay, Research Paper Presentation Skills Everyone knows the value of being able to communicate for a team project or the positive results of a well-written proposal. But in the area of Public Relations, you also need to be able to give an effective, professional presentation and in order to conquer this there are several things you should keep in mind.
Visual Perception Development Essay Research Paper Devlopment
Visual Perception Development Essay, Research Paper Devlopment of Visual Perception The development of visual perception changes through the caurse of life time from birth through adulthood. Sight is produced by taking ?stimulation in the form of light and converting it to electrochemical signals to the brain.? Most of the development of visual perception takes place in infants and then declines in old age.
Psychoology Essay Research Paper Visual sensation differs
Psychoology Essay, Research Paper Visual sensation differs from visual perception even though the two processes form a sequence. Our brain obtains meaning from what we look at through the process of sensation and perception (Grivas Down & Carter pg 77). Though the two systems interact they both serve a different purpose.
Dover Beach Essay Research Paper Dover Beachby
Dover Beach Essay, Research Paper ?Dover Beach? by: Matthew Arnold In the poem ?Dover Beach? by: Matthew Arnold there is a lot of irony, appeal to the auditory and visual sense, and illusions. The tone in this poem is very sad and dismal, but he shows us how to keep faith and hope in spite of that and how important being honest, true, and faithful to one another, really is.
The Masque Of The Red Death By 2
The Masque Of The Red Death By Edgar Allen Poe Essay, Research Paper Edgar Allen Poe’s ?The Masque of the Red Death? is an elaborate allegory that combines objects in the story with visual descriptions to give focus to the reader’s imagination. In the story, a prince named Prospero tries to dodge the Red Death through isolation and seclusion.
Masque Of The Red Death Essay Research
Paper The Masque of the Red Death: Language and Symbolism Edgar Allen Poe’s The Masque of the Red Death is an elaborate allegory that combines objects in the story with visual descriptions to give focus to the reader’s imagination. In the story,
Romeo Juliet- Comparison Between The Screenplay
And The 199 Essay, Research Paper Films are made with the directors different personal opinions based on the original screenplay. For the movie version of Romeo + Juliet (1996), the quote above illustrates this perfectly. For this essay, I will discuss contrasts between the original screenplay, and the film.
Television Essay Research Paper Televised debates between
Television Essay, Research Paper Televised debates between the nominees of the two major parties have become standard fare in contemporary presidential election campaigns. The authors of this important volume maintain that television has altered the very nature of presidential debates profoundly, that the demands of television have dictated the structure and formats of contemporary debates, and that the visual content of presidential debates plays an important role in the way that candidates exercise influence in televised debates.
Art 5 Essay Research Paper ArtArt comes
Art 5 Essay, Research Paper Art comes in many different forms. It isn t just visual work done on canvas using a certain medium, like pencils, watercolors, or oils. Art is just a way in which an individual expresses his or her inner most self, so that others can understand that individuals personality or feelings to their fullest.
Apple Picking Essay Research Paper Images of
Apple Picking Essay, Research Paper Images of Apple Picking Dr. Hofer "After Apple Picking" is fraught with imagery. Frost uses visual, olfactory, kinesthetic, tactile, and auditory imagery throughout this piece. Because the poem is filled with a variety of images, the reader is able to imagine the experience of apple picking.
What Are Visual Defects And How Common
Are They ? Essay, Research Paper What Are Visual Defects and How Common Are They ? Nate Schackow 2nd Period December 17, 1996 The human eye does alot more than allowing you to see. It is very
TV Violence Essay Research Paper Television ViolenceIn
TV Violence Essay, Research Paper Television Violence In today?s society, television violence harmfully affects the minds of children. However, it doesn?t mean that the violence on television is the only source for bad behavior, but it does largely contribute to the situation (Szaflik). For instance, the variety of television programming, which permeates violence, is sitcoms, commercials, and cartoons.
The Job Of A Graphic Designer Essay
, Research Paper Graphic designers create the visual presentation and design of goods, from gravestone markers to detergent boxes, from album covers to dog food cans (The Princeton Review Guide to Your Career.) Graphic artists, or graphic designers, are the bases of the graphic world. It is their designs that are sent to layout artists and then to the printers and then onto the outside world on cd covers, cereal boxes, billboards, posters, and basically anything that has to do with a visual representation.