【问题标题】:Parsing log file (custom name of column)解析日志文件(列的自定义名称)
【发布时间】:2016-10-26 16:17:51
【问题描述】:

我尝试解析日志文件并输出格式化结果。
结果文件已创建,但运行脚本后为空。

源日志文件:

2011-07-08 14:34:40.609 Ber   8 [R:   1] Http ->   GET http://test.com:80/api/test?__crd=78F5WE6WE
2011-08-08 12:34:51.202 Inf   9 [R:   1] Http <~   GET http://TEST.com:80/api/gs?__crid=7B9790431B8 [304 Not Modified] [11.774 ms]
2011-08-08 15:38:52.166 War   8 [R:  33] [Excn][Type:Api][Err:300][HTTPStatus:NotFound][Message:PCNDLS_. ISE Account : 111][CorrId:hvukyhv78r5564]

Write-Host 'Hello! My Name is test  !'

$Files = Get-ChildItem  C:\log\1\* -Include *.log 

New-Item -ItemType file -Path C:\log\result.txt –Force

foreach ($File in $Files)
{
    $StringMatch = $null
    $StringMatch = select-string $File -pattern  "[Exception]|[304 Not Modified]"
    if ($StringMatch) {out-file -filepath C:\log\result.txt -inputobject $StringMatch }

    $regex = 'Line\s+(\d+):\s+([^;]+);([^;]+);([^;]+);(.+)'
    [regex]::Matches($StringMatch, $regex) | ForEach-Object {
        [PsCustomObject]@{
            ID = $_.Groups[1].Value
            Time = $_.Groups[2].Value
            Status = $_.Groups[3].Value
            URL = $_.Groups[4].Value
            Message = $_.Groups[5].Value
        }
    }
}

【问题讨论】:

  • "[Exception]|[304 Not Modified]" 是一个错误的正则表达式,因为[] 具有特殊含义,所以它们应该被转义:"\[Exception\]|\[304 Not Modified\]" 并且您在每次迭代中覆盖结果:可能想使用-Append 开关...无论如何,通过设置断点在 PowerShell ISE 中调试脚本,然后单步执行代码,检查变量。
  • 您的源日志显示305 not modified,但您的代码查找304 not modifiedforeach (){} 不输出到管道 - 你把输出扔掉了。您的代码在日志中查找一行,但您想要的输出需要来自上一行的crd 信息,以及来自后续行的HTTPStatusMessage,您将需要使用Select-String -Context 并阅读.Context它生成的 MatchInfo 对象的属性。
  • @wOxxOm 谢谢,但无济于事((
  • @TessellatingHeckler 谢谢,但没有帮助((我更新问题
  • 你应该调试代码。

标签: powershell


【解决方案1】:

我认为您的搜索模式存在问题,但通常您似乎在与自然的 Powershell 做事方式作斗争。如果您使用管道方法,您的生活会轻松很多。试试下面的例子:

$regex = 'Line\s+(\d+):\s+([^;]+);([^;]+);([^;]+);(.+)'
$pat = "\[Exception\]|\[304 Not Modified\]"
$path = "C:\log\1\*.log"
$file = "C:\log\result.txt"

Remove-Item $file -ErrorAction SilentlyContinue
Get-ChildItem $path | Select-String -Pattern $pat | Select -ExpandProperty line | % {
    $_ | Add-Content $file
    # Add code to create object here
}

或者如果你不需要对象,你可以这样做:

 Get-ChildItem $path | Select-String -Pattern $pat | Select -ExpandProperty line | Add-Content $file

【讨论】:

  • 以及如何添加过滤器?
猜你喜欢
  • 2016-12-17
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
相关资源
最近更新 更多