miguel5655 Posted August 18, 2013 at 02:15 PM Report #522004 Posted August 18, 2013 at 02:15 PM (edited) Boas. Estou com alguma dificuldade em arranjar uma maneira de ler blocos de texto. É assim preciso fazer uma app que vá lendo o ficheiro de logs que está na máquina local de "x" em "x" tempo e sempre que existam novos erros, ele envia por mail. A minha ideia aceder ao ficheiro onde estão os logs e guardar o índice da linha do último erro enviado por email num ficheiro de texto, e depois verificar se depois desse indice existem mais erros ( um ou mais ), ler esses blocos de texto e enviar por email. A minha dificuldade está em ler a partir desse indice e agrupar os blocos de texto dos erros para enviar. Alguém me consegue ajudar ?? O que vou fazer para saber que é um erro é ler linha a linha e encontrar a palavra ERROR e sei que o erro termina quando tiver a palavra EXITING... Ou então quando encontrar o formato de data novamente sabe que terminou o erro. O código que tenho é este, claro que falta a lógica para ler os blocos de texto: Public Sub genErrorMessagesLog() Dim FILE_NAME As String = "C:\Users\***\Desktop\teste.txt" Dim FILE_NAME_ERROR As String = "C:\Users\***\Desktop\LastErrorLog.txt" Dim FILE_NAME_WRT_TIME As String = "C:\Users\***\Desktop\LastWrtTime.txt" Dim notification As New List(Of String) Dim lineLastError As Integer Dim lastWrtTime As String = Nothing Dim indxLine As String = Nothing If System.IO.File.Exists(FILE_NAME) = True Then 'Verificar se existe o ficheiro com a utlima vez que foi acedido no log If System.IO.File.Exists(FILE_NAME_WRT_TIME).ToString() = True Then lastWrtTime = File.ReadAllText(FILE_NAME_WRT_TIME).ToString() ''Verificar se coincide a ultima vez que o log foi acedido com o que foi guardado If Not lastWrtTime.Equals(File.GetLastWriteTime(FILE_NAME).ToString()) Then 'Verificar se existe o ficheiro com a linha do ultimo erro If System.IO.File.Exists(FILE_NAME_ERROR) Then lineLastError = File.ReadAllText(FILE_NAME_ERROR).ToString() Dim lines() As String = IO.File.ReadAllLines(FILE_NAME) If (IsDate(lines.ElementAt(lineLastError).Substring(0, 22))) Then /// End If Else Dim lines() As String = IO.File.ReadAllLines(FILE_NAME) indxLine = Array.FindLastIndex(lines, Function(s) s.Contains(" ERROR ")) Using outfile As New StreamWriter(FILE_NAME_ERROR) outfile.Write(indxLine) End Using End If End If Else 'Criar o ficheiro Using outfile As New StreamWriter(FILE_NAME_WRT_TIME) outfile.Write(File.GetLastWriteTime(FILE_NAME).ToString()) End Using End If End If End Sub O ficheiro de log tem o seguinte formato: 2013-08-09 16:37:02.346 UTC (6760) ERROR Server was unable to process request. ---> An exclusive lock could not be acquired for this item. Please try again later.Server stack trace: at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at ProcessPostSortOut.OnTimeTaskService.TaskHandlerSoap.UpdateTask(Guid securityToken, Task task) at ProcessPostSortOut.OnTimeTaskService.TaskHandlerSoapClient.UpdateTask(Guid securityToken, Task task) in 2 Exiting... 2013-08-12 07:53:23.755 UTC (4900) VERBOSE STARTED BuildDate=2013-08-12 08:53:18 (Arguments: "--export-to-ontime"; User= ; UserInteractive=True) ------------------------------------------------------------ 2013-08-12 10:43:49.526 UTC (596) VERBOSE STARTED BuildDate=2013-08-12 11:43:19 (Arguments: "--export-to-ontime"; User=; UserInteractive=True) ------------------------------------------------------------ 2013-08-12 10:48:45.917 UTC (596) ERROR Server was unable to process request. ---> Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Server stack trace: at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at ProcessPostSortOut.OnTimeAttachmentService.AttachmentHandlerSoap.AddAttachment(Guid securityToken, Attachment attachment) Exiting... 2013-08-12 11:12:02.566 UTC (592) VERBOSE exportPlanning(): Task not found! 2013-08-12 11:12:02.578 UTC (592) VERBOSE exportPlanning(): Task not found! 2013-08-12 11:12:02.590 UTC (592) VERBOSE exportPlanning(): Task not found! 2013-08-12 11:12:02.603 UTC (592) VERBOSE exportPlanning(): Task not found! 2013-08-12 11:12:02.619 UTC (592) VERBOSE exportPlanning(): Task not found! 2013-08-12 11:12:02.632 UTC (592) VERBOSE exportPlanning(): Task not found! Edited August 18, 2013 at 10:17 PM by thoga31 GeSHi
nelsonr Posted August 18, 2013 at 05:37 PM Report #522019 Posted August 18, 2013 at 05:37 PM Boas, aqui vai um exemplo assim feito à pressa, vê se ajuda: Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick Timer2.Enabled = False ' Dim ficheiroLinhasJaProcessadas As String = "C:\TESTE\LinhasJaProcessadas.txt" Dim ficheiroLog As String = "C:\TESTE\log.txt" Dim linhaAProcessar As Integer = 0 Dim blocosErros As New List(Of String) If File.Exists(ficheiroLinhasJaProcessadas) Then Dim LinhasJaProcessadas As String = File.ReadAllText(ficheiroLinhasJaProcessadas) Integer.TryParse(LinhasJaProcessadas, linhaAProcessar) End If ' If File.Exists(ficheiroLog) Then Dim blocoErro As New StringBuilder Dim capturandoBloco As Boolean ' capturandoBloco = False For Each linha As String In File.ReadLines(ficheiroLog).Skip(linhaAProcessar) ' Inicio de bloco ' "2013-08-09 16:37:02.346 UTC (6760) ERROR Server was unable to process request. ---> An exclusive lock could not be acquired for this item. Please try again later." If Regex.IsMatch(linha, "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d+ \w+ \(\d*\) ERROR") Then ' Se estava a capturar outro bloco If capturandoBloco Then blocosErros.Add(blocoErro.ToString()) End If ' blocoErro.Clear() capturandoBloco = True End If ' If capturandoBloco Then blocoErro.AppendLine(linha) End If ' Fim de bloco If linha = "Exiting..." And capturandoBloco Then blocosErros.Add(blocoErro.ToString()) blocoErro.Clear() capturandoBloco = False End If linhaAProcessar = linhaAProcessar + 1 Next End If ' File.WriteAllText(ficheiroLinhasJaProcessadas, linhaAProcessar.ToString()) ' Processar blocos de erros (enviar por email?) For Each bloco As String In blocosErros '.... Next ' Timer2.Enabled = True End Sub
miguel5655 Posted August 19, 2013 at 08:52 AM Author Report #522058 Posted August 19, 2013 at 08:52 AM Boas, aqui vai um exemplo assim feito à pressa, vê se ajuda: Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick Timer2.Enabled = False ' Dim ficheiroLinhasJaProcessadas As String = "C:\TESTE\LinhasJaProcessadas.txt" Dim ficheiroLog As String = "C:\TESTE\log.txt" Dim linhaAProcessar As Integer = 0 Dim blocosErros As New List(Of String) If File.Exists(ficheiroLinhasJaProcessadas) Then Dim LinhasJaProcessadas As String = File.ReadAllText(ficheiroLinhasJaProcessadas) Integer.TryParse(LinhasJaProcessadas, linhaAProcessar) End If ' If File.Exists(ficheiroLog) Then Dim blocoErro As New StringBuilder Dim capturandoBloco As Boolean ' capturandoBloco = False For Each linha As String In File.ReadLines(ficheiroLog).Skip(linhaAProcessar) ' Inicio de bloco ' "2013-08-09 16:37:02.346 UTC (6760) ERROR Server was unable to process request. ---> An exclusive lock could not be acquired for this item. Please try again later." If Regex.IsMatch(linha, "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d+ \w+ \(\d*\) ERROR") Then ' Se estava a capturar outro bloco If capturandoBloco Then blocosErros.Add(blocoErro.ToString()) End If ' blocoErro.Clear() capturandoBloco = True End If ' If capturandoBloco Then blocoErro.AppendLine(linha) End If ' Fim de bloco If linha = "Exiting..." And capturandoBloco Then blocosErros.Add(blocoErro.ToString()) blocoErro.Clear() capturandoBloco = False End If linhaAProcessar = linhaAProcessar + 1 Next End If ' File.WriteAllText(ficheiroLinhasJaProcessadas, linhaAProcessar.ToString()) ' Processar blocos de erros (enviar por email?) For Each bloco As String In blocosErros '.... Next ' Timer2.Enabled = True End Sub Grande ajuda mesmo. Obrigado
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now