Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

How not to capture the same error in a log when a powershell script runs every 5 minutes

I am now trying not to capture the same error in a log when the below script runs. The script is running every 5 minutes. The goal is to store the last time the log was checked with a time stamp. If there is no new entry (of the same error) when the script runs then there is nothing to do. (shouldn't send an Email) Else it should send an Email.

Thank you in advance for your time

$Date = Get-Date
$File = 'D:......logsNikos_text2.txt'
if ($content -like  '*Trigger action error*' | Where-Object {$_.LastWriteTime -lt (get- 
 date).addMinutes(-5) } | Select-Object LastWriteTime) {
$smtp = new-object Net.Mail.SmtpClient("server name")
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "[email protected]"
$objMailMessage.To.Add("[email protected]")
$objMailMessage.To.Add("[email protected]")
$objMailMessage.Subject = "Error message: 'Trigger action error'"
$objMailMessage.Body = "In log in server I traced the following error message: Trigger action error. 
  Pls check it asap"
$smtp.send($objMailMessage)
} else {
 break
}

I made some adjustments to my original code:

$File = 'D:...auroralogsNikos_text2.txt'
$content = Get-Content $File
$date =(Get-Date).AddMinutes(-5)
$time = @(Get-Item $File | Where-Object {$_.LastWriteTime -le $date})
If (time -eq 'True' -and $content -like  '*Trigger action error*'){
$smtp = new-object Net.Mail.SmtpClient("server name")
$objMailMessage = New-Object System.Net.Mail.MailMessage
$objMailMessage.From = "[email protected]"
$objMailMessage.To.Add("[email protected]")
$objMailMessage.To.Add("[email protected]")
$objMailMessage.Subject = "Error message: 'Trigger action error'"
$objMailMessage.Body = "In log in server I traced the following error message: 
 Trigger action error. Pls check it asap"
$smtp.send($objMailMessage)} else {
Exit
}

but now I don't receive any Email... What have I done wrong?

Thank you in advance

This is how a log looks like:

    2021-01-05 13:02:14,657
ERROR  on 
[Processor... ] It is not allowed to disable this user: [WebContainer : 8](ConfigurationStore.java:143)

2021-01-05 13:02:14,657
ERROR  on 
## in: custom.moduleule.Processor@412971a2
[WebContainer : 8](ConfigurationStore.java:147)

2021-01-05 15:44:45,328
ERROR HttpContext on 
Application Error!
[WebContainer : 3](LoggingHelper.java:129)

java.lang.NullPointerException
    at com..apps.common.util.HttpContext.getAdminService(HttpContext.java:318)
    at com..apps.common.util.HttpContext.checkForProfileChange(HttpContext.java:908)
    at com..apps.common.util.HttpContext.getMenuData(HttpContext.java:925)
    at com..apps.sosa.util.MenuUtil.createMenuData(MenuUtil.java:181)
    at com..apps.sosa.util.MenuUtil.createTopLevelMenuData(MenuUtil.java:208)
    at com..apps.sosa.SoxPageLoaderAction.getTopLevelMenuData(SoxPageLoaderAction.java:208)
    at com..apps.common.PageLoaderAction.doLoad(PageLoaderAction.java:169)
    at com..apps.common.AbstractPageLoaderAction.doLoad(AbstractPageLoaderAction.java:99)
    at com..apps.common.AbstractLoaderAction.execute(AbstractLoaderAction.java:176)
    at com..apps.common.util.OPRequestProcessor.processTilesDefinition(OPRequestProcessor.java:656)
    at org..struts.tiles.TilesRequestProcessor.internalModuleRelativeForward(TilesRequestProcessor.java:341)
    at org..struts.action.RequestProcessor.processForward(RequestProcessor.java:572)
    at org..struts.action.RequestProcessor.process(RequestProcessor.java:221)
    at com..apps.common.util.OPRequestProcessor.process(OPRequestProcessor.java:248)
    at org..struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org..struts.action.ActionServlet.doGet(ActionServlet.java:414)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com..ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1235)
    at com..ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com..ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com..ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com..ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:143)
    at com..ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:78)
    at com..ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:969)
    at com..ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1109)
    at com..ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1408)
    at com..ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:553)
    at com..ws.webcontainer.webapp.WebApp.sendError(WebApp.java:3666)
    at com..wsspi.webcontainer.collaborator.CollaboratorHelper.processSecurityPreInvokeException(CollaboratorHelper.java:145)
    at com..ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1199)
    at com..ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:82)
    at com..ws.webcontainer.WebContainer.handleRequest(WebContainer.java:963)
    at com..ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com..ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:382)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:532)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:318)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:289)
    at com..ws.ssl.channel.impl.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1187)
    at com..ws.ssl.channel.impl.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:694)
    at com..ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
    at com..ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com..io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com..io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com..io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com..io.async.ResultHandler.complete(ResultHandler.java:204)
    at com..io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com..io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com..ws.util.ThreadPool$Worker.run(ThreadPool.java:1909)
