Parse nginx log files using Python

Source: Internet
Author: User
Various system management tasks of the Web server include the statistics of multiple NginxApache logs. python makes this task extremely simple. next we will explain in detail the specific practices, if you have any need, refer. One requirement of the project is to parse nginx log files.
A simple arrangement is as follows:

Log rule description

First, you must specify your Nginx log format. the default Nginx log format is used here:

 log_format main '$remote_addr - $remote_user [$time_local] "$request" '          '$status $body_bytes_sent "$http_referer" '          '"$http_user_agent" "$http_x_forwarded_for"';

A real record example is as follows:

The code is as follows:


172.22.8.207--[16/Dec/2014: 17: 57: 35 + 0800] "GET/report? DOmjjuS6keWJp + WculSQAgdUkAIPODExMzAwMDJDN0FC HTTP/1.1 "200 0"-"" XXXXXXX/1.0.16; iPhone/iOS 8.1.2; 8DA77E2F91D0"

The client model information is replaced by XXXXXXX.

The project has processed Nginx log files according to the business rules. The naming rules are as follows:

ID-YYMMDD-hhmmss
All log files are stored in the same path.

Solution

Retrieve all log files path

The glob module of Python is used to obtain the path of the log file.

import globdef readfile(path):  return glob.glob(path + '*-*-*-*')

Obtain the content of each row in the log file.

Use the linecache module of Python to obtain the content of the file line.

import linecachedef readline(path):  return linecache.getlines(path)

Note: The linecache module uses cache, so the following problems exist:

After the linecache module is used to read the file content, if the file changes, you need to use linecache. updatecache (filename) to update the cache for the latest changes.

The linecache module uses cache, which consumes memory and is related to the file to be parsed. Run linecache. sort ache () to clear the cache.

Of course, as an optimization, the generator can be used for optimization. Temporarily press the table.

Process log entries

A log is a string in a specific format, so regular expressions are used for parsing. here we use the Python re module.
Next, create a rule one by one:

Rules

  ip = r"?P
 
  [\d.]*"  date = r"?P
  
   \d+"  month = r"?P
   
    \w+"  year = r"?P
    
     \d+"  log_time = r"?P
     \S+"  method = r"?P
      
       \S+" request = r"?P
       
        \S+" status = r"?P
        
         \d+" bodyBytesSent = r"?P
         
          \d+" refer = r"""?P
          
            [^\"]* """ userAgent=r"""?P
           
             .* """
           
          
         
        
       
      
    
   
  
 

Analysis

The code is as follows:


P = re. compile (r "(% s) \-\ [(% s)/(% s) \ :( % s) \ [\ S] + \] \ "(% s )? [\ S]? (% S )?. *? \ "\ (% S) \" (% s) \ "\" (% s ).*? \ "" % (Ip, date, month, year, log_time, method, request, status, bodyBytesSent, refer, userAgent), re. VERBOSE)
M = re. findall (p, logline)

In this way, you can obtain the raw data of each element in the log entry.

Format and Content conversion

After obtaining the original log data, convert the format and content of the original data according to business requirements.
The content to be processed here includes: time, request, and userAgent.

Time format conversion

The raw log information contains such information as Dec, which can be easily parsed using the time module of Python.

import timedef parsetime(date, month, year, log_time):  time_str = '%s%s%s %s' %(year, month, date, log_time)  return time.strptime(time_str, '%Y%b%d %H:%M:%S')

Parse request

The format of the request obtained from the raw log information is as follows:

/Report? XXXXXX
Here, you only need to retrieve XXXXXX according to the protocol.
The re module of Python is still used here

import redef parserequest(rqst):  param = r"?P.*"  p = re.compile(r"/report\?(%s)" %param, re.VERBOSE)  return re.findall(p, rqst)

Next, you need to parse the parameter content based on the business protocol. Here we need to decode using base64 and then use struct to deconstruct the content:

import structimport base64def parseparam(param):  decodeinfo = base64.b64decode(param)  s = struct.Struct('!x' + bytes(len(decodeinfo) - (1 + 4 + 4 + 12)) + 'xii12x')  return s.unpack(decodeinfo)

Parsing userAgent

In the raw log information, the format of userAgent data is as follows:

XXX; XXX
According to business requirements, you only need to retrieve the last item.
The re module is used for parsing.

import redef parseuseragent(useragent):  agent = r"?P.*"  p = re.compile(r".*;.*;.*;(%s)" %agent, re.VERBOSE)  return re.findall(p, useragent)

So far, nginx log file parsing is basically complete.
The rest of the work is to process the basic information obtained based on business needs.

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.