登录
首页 >  Golang >  Go问答

解析GO中的日志文件

来源:stackoverflow

时间:2024-03-24 09:45:29 280浏览 收藏

本教程旨在指导初学者使用 Go 语言解析日志文件并提取特定信息。本文将介绍如何使用 Go 中的标准库(如 os 和 bufio)读取日志文件,并使用扫描器和正则表达式过滤和提取请求日志中与特定请求(如“request-a”)匹配的行。还将探讨性能优化和使用基准测试进行比较的不同解决方案的效率。

问题内容

这里是新手!

我正在尝试编写一个 go 程序,该程序将解析日志文件并返回匹配行的特定信息。

为了举例说明我想要实现的目标,我将从一个如下所示的日志文件开始:

2019-09-30t04:17:02 - request-a
2019-09-30t04:18:02 - request-c
2019-09-30t04:19:02 - request-b
2019-09-30t04:20:02 - request-a
2019-09-30t04:21:02 - request-a
2019-09-30t04:22:02 - request-b

从这里我想提取所有“request-a”并将请求发生的时间打印到终端或文件。

我尝试使用 os.open 和 scanner,我可以使用 scanner.text 来记录它发现了我的字符串的出现,如下所示:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    request := 0
    f, err := os.Open("request.log")
    if err != nil {
        fmt.Print("There has been an error!: ", err)
    }
    defer f.Close()
    scanner := bufio.NewScanner(f)

    for scanner.Scan() {
        if strings.Contains(scanner.Text(), "REQUEST-A") {
            request = request + 1
        }

        if err := scanner.Err(); err != nil {
        }
        fmt.Println(request)
    }
}

但我不确定如何使用它来检索我想要的信息。 通常我会使用 bash,但我想我应该扩展一下,看看是否可以使用 go。 任何建议将不胜感激。


解决方案


在 go 中,我们努力提高效率。不要做不必要的事情。

例如,

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "os"
)

func main() {
    lines, requesta := 0, 0
    f, err := os.open("request.log")
    if err != nil {
        fmt.print("there has been an error!: ", err)
    }
    defer f.close()

    scanner := bufio.newscanner(f)
    for scanner.scan() {
        lines++
        // filter request a
        line := scanner.bytes()
        if len(line) <= 30 || line[30] != 'a' {
            continue
        }
        if !bytes.equal(line[22:], []byte("request-a")) {
            continue
        }
        requesta++
        request := string(line)

        // handle request a
        fmt.println(request)
    }
    if err := scanner.err(); err != nil {
        fmt.println(err)
    }
    fmt.println(lines, requesta)
}

输出:

$ go run request.go

2019-09-30t04:17:02 - request-a
2019-09-30t04:20:02 - request-a
2019-09-30t04:21:02 - request-a
6 3

$ cat request.log
2019-09-30t04:17:02 - request-a
2019-09-30t04:18:02 - request-c
2019-09-30t04:19:02 - request-b
2019-09-30t04:20:02 - request-a
2019-09-30t04:21:02 - request-a
2019-09-30t04:22:02 - request-b

为了强调效率的重要性(日志可能非常大),让我们针对 Markus W Mahlberg 的解决方案运行一个基准测试:https://play.golang.org/p/R2D_BeiJvx9

$ go test log_test.go -bench=. -benchmem
benchmarkpeterso-4   21285     56953 ns/op    4128 b/op      2 allocs/op
benchmarkmarkusm-4     649   1817868 ns/op   84747 b/op   2390 allocs/op

log_test.go

package main

import (
    "bufio"
    "bytes"
    "regexp"
    "strings"
    "testing"
)

var requestlog = `
2019-09-30t04:17:02 - request-a
2019-09-30t04:18:02 - request-c
2019-09-30t04:19:02 - request-b
2019-09-30t04:20:02 - request-a
2019-09-30t04:21:02 - request-a
2019-09-30t04:22:02 - request-b
`

var benchlog = strings.repeat(requestlog[1:], 256)

func benchmarkpeterso(b *testing.b) {
    for n := 0; n < b.n; n++ {
        scanner := bufio.newscanner(strings.newreader(benchlog))
        for scanner.scan() {
            // filter request a
            line := scanner.bytes()
            if len(line) <= 30 || line[30] != 'a' {
                continue
            }
            if !bytes.equal(line[22:], []byte("request-a")) {
                continue
            }
            request := string(line)
            // handle request a
            _ = request
        }
        if err := scanner.err(); err != nil {
            b.fatal(err)
        }
    }
}

func benchmarkmarkusm(b *testing.b) {
    for n := 0; n < b.n; n++ {
        var re *regexp.regexp = regexp.mustcompile(`^(\s*) - request-a$`)
        scanner := bufio.newscanner(strings.newreader(benchlog))
        var res []string
        for scanner.scan() {
            if res = re.findstringsubmatch(scanner.text()); len(res) > 0 {
                _ = res[1]
            }
        }
        if err := scanner.err(); err != nil {
            b.fatal(err)
        }
    }
}

使用以下代码打印值为“request-a”的日志条目的时间字段。

for scanner.scan() {
    line := scanner.text()
    if len(line) < 19 {
        continue
    }
    if line[19:] == " - request-a" {
        fmt.println(line[:19])
    }
}

Run it on the Go play ground!

要写入文件,请将标准输出重定向到文件。

上面的代码假设时间戳之后的所有内容都是“-request-a”。如果“-request-a”是其他数据的前缀,请使用以下内容:

const lenTimestamp = 19
for scanner.Scan() {
    line := scanner.Text()
    if len(line) < lenTimestamp {
        continue
    }
    if strings.HasPrefix(line[lenTimestamp:], " - REQUEST-A") {
        fmt.Println(line[:lenTimestamp])
    }
}

Run this version on the playground

到这里,我们也就讲完了《解析GO中的日志文件》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>