-- nested by --
2021-01-05 15:44:45
CODE       : 00002
LEVEL      : 4
NAME       : com.apps.common.util.ApplicationException
ERROR #    : UTUD3SIQY3Z0
TOKEN ID   : 2574333
USER       : System
MESSAGE    : The requested operation could not be completed.
    at com..apps.common.util.LoggingHelper.logError(LoggingHelper.java:128)
    at com..apps.common.util.ErrorHandler.log(ErrorHandler.java:644)
    at com..apps.common.util.ErrorHandler.handleError(ErrorHandler.java:131)
    at com..apps.common.util.ErrorHandler.handleError(ErrorHandler.java:100)
    at com..apps.common.AbstractLoaderAction.handleException(AbstractLoaderAction.java:926)
    at com..apps.common.AbstractPageLoaderAction.doLoad(AbstractPageLoaderAction.java:109)
    at com..apps.common.AbstractLoaderAction.execute(AbstractLoaderAction.java:176)
    at com..apps.common.util.OPRequestProcessor.processTilesDefinition(OPRequestProcessor.java:656)
    at org..struts.tiles.TilesRequestProcessor.internalModuleRelativeForward(TilesRequestProcessor.java:341)
    at org..struts.action.RequestProcessor.processForward(RequestProcessor.java:572)
    at org..struts.action.RequestProcessor.process(RequestProcessor.java:221)
    at com..apps.common.util.OPRequestProcessor.process(OPRequestProcessor.java:248)
    at org..struts.action.ActionServlet.process(ActionServlet.java:1196)
    at org..struts.action.ActionServlet.doGet(ActionServlet.java:414)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at com..ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1235)
    at com..ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com..ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com..ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com..ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:143)
    at com..ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:78)
    at com..ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:969)
    at com..ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1109)
    at com..ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1408)
    at com..ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:553)
    at com..ws.webcontainer.webapp.WebApp.sendError(WebApp.java:3666)
    at com..wsspi.webcontainer.collaborator.CollaboratorHelper.processSecurityPreInvokeException(CollaboratorHelper.java:145)
    at com..ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1199)
    at com..ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:82)
    at com..ws.webcontainer.WebContainer.handleRequest(WebContainer.java:963)
    at com..ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com..ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:382)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:532)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:318)
    at com..ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:289)
    at com..ws.ssl.channel.impl.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1187)
    at com..ws.ssl.channel.impl.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:694)
    at com..ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
    at com..ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com..io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com..io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com..io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com..io.async.ResultHandler.complete(ResultHandler.java:204)
    at com..io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com..io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com..ws.util.ThreadPool$Worker.run(ThreadPool.java:1909)
2021-01-05 17:07:24,200
ERROR HttpContext on 
Application Error!
[WebContainer : 3](LoggingHelper.java:129)

java.lang.NullPointerException
    at com.apps.common.util.HttpContext.getAdminService(HttpContext.java:318)
    at com.apps.common.util.HttpContext.checkForProfileChange(HttpContext.java:908)
    at com.apps.common.util.HttpContext.getMenu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's start with your revamp with the While loop... you were so close! When PowerShell evaluates a comparison it uses the type of the left hand object to perform the comparison. In your case you have:

($_ -split ',')[0] -gt $time

Now ($_ -split ',')[0] is just text, it's a [string]. It quite likely contains a valid date for the string, but it is still just a string. So PowerShell converts (or at least tries to) $time to a string, and then does the comparison. If you just reverse it PowerShell will see that $time is a [datetime] object, and will try to convert ($_ -split ',')[0] to be a time object as well, and perform the comparison on two times which is really what you want. What you have may very well work by changing that to:

$time -lt ($_ -split ',')[0]

But wait, there's more!

Your log has timestamps in it, that makes this much better! First get your log as one multi-line string, then split on lines that begin with your timestamp pattern, and parse for times that happened in the last 5 minutes!

$RawLog = Get-Content 'D:......logs...log' -Raw
If($RawLog -split '(?sm)[
](?=d{4}-dd-dd dd:dd:dd)'|Where{[datetime]::Now.AddMinutes(-5) -lt $_.Substring(0,18) -and $_ -match 'Application Error!'}){
    $smtp = new-object Net.Mail.SmtpClient("server")
    $objMailMessage = New-Object System.Net.Mail.MailMessage
    $objMailMessage.From = "[email protected]"
    #$objMailMessage.To.Add("[email protected]")
    $objMailMessage.To.Add("[email protected]")
    $objMailMessage.Subject = "Error message: 'Application error'"
    $objMailMessage.Body = "In log in server I traced the following error message: Application error"
    $smtp.send($objMailMessage)
    }

To break that down a little, we first get the whole log as one long string (with line breaks intact and all that). After that we split the log by looking for either a Carriage Return or New Line character (as represented by [ ]), with a RegEx Look Ahead looking for 4 numbers, a hyphen, 2 numbers, a hyphen, 2 numbers, a space, 2 numbers, colon, 2 numbers, colon, 2 numbers. The way this work is that it removes that new line character, and splits the big string into two parts, then moves on through the second part and keeps doing that splitting it into individual records. For the sample log you provided we end up with 6 records, the last of which is:

2021-01-05 17:07:24
CODE       : 00002
LEVEL      : 4
NAME       : com.apps.common.util.ApplicationException
ERROR #    : UTUG12S6W7J0
TOKEN ID   : 2574334
USER       : 100940297
IP         : 10.174.25.221
HOST       : xpe1.net

Then we send each of those records through a Where statement where it checks if the record as a whole matches your search string, and then compares [datetime]::Now.AddMinutes(-5), which is a [datetime] object to $_.Substring(0,18), which is the first 18 characters of the current record, or in this case 2021-01-05 17:07:24. Since the left hand item is a [datetime] it will try to convert 2021-01-05 17:07:24 to a [datetime], which it can totally do, and checks to see if that happened in the last 5 minutes. If any of the records both match the search text, and happened in the last 5 minutes they'll make it past the Where statement, which makes the If() evaluate to $true and it will execute the code in the scriptblock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...