Package: task4
Parsing log with Regex in Python.Module 2: Python. Task 4.PrefaceThis project contains a solution to one of the tasks of the EPAM DevOps Initial Internal Training Course #7 in 2023.
Detailed information about the course, as well as reports on each of the completed tasks (including this one) can be foundhere.As mentioned above, the project contains a solution to task #4 as part of module #2 of learning the Python programming language.
Below you will find a detailed description of the task, as well as a brief description of the implementation.Table of ContentsConditionsImplementationStructureInstallationUsageLibraryCLIPipes and filesShowcaseGeneral ProvisionsConditionsCreate a log parser based on Regex. For test reasons utilize the access.log file.
The format of the access.log file is as follows:
LogFormat "%h (%{X-Forwarded-For}i) %l %u %t "%r" %>s %b %T %D "%{Referer}i" "%{UserAgent}i" "%{BALANCER_WORKER_NAME}e""
Parse the Apache Tomcat access.log file and display the necessary records:#Task1Collect statistics on IP addresses of the browser, as a result, specify the N most frequent ones.2Find the frequency of requests in the time interval dT (minutes).3Find the N most frequent User-Agent.4Statistics status code S (50x errors) in the time interval dT (minutes).5Find N longest queries or shortest queries.6N most frequent requests to the K slash. For instance, to the 2nd slash, if the request is "GET /merlin-servicesearch/rest/vehiclefamilyvalueslookup/117341 HTTP/1.1", then the statistics are collected for /merlin-servicesearch.7Number of requests regarding upstream (workers).8For the url link find conversion statistics. Display statistics for specific domain total request count.9Number of outgoing requests (workers) in dT (30 sec, 1 minute, 5 min).10Find the N time periods dT (1 min, 2 min, 3 min, etc.) for which the largest number of requests are executed.ImplementationLog_Parseris a Python package that could be added to your global or virtual environment by preferable package manager pip, pipenv, poetry, etc.
The project itself was managed and built using thePoetry library,
so if you intend to clone this repo and make some changes for your own purposes, please installPoetryor migrate to your preferred package management library.Based on the need to build and the possibility of using both the library and the CLI, the code was split into a library for importing and a script for execution
via the command line. Additionally, the package contains a showcase that demonstrates all use cases when run through the command line.To enhance the command line's functionality and expand showcase capabilities, theQuestionarylibrary is used and will be installed through a dependency link upon package installation.Structuretask4/
├── README.md (You are here now)
├── pyproject.toml # Poetry package management file
└── log_parser/ 
    ├──__init__.py # library entry point
    ├──__main__.py # CLI entry point
    ├──__version__.py 
    ├── log_parser.py # library implementation
    ├── cli/
    │   ├──__init__.py
    │   ├──__main__.py
    │   └── cli.py # CLI code implementation
    └── showcase/
            ├──__init__.py 
            ├──__main__.py # showcase entry point when using python -m log_parser.showcase
            ├── access.log # a sample CSV file
            └── showcase.py # showcase implementationInstallationUse your preferred installation method via different package installation managers to install Log_Parser.PipTo install Log_Parser packet to your environment using pip manager invokepip install task4.$pipinstalltask4
