go語言實現 tail 查看文字檔末行功能,類似於linux tail -n 100 功能

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

主要用於Web服務日誌最新行查看。

package main

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

const (
  defaultBufSize = 4096
)

func tail( filename string, n int ) (lines []string,err error) {
  f,e := os.Stat( filename )
  if e == nil {
    size := f.Size()
    var fi *os.File
    fi,err = os.Open(filename)
    if err == nil{
      b := make( []byte,defaultBufSize )
      sz := int64(defaultBufSize)
      nn := n
      bTail := bytes.NewBuffer([]byte{})
      istart := size
      flag := true
      for flag {
        if istart < defaultBufSize {
          sz = istart
          istart = 0
          //flag = false
        }else{
          istart -= sz
        }
        _,err = fi.Seek( istart,os.SEEK_SET )
        if err==nil {
          mm,e := fi.Read( b )
          if e==nil && mm>0 {
            j := mm
            for i:=mm-1;i>=0;i-- {
              if b[i]=='\n' {
                bLine := bytes.NewBuffer([]byte{})
                bLine.Write( b[i+1:j] )
                j = i
                if bTail.Len()>0 {
                  bLine.Write( bTail.Bytes() )
                  bTail.Reset()
                }

                if (nn==n && bLine.Len()>0) || nn<n {//skip last "\n"
                  lines = append( lines,bLine.String() )
                  nn --
                }
                if nn==0 {
                  flag = false
                  break
                }
              }
            }
            if flag && j>0 {
              if istart==0 {
                bLine := bytes.NewBuffer([]byte{})
                bLine.Write( b[:j] )
                if bTail.Len()>0 {
                  bLine.Write( bTail.Bytes() )
                  bTail.Reset()
                }
                lines = append( lines,bLine.String() )
                flag = false
              }else{
                bb := make( []byte,bTail.Len() )
                copy( bb,bTail.Bytes() )
                bTail.Reset()
                bTail.Write( b[:j] )
                bTail.Write( bb )
              }
            }
          }
        }
      }
      //func (f *File) Seek(offset int64, whence int) (ret int64, err error)
       //func (f *File) Read(b []byte) (n int, err error) {
    }
    defer fi.Close()
  }
  return
}

func main(){

  lns,_ := tail("此處為記錄檔路徑",50)  //查看檔案末行

  for _,v := range lns {

    fmt.Println( v )

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.