Merge pull request #2 from jkugler/master
[apachelog.git] / apachelog.py
1 #!/usr/bin/env python
2 """Apache Log Parser
3
4 Parser for Apache log files. This is a port to python of Peter Hickman's
5 Apache::LogEntry Perl module:
6 <http://cpan.uwinnipeg.ca/~peterhi/Apache-LogRegex>
7
8 Takes the Apache logging format defined in your httpd.conf and generates
9 a regular expression which is used to a line from the log file and
10 return it as a dictionary with keys corresponding to the fields defined
11 in the log format.
12
13 Example:
14
15     import apachelog, sys
16
17     # Format copied and pasted from Apache conf - use raw string + single quotes
18     format = r'%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
19
20     p = apachelog.parser(format)
21
22     for line in open('/var/apache/access.log'):
23         try:
24            data = p.parse(line)
25         except:
26            sys.stderr.write("Unable to parse %s" % line)
27
28 The return dictionary from the parse method depends on the input format.
29 For the above example, the returned dictionary would look like;
30
31     {
32     '%>s': '200',
33     '%b': '2607',
34     '%h': '212.74.15.68',
35     '%l': '-',
36     '%r': 'GET /images/previous.png HTTP/1.1',
37     '%t': '[23/Jan/2004:11:36:20 +0000]',
38     '%u': '-',
39     '%{Referer}i': 'http://peterhi.dyndns.org/bandwidth/index.html',
40     '%{User-Agent}i': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202'
41     }
42
43 ...given an access log entry like (split across lines for formatting);
44
45     212.74.15.68 - - [23/Jan/2004:11:36:20 +0000] "GET /images/previous.png HTTP/1.1"
46         200 2607 "http://peterhi.dyndns.org/bandwidth/index.html"
47         "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202"
48
49 You can also re-map the field names by subclassing (or re-pointing) the
50 alias method.
51
52 Generally you should be able to copy and paste the format string from
53 your Apache configuration, but remember to place it in a raw string
54 using single-quotes, so that backslashes are handled correctly.
55
56 This module provides three of the most common log formats in the
57 formats dictionary;
58
59     # Common Log Format (CLF)
60     p = apachelog.parser(apachelog.formats['common'])
61
62     # Common Log Format with Virtual Host
63     p = apachelog.parser(apachelog.formats['vhcommon'])
64
65     # NCSA extended/combined log format
66     p = apachelog.parser(apachelog.formats['extended'])
67
68 For notes regarding performance while reading lines from a file
69 in Python, see <http://effbot.org/zone/readline-performance.htm>.
70 Further performance boost can be gained by using psyco
71 <http://psyco.sourceforge.net/>
72
73 On my system, using a loop like;
74
75     for line in open('access.log'):
76         p.parse(line)
77
78 ...was able to parse ~60,000 lines / second. Adding psyco to the mix,
79 up that to ~75,000 lines / second.
80
81 The parse_date function is intended as a fast way to convert a log
82 date into something useful, without incurring a significant date
83 parsing overhead - good enough for basic stuff but will be a problem
84 if you need to deal with log from multiple servers in different
85 timezones.
86 """
87
88 __version__ = "1.1"
89 __license__ = """Released under the same terms as Perl.
90 See: http://dev.perl.org/licenses/
91 """
92 __author__ = "Harry Fuecks <hfuecks@gmail.com>"
93 __contributors__ = [
94     "Peter Hickman <peterhi@ntlworld.com>",
95     "Loic Dachary <loic@dachary.org>"
96     ]
97
98 import re
99
100 class ApacheLogParserError(Exception):
101     pass
102
103 class AttrDict(dict):
104     """
105     Allows dicts to be accessed via dot notation as well as subscripts
106     Makes using the friendly names nicer
107     """
108     def __getattr__(self, name):
109         return self[name]
110
111 class parser:
112     format_to_name = {
113         # Explanatory comments copied from
114         # http://httpd.apache.org/docs/2.2/mod/mod_log_config.html
115         # Remote IP-address
116         '%a':'remote_ip',
117         # Local IP-address
118         '%A':'local_ip',
119         # Size of response in bytes, excluding HTTP headers.
120         '%B':'response_bytes',
121         # Size of response in bytes, excluding HTTP headers. In CLF
122         # format, i.e. a "-" rather than a 0 when no bytes are sent.
123         '%b':'response_bytes_clf',
124         # The contents of cookie Foobar in the request sent to the server.
125         # Only version 0 cookies are fully supported.
126         #'%{Foobar}C':'TODO',
127         # The time taken to serve the request, in microseconds.
128         '%D':'response_time_us',
129         # The contents of the environment variable FOOBAR
130         #'%{FOOBAR}e':'TODO',
131         # Filename
132         '%f':'filename',
133         # Remote host
134         '%h':'remote_host',
135         # The request protocol
136         '%H':'request_protocol',
137         # The contents of Foobar: header line(s) in the request sent to
138         # the server. Changes made by other modules (e.g. mod_headers)
139         # affect this.
140         #'%{Foobar}i':'TODO',
141         # Number of keepalive requests handled on this connection.
142         # Interesting if KeepAlive is being used, so that, for example,
143         # a "1" means the first keepalive request after the initial one,
144         # "2" the second, etc...; otherwise this is always 0 (indicating
145         # the initial request). Available in versions 2.2.11 and later.
146         '%k':'keepalive_num',
147         # Remote logname (from identd, if supplied). This will return a
148         # dash unless mod_ident is present and IdentityCheck is set On.
149         '%l':'remote_logname',
150         # The request method
151         '%m':'request_method',
152         # The contents of note Foobar from another module.
153         #'%{Foobar}n':'TODO',
154         # The contents of Foobar: header line(s) in the reply.
155         #'%{Foobar}o':'TODO',
156         # The canonical port of the server serving the request
157         '%p':'server_port',
158         # The canonical port of the server serving the request or the
159         # server's actual port or the client's actual port. Valid
160         # formats are canonical, local, or remote.
161         #'%{format}p':"TODO",
162         # The process ID of the child that serviced the request.
163         '%P':'process_id',
164         # The process ID or thread id of the child that serviced the
165         # request. Valid formats are pid, tid, and hextid. hextid requires
166         # APR 1.2.0 or higher.
167         #'%{format}P':'TODO',
168         # The query string (prepended with a ? if a query string exists,
169         # otherwise an empty string)
170         '%q':'query_string',
171         # First line of request
172         # e.g., what you'd see in the logs as 'GET / HTTP/1.1'
173         '%r':'first_line',
174         # The handler generating the response (if any).
175         '%R':'response_handler',
176         # Status. For requests that got internally redirected, this is
177         # the status of the *original* request --- %>s for the last.
178         '%s':'status',
179         '%>s':'last_status',
180         # Time the request was received (standard english format)
181         '%t':'time',
182         # The time, in the form given by format, which should be in
183         # strftime(3) format. (potentially localized)
184         #'%{format}t':'TODO',
185         # The time taken to serve the request, in seconds.
186         '%T':'response_time_sec',
187         # Remote user (from auth; may be bogus if return status (%s) is 401)
188         '%u':'remote_user',
189         # The URL path requested, not including any query string.
190         '%U':'url_path',
191         # The canonical ServerName of the server serving the request.
192         '%v':'canonical_server_name',
193         # The server name according to the UseCanonicalName setting.
194         '%V':'server_name_config', #TODO: Needs better name
195         # Connection status when response is completed:
196         # X = connection aborted before the response completed.
197         # + = connection may be kept alive after the response is sent.
198         # - = connection will be closed after the response is sent.
199         '%X':'completed_connection_status',
200         # Bytes received, including request and headers, cannot be zero.
201         # You need to enable mod_logio to use this.
202         '%I':'bytes_received',
203         # Bytes sent, including headers, cannot be zero. You need to
204         # enable mod_logio to use this
205         '%O':'bytes_sent',
206     }
207
208     def __init__(self, format, use_friendly_names=False):
209         """
210         Takes the log format from an Apache configuration file.
211
212         Best just copy and paste directly from the .conf file
213         and pass using a Python raw string e.g.
214
215         format = r'%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"'
216         p = apachelog.parser(format)
217         """
218         self._names = []
219         self._regex = None
220         self._pattern = ''
221         self._use_friendly_names = use_friendly_names
222         self._parse_format(format)
223
224     def _parse_format(self, format):
225         """
226         Converts the input format to a regular
227         expression, as well as extracting fields
228
229         Raises an exception if it couldn't compile
230         the generated regex.
231         """
232         format = format.strip()
233         format = re.sub('[ \t]+',' ',format)
234
235         subpatterns = []
236
237         findquotes = re.compile(r'^\\"')
238         findreferreragent = re.compile('Referer|User-Agent', re.I)
239         findpercent = re.compile('^%.*t$')
240         lstripquotes = re.compile(r'^\\"')
241         rstripquotes = re.compile(r'\\"$')
242         self._names = []
243
244         for element in format.split(' '):
245
246             hasquotes = 0
247             if findquotes.search(element): hasquotes = 1
248
249             if hasquotes:
250                 element = lstripquotes.sub('', element)
251                 element = rstripquotes.sub('', element)
252
253             if self._use_friendly_names:
254                 self._names.append(self.alias(element))
255             else:
256                 self._names.append(element)
257
258             subpattern = '(\S*)'
259
260             if hasquotes:
261                 if element == '%r' or findreferreragent.search(element):
262                     subpattern = r'\"([^"\\]*(?:\\.[^"\\]*)*)\"'
263                 else:
264                     subpattern = r'\"([^\"]*)\"'
265
266             elif findpercent.search(element):
267                 subpattern = r'(\[[^\]]+\])'
268
269             elif element == '%U':
270                 subpattern = '(.+?)'
271
272             subpatterns.append(subpattern)
273
274         self._pattern = '^' + ' '.join(subpatterns) + '$'
275         try:
276             self._regex = re.compile(self._pattern)
277         except Exception, e:
278             raise ApacheLogParserError(e)
279
280     def parse(self, line):
281         """
282         Parses a single line from the log file and returns
283         a dictionary of it's contents.
284
285         Raises and exception if it couldn't parse the line
286         """
287         line = line.strip()
288         match = self._regex.match(line)
289
290         if match:
291             data = AttrDict()
292             for k, v in zip(self._names, match.groups()):
293                 data[k] = v
294             return data
295
296         raise ApacheLogParserError("Unable to parse: %s with the %s regular expression" % ( line, self._pattern ) )
297
298     def alias(self, name):
299         """
300         Override / replace this method if you want to map format
301         field names to something else. This method is called
302         when the parser is constructed, not when actually parsing
303         a log file
304
305         Takes and returns a string fieldname
306         """
307         try:
308             return self.format_to_name[name]
309         except KeyError:
310             return name
311
312     def pattern(self):
313         """
314         Returns the compound regular expression the parser extracted
315         from the input format (a string)
316         """
317         return self._pattern
318
319     def names(self):
320         """
321         Returns the field names the parser extracted from the
322         input format (a list)
323         """
324         return self._names
325
326 months = {
327     'Jan':'01',
328     'Feb':'02',
329     'Mar':'03',
330     'Apr':'04',
331     'May':'05',
332     'Jun':'06',
333     'Jul':'07',
334     'Aug':'08',
335     'Sep':'09',
336     'Oct':'10',
337     'Nov':'11',
338     'Dec':'12'
339     }
340
341 def parse_date(date):
342     """
343     Takes a date in the format: [05/Dec/2006:10:51:44 +0000]
344     (including square brackets) and returns a two element
345     tuple containing first a timestamp of the form
346     YYYYMMDDHH24IISS e.g. 20061205105144 and second the
347     timezone offset as is e.g.;
348
349     parse_date('[05/Dec/2006:10:51:44 +0000]')
350     >> ('20061205105144', '+0000')
351
352     It does not attempt to adjust the timestamp according
353     to the timezone - this is your problem.
354     """
355     date = date[1:-1]
356     elems = [
357         date[7:11],
358         months[date[3:6]],
359         date[0:2],
360         date[12:14],
361         date[15:17],
362         date[18:20],
363         ]
364     return (''.join(elems),date[21:])
365
366
367 """
368 Frequenty used log formats stored here
369 """
370 formats = {
371     # Common Log Format (CLF)
372     'common':r'%h %l %u %t \"%r\" %>s %b',
373
374     # Common Log Format with Virtual Host
375     'vhcommon':r'%v %h %l %u %t \"%r\" %>s %b',
376
377     # NCSA extended/combined log format
378     'extended':r'%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"',
379     }
380
381 if __name__ == '__main__':
382     import unittest
383
384     class TestApacheLogParser(unittest.TestCase):
385
386         def setUp(self):
387             self.format = r'%h %l %u %t \"%r\" %>s '\
388                           r'%b \"%{Referer}i\" \"%{User-Agent}i\"'
389             self.fields = '%h %l %u %t %r %>s %b %{Referer}i '\
390                           '%{User-Agent}i'.split(' ')
391             self.pattern = '^(\\S*) (\\S*) (\\S*) (\\[[^\\]]+\\]) '\
392                            '\\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\" '\
393                            '(\\S*) (\\S*) \\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\" '\
394                            '\\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\"$'
395             self.line1  = r'212.74.15.68 - - [23/Jan/2004:11:36:20 +0000] '\
396                           r'"GET /images/previous.png HTTP/1.1" 200 2607 '\
397                           r'"http://peterhi.dyndns.org/bandwidth/index.html" '\
398                           r'"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) '\
399                           r'Gecko/20021202"'
400             self.line2  = r'212.74.15.68 - - [23/Jan/2004:11:36:20 +0000] '\
401                           r'"GET /images/previous.png=\" HTTP/1.1" 200 2607 '\
402                           r'"http://peterhi.dyndns.org/bandwidth/index.html" '\
403                           r'"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) '\
404                           r'Gecko/20021202"'
405             self.line3  = r'4.224.234.46 - - [20/Jul/2004:13:18:55 -0700] '\
406                           r'"GET /core/listing/pl_boat_detail.jsp?&units=Feet&checked'\
407                           r'_boats=1176818&slim=broker&&hosturl=giffordmarine&&ywo='\
408                           r'giffordmarine& HTTP/1.1" 200 2888 "http://search.yahoo.com/'\
409                           r'bin/search?p=\"grady%20white%20306%20bimini\"" '\
410                           r'"\"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; '\
411                           r'YPC 3.0.3; yplus 4.0.00d)\""'
412 #                          r'"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; '\
413 #                          r'YPC 3.0.3; yplus 4.0.00d)"'
414             self.p = parser(self.format)
415
416         def testpattern(self):
417             self.assertEqual(self.pattern, self.p.pattern())
418
419         def testnames(self):
420             self.assertEqual(self.fields, self.p.names())
421
422         def testline1(self):
423             data = self.p.parse(self.line1)
424             self.assertEqual(data['%h'], '212.74.15.68', msg = 'Line 1 %h')
425             self.assertEqual(data['%l'], '-', msg = 'Line 1 %l')
426             self.assertEqual(data['%u'], '-', msg = 'Line 1 %u')
427             self.assertEqual(data['%t'], '[23/Jan/2004:11:36:20 +0000]', msg = 'Line 1 %t')
428             self.assertEqual(
429                 data['%r'],
430                 'GET /images/previous.png HTTP/1.1',
431                 msg = 'Line 1 %r'
432                 )
433             self.assertEqual(data['%>s'], '200', msg = 'Line 1 %>s')
434             self.assertEqual(data['%b'], '2607', msg = 'Line 1 %b')
435             self.assertEqual(
436                 data['%{Referer}i'],
437                 'http://peterhi.dyndns.org/bandwidth/index.html',
438                 msg = 'Line 1 %{Referer}i'
439                 )
440             self.assertEqual(
441                 data['%{User-Agent}i'],
442                 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202',
443                 msg = 'Line 1 %{User-Agent}i'
444                 )
445
446
447         def testline2(self):
448             data = self.p.parse(self.line2)
449             self.assertEqual(data['%h'], '212.74.15.68', msg = 'Line 2 %h')
450             self.assertEqual(data['%l'], '-', msg = 'Line 2 %l')
451             self.assertEqual(data['%u'], '-', msg = 'Line 2 %u')
452             self.assertEqual(
453                 data['%t'],
454                 '[23/Jan/2004:11:36:20 +0000]',
455                 msg = 'Line 2 %t'
456                 )
457             self.assertEqual(
458                 data['%r'],
459                 r'GET /images/previous.png=\" HTTP/1.1',
460                 msg = 'Line 2 %r'
461                 )
462             self.assertEqual(data['%>s'], '200', msg = 'Line 2 %>s')
463             self.assertEqual(data['%b'], '2607', msg = 'Line 2 %b')
464             self.assertEqual(
465                 data['%{Referer}i'],
466                 'http://peterhi.dyndns.org/bandwidth/index.html',
467                 msg = 'Line 2 %{Referer}i'
468                 )
469             self.assertEqual(
470                 data['%{User-Agent}i'],
471                 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202',
472                 msg = 'Line 2 %{User-Agent}i'
473                 )
474
475         def testline3(self):
476             data = self.p.parse(self.line3)
477             self.assertEqual(data['%h'], '4.224.234.46', msg = 'Line 3 %h')
478             self.assertEqual(data['%l'], '-', msg = 'Line 3 %l')
479             self.assertEqual(data['%u'], '-', msg = 'Line 3 %u')
480             self.assertEqual(
481                 data['%t'],
482                 '[20/Jul/2004:13:18:55 -0700]',
483                 msg = 'Line 3 %t'
484                 )
485             self.assertEqual(
486                 data['%r'],
487                 r'GET /core/listing/pl_boat_detail.jsp?&units=Feet&checked_boats='\
488                 r'1176818&slim=broker&&hosturl=giffordmarine&&ywo=giffordmarine& '\
489                 r'HTTP/1.1',
490                 msg = 'Line 3 %r'
491                 )
492             self.assertEqual(data['%>s'], '200', msg = 'Line 3 %>s')
493             self.assertEqual(data['%b'], '2888', msg = 'Line 3 %b')
494             self.assertEqual(
495                 data['%{Referer}i'],
496                 r'http://search.yahoo.com/bin/search?p=\"grady%20white%20306'\
497                 r'%20bimini\"',
498                 msg = 'Line 3 %{Referer}i'
499                 )
500             self.assertEqual(
501                 data['%{User-Agent}i'],
502                 '\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YPC 3.0.3; '\
503                 'yplus 4.0.00d)\\"',
504 #                'Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YPC 3.0.3; '\
505 #                'yplus 4.0.00d)',
506                 msg = 'Line 3 %{User-Agent}i'
507                 )
508
509
510         def testjunkline(self):
511             self.assertRaises(ApacheLogParserError,self.p.parse,'foobar')
512
513         def testhasquotesaltn(self):
514             p = parser(r'%a \"%b\" %c')
515             line = r'foo "xyz" bar'
516             data = p.parse(line)
517             self.assertEqual(data['%a'],'foo', '%a')
518             self.assertEqual(data['%b'],'xyz', '%c')
519             self.assertEqual(data['%c'],'bar', '%c')
520
521         def testparsedate(self):
522             date = '[05/Dec/2006:10:51:44 +0000]'
523             self.assertEqual(('20061205105144','+0000'),parse_date(date))
524
525     class TestApacheLogParserFriendlyNames(unittest.TestCase):
526
527         def setUp(self):
528             self.format = r'%h %l %u %t \"%r\" %>s '\
529                           r'%b \"%{Referer}i\" \"%{User-Agent}i\"'
530             self.fields = ('remote_host remote_logname remote_user time '
531                            'first_line last_status response_bytes_clf '
532                            '%{Referer}i %{User-Agent}i').split(' ')
533             self.pattern = '^(\\S*) (\\S*) (\\S*) (\\[[^\\]]+\\]) '\
534                            '\\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\" '\
535                            '(\\S*) (\\S*) \\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\" '\
536                            '\\\"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)\\\"$'
537             self.line1  = r'212.74.15.68 - - [23/Jan/2004:11:36:20 +0000] '\
538                           r'"GET /images/previous.png HTTP/1.1" 200 2607 '\
539                           r'"http://peterhi.dyndns.org/bandwidth/index.html" '\
540                           r'"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) '\
541                           r'Gecko/20021202"'
542             self.line2  = r'212.74.15.68 - - [23/Jan/2004:11:36:20 +0000] '\
543                           r'"GET /images/previous.png=\" HTTP/1.1" 200 2607 '\
544                           r'"http://peterhi.dyndns.org/bandwidth/index.html" '\
545                           r'"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) '\
546                           r'Gecko/20021202"'
547             self.line3  = r'4.224.234.46 - - [20/Jul/2004:13:18:55 -0700] '\
548                           r'"GET /core/listing/pl_boat_detail.jsp?&units=Feet&checked'\
549                           r'_boats=1176818&slim=broker&&hosturl=giffordmarine&&ywo='\
550                           r'giffordmarine& HTTP/1.1" 200 2888 "http://search.yahoo.com/'\
551                           r'bin/search?p=\"grady%20white%20306%20bimini\"" '\
552                           r'"\"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; '\
553                           r'YPC 3.0.3; yplus 4.0.00d)\""'
554 #                          r'"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; '\
555 #                          r'YPC 3.0.3; yplus 4.0.00d)"'
556             self.p = parser(self.format, True)
557
558         def testpattern(self):
559             self.assertEqual(self.pattern, self.p.pattern())
560
561         def testnames(self):
562             self.assertEqual(self.fields, self.p.names())
563
564         def testline1(self):
565             data = self.p.parse(self.line1)
566             self.assertEqual(data.remote_host, '212.74.15.68', msg = 'Line 1 remote_host')
567             self.assertEqual(data.remote_logname, '-', msg = 'Line 1 remote_logname')
568             self.assertEqual(data.remote_user, '-', msg = 'Line 1 remote_user')
569             self.assertEqual(data.time, '[23/Jan/2004:11:36:20 +0000]', msg = 'Line 1 time')
570             self.assertEqual(
571                 data.first_line,
572                 'GET /images/previous.png HTTP/1.1',
573                 msg = 'Line 1 first_line'
574                 )
575             self.assertEqual(data.last_status, '200', msg = 'Line 1 last_status')
576             self.assertEqual(data.response_bytes_clf, '2607', msg = 'Line 1 response_bytes_clf')
577             self.assertEqual(
578                 data['%{Referer}i'],
579                 'http://peterhi.dyndns.org/bandwidth/index.html',
580                 msg = 'Line 1 %{Referer}i'
581                 )
582             self.assertEqual(
583                 data['%{User-Agent}i'],
584                 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202',
585                 msg = 'Line 1 %{User-Agent}i'
586                 )
587
588
589         def testline2(self):
590             data = self.p.parse(self.line2)
591             self.assertEqual(data.remote_host, '212.74.15.68', msg = 'Line 2 remote_host')
592             self.assertEqual(data.remote_logname, '-', msg = 'Line 2 remote_logname')
593             self.assertEqual(data.remote_user, '-', msg = 'Line 2 remote_user')
594             self.assertEqual(
595                 data.time,
596                 '[23/Jan/2004:11:36:20 +0000]',
597                 msg = 'Line 2 time'
598                 )
599             self.assertEqual(
600                 data.first_line,
601                 r'GET /images/previous.png=\" HTTP/1.1',
602                 msg = 'Line 2 first_line'
603                 )
604             self.assertEqual(data.last_status, '200', msg = 'Line 2 last_status')
605             self.assertEqual(data.response_bytes_clf, '2607', msg = 'Line 2 response_bytes_clf')
606             self.assertEqual(
607                 data['%{Referer}i'],
608                 'http://peterhi.dyndns.org/bandwidth/index.html',
609                 msg = 'Line 2 %{Referer}i'
610                 )
611             self.assertEqual(
612                 data['%{User-Agent}i'],
613                 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2) Gecko/20021202',
614                 msg = 'Line 2 %{User-Agent}i'
615                 )
616
617         def testline3(self):
618             data = self.p.parse(self.line3)
619             self.assertEqual(data.remote_host, '4.224.234.46', msg = 'Line 3 remote_host')
620             self.assertEqual(data.remote_logname, '-', msg = 'Line 3 remote_logname')
621             self.assertEqual(data.remote_user, '-', msg = 'Line 3 remote_user')
622             self.assertEqual(
623                 data.time,
624                 '[20/Jul/2004:13:18:55 -0700]',
625                 msg = 'Line 3 time'
626                 )
627             self.assertEqual(
628                 data.first_line,
629                 r'GET /core/listing/pl_boat_detail.jsp?&units=Feet&checked_boats='\
630                 r'1176818&slim=broker&&hosturl=giffordmarine&&ywo=giffordmarine& '\
631                 r'HTTP/1.1',
632                 msg = 'Line 3 first_line'
633                 )
634             self.assertEqual(data.last_status, '200', msg = 'Line 3 last_status')
635             self.assertEqual(data.response_bytes_clf, '2888', msg = 'Line 3 response_bytes_clf')
636             self.assertEqual(
637                 data['%{Referer}i'],
638                 r'http://search.yahoo.com/bin/search?p=\"grady%20white%20306'\
639                 r'%20bimini\"',
640                 msg = 'Line 3 %{Referer}i'
641                 )
642             self.assertEqual(
643                 data['%{User-Agent}i'],
644                 '\\"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YPC 3.0.3; '\
645                 'yplus 4.0.00d)\\"',
646 #                'Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YPC 3.0.3; '\
647 #                'yplus 4.0.00d)',
648                 msg = 'Line 3 %{User-Agent}i'
649                 )
650
651
652         def testjunkline(self):
653             self.assertRaises(ApacheLogParserError,self.p.parse,'foobar')
654
655         def testhasquotesaltn(self):
656             p = parser(r'%a \"%b\" %c')
657             line = r'foo "xyz" bar'
658             data = p.parse(line)
659             self.assertEqual(data['%a'],'foo', '%a')
660             self.assertEqual(data['%b'],'xyz', '%c')
661             self.assertEqual(data['%c'],'bar', '%c')
662
663         def testparsedate(self):
664             date = '[05/Dec/2006:10:51:44 +0000]'
665             self.assertEqual(('20061205105144','+0000'),parse_date(date))
666
667
668     unittest.main()