Friday, June 24, 2011

Tail!

Quick and dirty tail application for your command line. Just create a console application, paste this code in, build it and you should be good to go.





Imports System
Imports System.IO
Imports System.Collections
Imports System.Threading
Imports System.Text
Imports Microsoft.VisualBasic
Imports System.Net

Module Module1
Dim tempstr As String

Sub Main(ByVal args() As String)
tailLog(Environment.CurrentDirectory & "\" & args(0))
End Sub



Sub tailLog(ByVal logName As String)
Dim filename As String = logName
Dim lastLogEntry As DateTime = DateTime.Now
Dim line As String
Dim filePath As New FileInfo(logName)

Try
Using logReader As New StreamReader(New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
'start at the end of the file

'This is the end of the file, send what's before it.
Dim logOffset As Long = logReader.BaseStream.Length

While True
Thread.Sleep(750)

'If the file size is the same nothing has changed in the log file and we can just loop again.
If logReader.BaseStream.Length = logOffset Then
Continue While
End If

'If the stream length changed it probably means the file was truncated or the file length changed
'Send the last line and reset the offset to the current length of the file.

'seek to the last max offset
logReader.BaseStream.Seek(logOffset, SeekOrigin.Begin)

'read out of the file until the EOF
While (helper(line, logReader.ReadLine())) IsNot Nothing
If line = "" Then
'If the line has no contents, skip it.
Else
Console.WriteLine(line)
End If

End While

logOffset = logReader.BaseStream.Position
End While
End Using
Catch ta As ThreadAbortException
'Thread abort exception will get thrown when the thread gets aborted by the expired timer, if anything needs to be done do it here.
'EventLog.WriteEntry(My.Application.Info.AssemblyName, ta.Message.ToString)
Catch ex As Exception
EventLog.WriteEntry(My.Application.Info.AssemblyName, & ex.Message.ToString)
End Try

End Sub

Function helper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function

No comments:

Post a Comment