能分析压缩的日志,且基于文件输入的PYTHON代码实现

简介:

确实感觉长见识了。

希望能坚持,并有多的时间用来分析这些思路和模式。

复制代码
#!/usr/bin/python
import sys
import gzip
import bz2
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 ColumnLogProcessor(LogProcessor):
    def split(self, line):
        parts = line.split()
        return {
            'size': int(parts[1]),
            'file_requested': parts[0]
        }

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']))
def get_stream(path):
    """
    Detect compression.
    If the file name ends in a compression suffix, we'll open
    using the correct algorith. If not, we just return a standard
    file object.
    """
    _open = open
    if path.endswith(',gz'):
        _open = gzip.open
    elif path.endswith('.bz2'):
        _open = bz2.open()
    return _open(path)
if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option('-s', '--size', dest = "size",
                      help = "Maximum File Size Allowed",
                      default = 0, type = "int")
    parser.add_option('-f', '--file', dest = "file",
                      help = "Path to Web Log File",default = "-")
    opts,args = parser.parse_args()
    call_chain = []

    if opts.file == '-':
        file_stream = sys.stdin
    else:
        try:
            #file_stream = open(opts.file, 'r')
            file_stream = get_stream(opts.file)
        except IOError as e:
            print (sys.stderr,str(e))
            sys.exit(-1)

    size_check = MaxSizeHandler(opts.size)
    call_chain.append(size_check.process)
    processor = LogProcessor(call_chain)
    processor.parse(file_stream)
    #processorC = ColumnLogProcessor(call_chain)
    #processorC.parse(file_stream)
复制代码

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
目录
相关文章
|
2月前
|
存储 监控 算法
防止员工泄密软件中文件访问日志管理的 Go 语言 B + 树算法
B+树凭借高效范围查询与稳定插入删除性能,为防止员工泄密软件提供高响应、可追溯的日志管理方案,显著提升海量文件操作日志的存储与检索效率。
122 2
|
2月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
290 0
|
7月前
|
SQL 安全 算法
解读 Python 3.14:模板字符串、惰性类型、Zstd压缩等7大核心功能升级
Python 3.14 引入了七大核心技术特性,大幅提升开发效率与应用安全性。其中包括:t-strings(PEP 750)提供更安全灵活的字符串处理;类型注解惰性求值(PEP 649)优化启动性能;外部调试器API标准化(PEP 768)增强调试体验;原生支持Zstandard压缩算法(PEP 784)提高效率;REPL交互环境升级更友好;UUID模块扩展支持新标准并优化性能;finally块语义强化(PEP 765)确保资源清理可靠性。这些改进使Python在后端开发、数据科学等领域更具竞争力。
329 5
解读 Python 3.14:模板字符串、惰性类型、Zstd压缩等7大核心功能升级
|
8月前
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
280 22
|
9月前
|
API 开发工具 Python
|
10月前
|
运维 应用服务中间件 nginx
docker运维查看指定应用log文件位置和名称
通过本文的方法,您可以更高效地管理和查看Docker容器中的日志文件,确保应用运行状态可控和可监测。
1525 28
|
存储 SQL 关系型数据库
【赵渝强老师】PostgreSQL的运行日志文件
PostgreSQL的物理存储结构包括数据文件、日志文件等。运行日志默认未开启,需配置`postgresql.conf`文件中的相关参数如`log_destination`、`log_directory`等,以记录数据库状态、错误信息等。示例配置中启用了CSV格式日志,便于管理和分析。通过创建表操作,可查看生成的日志文件,了解具体日志内容。
378 3
|
监控 数据挖掘 数据安全/隐私保护
Python脚本:自动化下载视频的日志记录
Python脚本:自动化下载视频的日志记录
|
SQL 关系型数据库 MySQL
【赵渝强老师】MySQL的全量日志文件
MySQL全量日志记录所有操作的SQL语句,默认禁用。启用后,可通过`show variables like %general_log%检查状态,使用`set global general_log=ON`临时开启,执行查询并查看日志文件以追踪SQL执行详情。
217 4
|
存储 安全 Python
[python]使用标准库logging实现多进程安全的日志模块
[python]使用标准库logging实现多进程安全的日志模块
485 1

推荐镜像

更多