处理特定字段的内容,并指指定条件输出。

注意代码中用一个方法列表,并且将方法参数延后传递。

GOOGLE作过PYTHON代码的水平,就是不一样呀。

希望能学到这种通用的技巧。

只是,英文PDF看起来有难度,并且印刷代码还有错误。

有识之士能出个中文版么?现在只好硬头皮看下去。

#!/usr/bin/python
import sys
from optparse import OptionParser

class LogProcessor(object):
    '''
    Process a combined log format.

    This processor handles log files in a combined format,
    objects that act on the results are passed in to
    the init method as a series of methods.
    '''
    def __init__(self, call_chain=None):
        """
        Setup parser
        Save the call chain. Each time we process a log ,
        we'll run the list of callbacks with the processed
        log results.
        """
        if call_chain is None:
            call_chain = []
        self._call_chain = call_chain
    def split(self, line):
            """
            Split a log file.
            Initially,we just want size and requested file name . so
            we'll split on spaces and pull the data out.
            """
            parts = line.split()

            return {
                'size': 0 if parts[9] == '-' else int(parts[9]),
                'file_requested': parts[6]
            }
    def parse(self, handle):
            """
            Parses the log file.
            Returns a dictionary composed of log entry values
            for easy data summation
            """
            for line in handle:
                fields = self.split(line)
                for func in self._call_chain:
                   func(fields)

class MaxSizeHandler(object):
    """
    Check a file's size.
    """
    def __init__(self, size):
        self.size = size
    def process(self, fields):
        """
        Looks at each line individually.
        Looks at each parsed log line individually and
        performs a size calculation. If it's bigger than
        our self.size, we just print a warning.
        """
        if fields['size'] > self.size:
            #print ('Warning: %s exceeds $d bytes (%s) !' % (fields['file_requested'], str(self.size), fields['size']))
            print ('Warning: {0} exceeds {1} bytes {2} !'.format (fields['file_requested'], str(self.size), fields['size']))
if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-s', '--size', dest = "size",
                      help = "Maximum File Size Allowed",
                      default = 0, type = "int")
    opts,args = parser.parse_args()
    call_chain = []

    size_check = MaxSizeHandler(opts.size)
    call_chain.append(size_check.process)
    processor = LogProcessor(call_chain)
    processor.parse(sys.stdin)

PYTHON文本处理指南之日志LOG解析的更多相关文章

  1. Python 文本解析器

    Python 文本解析器 一.课程介绍 本课程讲解一个使用 Python 来解析纯文本生成一个 HTML 页面的小程序. 二.相关技术 Python:一种面向对象.解释型计算机程序设计语言,用它可以做 ...

  2. 5. python 文本解析

    5. python 文本解析 这一章节我们简单的聊聊文本解析的两种方法: 1.分片,通过分片,记录偏移处,然后提取想要的字符串 例子: >>> line='aaa bbb ccc'  ...

  3. Python 编码风格指南

    原文:http://python.jobbole.com/84618/ 本文超出 PEP8 的范畴以涵盖我认为优秀的 Python 风格.本文虽然坚持己见,却不偏执.不仅仅涉及语法.模块布局等问题,同 ...

  4. 【转】python模块分析之logging日志(四)

    [转]python模块分析之logging日志(四) python的logging模块是用来写日志的,是python的标准模块. 系列文章 python模块分析之random(一) python模块分 ...

  5. python模块分析之logging日志(四)

    前言 python的logging模块是用来设置日志的,是python的标准模块. 系列文章 python模块分析之random(一) python模块分析之hashlib加密(二) python模块 ...

  6. Python 全栈开发九 日志模块

    日志是一种可以追踪某些软件运行时所发生事件的方法.软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情.一个事件可以用一个可包含可选变量数据的消息来描述.此外,事件也有重要性的概念 ...

  7. Python开发人员指南

    本指南是一个全面的资源贡献 给Python的 -为新的和经验丰富的贡献者.这是 保持由维护的Python同一社区.我们欢迎您对Python的贡献! 快速参考 这是设置和添加补丁所需的基本步骤.了解基础 ...

  8. .NetCore中的日志(1)日志组件解析

    .NetCore中的日志(1)日志组件解析 0x00 问题的产生 日志记录功能在开发中很常用,可以记录程序运行的细节,也可以记录用户的行为.在之前开发时我一般都是用自己写的小工具来记录日志,输出目标包 ...

  9. 如何正确使用日志Log

    title: 如何正确使用日志Log date: 2015-01-08 12:54:46 categories: [Python] tags: [Python,log] --- 文章首发地址:http ...

随机推荐

  1. 常用JDBC连接字符串

    1.MySQL Class.forName( " org.gjt.mm.mysql.Driver " ); Connection conn = DriverManager.getC ...

  2. Android开发之View重写相关API-onLayout,onMeasure,MeasureSpec

     1.onLayout android.view.ViewGroup protected void onLayout(boolean changed, int l, int t, int r, int ...

  3. div随另一个div自动增高

    <script type="text/javascript"> document.getElementById("div1").style.heig ...

  4. webapi 接口规则

    [HttpPost] [AuthorizeFilter] public HttpResponseMessage DeleteStudentInfo([FromBody] object value) { ...

  5. wps批量使标题靠文档左边

  6. SqlSugar框架T4模板的使用

    一.T4模板说明 1.T4模板是用来生成Model层实体类的 2.文件后缀为.tt 3.需要修改配置主要有:引用的SqlSugar.dll的位置.生成实体类的位置及生成实体类的命名空间 4.T4模板生 ...

  7. JS一些应用脚本

    脚本一: //重置下标(可以修改成自己所需要的脚本) function ReSetBoxOrder() { var q = 0;//下标值 var a = 0;//暂未用到 //循环当前tbody下的 ...

  8. 一个实例明白AutoResetEvent和 ManulResetEvent的用法

    先看一段代码: public class WaitHandlerExample {                 public static AutoResetEvent waitHandler;  ...

  9. cocos2d-x系列 Mac下配置cocos2d-x开发环境(android和ios)

    一.下载cocos2d-x http://cocos2d-x.org/projects/cocos2d-x/wiki/Download cocos2d-x-2.1.4.zip @ June.18, 2 ...

  10. ACM hdu 1008 Elavator

    Elevator其实是一道水题,思路也很简单,但不知道怎么也不能AC,后来看了别人的再比较自己的以后找到错误. 在判断奇偶数之后的语句时,我用了if()  else if(),这是不能AC的原因,这种 ...