首页 > 系统 > Linux > 正文

利用shell命令统计日志的方法详解

2019-10-26 18:55:11
字体:
来源:转载
供稿:网友

前言

大家都知道,通过使用 shell 命令可以很方便地对日志进行统计和分析,当服务有异常的时候,需要去排查日志,那么掌握一种统计日志的技巧就是必不可少的了。

假设有一个包含下面内容的日志文件 access.log。我们以统计这个文件的日志为例。

date=2017-09-23 13:32:50 | ip=40.80.31.153 | method=GET | url=/api/foo/bar?params=something | status=200 | time=9.703 | bytes=129 | referrer="-" | user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7" | cookie="-"date=2017-09-23 00:00:00 | ip=100.109.222.3 | method=HEAD | url=/api/foo/healthcheck | status=200 | time=0.337 | bytes=10 | referrer="-" | user-agent="-" | cookie="-"date=2017-09-23 13:32:50 | ip=40.80.31.153 | method=GET | url=/api/foo/bar?params=anything | status=200 | time=8.829 | bytes=466 | referrer="-" | user-agent="GuzzleHttp/6.2.0 curl/7.19.7 PHP/7.0.15" | cookie="-"date=2017-09-23 13:32:50 | ip=40.80.31.153 | method=GET | url=/api/foo/bar?params=everything | status=200 | time=9.962 | bytes=129 | referrer="-" | user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7" | cookie="-"date=2017-09-23 13:32:50 | ip=40.80.31.153 | method=GET | url=/api/foo/bar?params=nothing | status=200 | time=11.822 | bytes=121 | referrer="-" | user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7" | cookie="-"

不同的服务对应的日志可能不一样,本文使用示例日志的格式是:

date | ip | method | url | status | time | bytes | referrer | user-agent | cookie

注意:mac 系统和 linux 系统中的命令行为可能不同,以下命令请在 linux 系统中使用

排除特殊日志

统计日志时,我们可能不关心 HEAD 请求,或者只关心 GET 请求,这里首先需要筛选日志,可以使用 grep 命令。-v 的含义是排除匹配的文本行。

grep GET access.log # 只统计 GET 请求grep -v HEAD access.log # 不统计 HEAD 请求grep -v 'HEAD/|POST' access.log # 不统计 HEAD 和 POST 请求

查看接口耗时情况

我们可以将每行的 time 匹配出来,然后做一个排序。使用 awk 的 match 方法可以匹配正则:

awk '{ match($0, /time=([0-9]+/.[0-9]+)/, result); print result[1]}' access.log

awk 命令使用方法如下:

awk '{pattern + action}' {filenames}

我们实际上只用到了 action:match($0, /time=([0-9]+/.[0-9]+)/, result); print result[1] 这一段。

match 方法接收三个参数:需要匹配的文本、正则表达式、结果数组。$0 代表 awk 命令处理的每一行,结果数组是可选的,因为我们要拿到匹配结果所以这里传入了一个 result 数组,用来存储匹配后的结果。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表