This is a creation in Article, where the information may have evolved or changed.
Used primarily for the latest line view of Web service logs.
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 ("Here is the log file path", 50)//view the last line of the file
For _,v: = Range LNS {
Fmt. Println (v)
}
}