Collectingtask4Usingcachedtask4-1.0.N-py3-none-any.whl(62kB)Collectingquestionary<2.0.0,>=1.10.0(fromtask3)Downloadingquestionary-1.10.0-py3-none-any.whl(31kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━31.1/31.1kBN.NMB/seta0:00:00
Collectingprompt_toolkit<4.0,>=2.0(fromquestionary<2.0.0,>=1.10.0->task3)Downloadingprompt_toolkit-3.0.39-py3-none-any.whl(385kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━385.2/385.2kBN.NMB/seta0:00:00
Collectingwcwidth(fromprompt_toolkit<4.0,>=2.0->questionary<2.0.0,>=1.10.0->task3)Downloadingwcwidth-0.2.6-py2.py3-none-any.whl(29kB)━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━29.2/29.2kBN.NMB/seta0:00:00
Installingcollectedpackages:wcwidth,prompt_toolkit,questionary,task3
Successfullyinstalledprompt_toolkit-3.0.39questionary-1.10.0task4-1.0.Nwcwidth-0.2.6To uninstall Log Parser from your environment invokepip uninstall task4.
It's important to note that the pip manager does not uninstall dependent packages. Therefore, if you wish to remove them, you'll need to take
the initiative and perform the task yourself. You can do this by using the commandspip uninstall questionary prompt-toolkit wcwidth.PoetryTo install Log Parser packet to your environment using poetry manager invokepoetry add task4.$poetryaddtask4
Usingversion^1.0.Nfortask4

Updatingdependencies
Resolvingdependencies...

Packageoperations:6installs,0updates,0removals•Installingwcwidth(0.2.6)•Installingprompt-toolkit(3.0.39)•Installingquestionary(1.10.0)WritinglockfileBy taking this action, a new dependency line will be added to your pyproject.toml file.[tool.poetry.dependencies]task4="^1.0.N"To uninstall Log Parser from your environment invokepoetry remove task4.
One of the benefits of utilizing Poetry is that it allows for the removal of all dependent packages with a single command.UsageThere are various ways to use this library, as mentioned earlier.Utilize it like a library you can just import it into your .py file and use LogHelper class within your code.Utilize CLI via the command shell, either as a Python module or as a standalone command.Utilize CLI command in a pipe by passing stdout of other commands to the stdin of the log_parser command, writing stdout and stderr to files, or passing them to following commands.The library also contains rich showcase command that allows you to test all the use cases and even perform them in batches.LibraryBelow is a code snippet that demonstrates how to be able to use the log_parser library in your code.fromlog_parser.log_parserimportlogger,LogHandlerimportrewithopen('access.log','r')asf:handler=LogHandler(log=f,extractor=re.compile(extractor,flags=re.I|re.X),selection=selection,aggregation=aggregation,filter_str=filter_str,rows=rows)print(handler.output)CLIThe CLI interface has a single command called "log_parser". It can be invoked using two methods:python3 -m log_parseror simplylog_parser.
Log_parser accepts various arguments, which are described below.log_parser [-h] [--version] -e  [-s] [-a] [-f] [-r [INDEXES ...]] [-v] [file_name]

positional arguments:
  file_name             An input filename

options:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -e , --extractor      Specify a regular expression for extracting certain data from each log line. 
                        The following expression patterns can be used to make      
                        writing an expression easier and reduce its size. 
                        For instance, "IP4\ \((?P<IP4_LIST>(?:(?:IP4|.*?),\ )*)(?:IP4|.*?)\)\ -\ -\
                        \[DATE_TIME_SEC\]\ \"(?:REQUEST|-)\"" 
                        
                        IP4_OCTET, MASK_OCTET, IP4, IP4_CIDR, MASK, IP6, IP6_CIDR, MAC_PART, MAC, VERSION, AGENT_AGENT,   
                        AGENT_OS, AGENT_DEVICE, AGENT_BROWSER, USER_AGENT, DOMAIN, EMAIL_NAME_CHARSET, EMAIL, URI, URL, 
                        REQUEST_TYPES, REQUEST, DATE_TIME_SEC, UUID
  -s , --selection      Specify a regular expression template to output selected data. To add previously extracted data
                        via regular expression groups use template group naming like \g<group_name>. 
                        It is allowed to use various transformation functions for substitution, extracting and even  
                        splitting data.
                        For instance, 
                        "TO_MIN(\g<DATE_TIME>) \g<URL>" or "SPLIT(RE('(?<=\().+?(?=\))', \g<IP4>), ',\ ')" 
                        
                        The list of possible functions: MIN, MAX, SPLIT, SUB, INTERVAL, SUM, COUNT, RE
  -a , --aggregation    The aggregate to be calculated during log parsing. It is used for sorting or summation.
                        For instance, "MAX(\g<STATUS>,5)" or ..... 
                        
                        The list of possible functions: MIN, MAX, SPLIT, SUB, INTERVAL, SUM, COUNT, RE
  -f , --filter         Specify a regular expression for filtering each line. It is supposed to used RE functions
                        and group naming like \g<group_name>. If the result of using regular expression return None
                        the line will be omitted. 
                        
                        For instance, 
                        "RE('50\d', \g<STATUS>)" or "RE((?:/+[a-z\d\-._~%&\'()*+,;=:@{\'}{\'}]+){2}, \g<REQUEST_PATH>)"
  -r [INDEXES ...], --rows [INDEXES ...]
                        The row range from the log file to be parsed. You can pass values in the following formats: particular indexes: index1 index2 ...       
                        indexN range of indexes: index1-index2 from the beginning up to index: -index from index to the end: index-
  -v                    Increase verbosity level (add more v)To handle the arguments, theargparsemodule is used. If you are already acquainted with it, you will have no difficulty in passing the arguments along with their values and comprehending their behavior.The examples in a more convenient form you could find in theshowcase.Pipes and filesThe log_parser command could be used inside the pipe of the BASH commands. It can be used in various ways within a pipeline:receiving inputdirect output to a filedirect logging also to a fileThis command isn't intended for use in pipe sequence due to the table output format but is allowed.ShowcaseTo showcase the behavior of the log_parser library, an interactive command called "log_parser_showcase" has been created.
This command utilizes both the log_parser CLI and the log_parser library. It's an interactive command you can invoke vialog_parser_showcaseorpython3 -m log_parser.showcase.
It has an optional flag that allows you to view all use cases at once without any interaction.
You can use the commandlog_parser_showcase --allto activate this feature.
There are also a ready-made Apache Tomcat log file presents -access.log.
You can use the showcase to test your own regular expressions and regular expression templates.General provisionsAll materials provided and/or made available contain EPAM’s proprietary and confidential information and must not to be copied,
reproduced or disclosed to any third party or to any other person, other than those persons who have a bona fide need to review it
for the purpose of participation in the online courses being provided by EPAM.
The intellectual property rights in all materials (including any trademarks) are owned by EPAM Systems Inc or its associated companies,
and a limited license, terminable at the discretion of EPAM without notice, is hereby granted to you solely for the purpose of participating
in the online courses being provided by EPAM. Neither you nor any other party shall acquire any intellectual property rights of any kind
in such materials.