go tail 使用

git 仓库:https://github.com/hpcloud/tail.git

package main

import (
    "fmt"
    "github.com/hpcloud/tail"
    "strings"
)

type InfoData struct {
    InIntf   string
    OutIntf  string
    SrcAddr  string
    DstAddr  string
    Protocol string
    SrcPort  string
    DstPort  string
    DateTime string
}

func main() {
    t, err := tail.TailFile("/var/log/iptables.log", tail.Config{
        Location:  &tail.SeekInfo{0, 2},
        Follow:    true,
        MustExist: true,
        Logger:    tail.DiscardingLogger,
    })
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    defer t.Stop()

    for line := range t.Lines {
        data := InfoData{
            DateTime: line.Time.Format("2006-01-02 15:04:05"),
        }

        fmt.Println(line)
        fmt.Println(line.Time)
        fmt.Println(line.Text)

        n1 := strings.Split(line.Text, "iptables:")
        fmt.Println(n1)

        n2 := strings.Fields(n1[1])
        for n := range n2 {
            s := strings.Split(n2[n], "=")

            switch s[0] {
            case "IN":
                data.InIntf = s[1]
            case "OUT":
                data.OutIntf = s[1]
            case "SRC":
                data.SrcAddr = s[1]
            case "DST":
                data.DstAddr = s[1]
            case "SPT":
                data.SrcPort = s[1]
            case "DPT":
                data.DstPort = s[1]
            case "PROTO":
                data.Protocol = s[1]
            }
        }

        fmt.Println(data)
    }
}

 

go tail 使用

上一篇:php编码问题


下一篇:对高访问量与庞大数据处理的网站系统结构分析