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

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

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. [转]allocWithZone 和 单例模式

    一.问题起源 一切起源于Apple官方文档里面关于单例(Singleton)的示范代码:Creating a Singleton Instance. 主要的争议集中在下面这一段: ? 1 2 3 4 ...

  2. springmvc 返回xml

    需求: 1.springmvc返回xml: 技术及环境: Spring 4.3.1.RELEASE JDK 1.8 IDEA 15.0.6 Maven 3 实现: spirngxml的配置主要如下: ...

  3. pnd_start_2

    试过才知道一点都不简单,虽然表现出的逻辑是错的,但是至少运行上是正确的.

  4. Http,Https(SSL)的Url绝对路径,相对路径解决方案Security Switch 4.2的配置和使用 分类: ASP.NET 2014-11-05 12:51 97人阅读 评论(0) 收藏

    下载地址1:https://securityswitch.googlecode.com/files/SecuritySwitch%20v4.2.0.0%20-%20Binary.zip 下载地址2:h ...

  5. Android客户端中Bitmap的下载过程和缓存机制

    加载流程: if(内存命中){      从内存中读取 }else{      create AsyncTasks,task中的多个Runnable是通过堆栈先进后出的方式来调度,而非队列式的先进先出 ...

  6. Java设计模式--单列设计模式

    设计模式:解决某一类问题行知最有效的方法.java有23种设计模式 单列设计模式: 解决一个类在内存中只存在一个对象 思路:(要保证对象的唯一性) 1.为了避免其它程序建立该对象,先禁止替他类创建改对 ...

  7. jsp - 引用 jar包.

    在jsp中使用不同的方式引用jar,准备的工作也不同.我接触过的有两种:1)直接在jsp页面中引用;2)在src下的java类中引用,然后在jsp中调用java类. 1)直接引用:可以将jar包丢到W ...

  8. Lucene索引的初步创建

    从百度上知道的,Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的 ...

  9. jquery文本折叠

    /** * Created by dongdong on 2015/4/28. */(function($){ var defaults = { height:40, //文本收起后的高度 speed ...

  10. QTableView使用自定义委托(QItemDelegate)

    需要在表格中绘制流程图,主要有箭头,方向,颜色,字符串,由于QTableView没有可用的绘制函数,所以需要自己去定义. 委托(delegate)继承QItemDelegate,模型(model)继承 ...