【问题标题】:Windows tail a log file with jqWindows 使用 jq 尾随日志文件
【发布时间】:2020-10-27 00:02:09
【问题描述】:

我正在使用 Windows 10 Powershell。

我想跟踪一个 JSON 格式的日志文件,并且我还想选择特定的 json 字段。

示例日志文件:

{"msg":"abc def1","time":"20:08","notneeded1":"xyz","notneeded2":"xyz"}
{"msg":"abc def2","time":"20:09","notneeded1":"xyz","notneeded2":"xyz"}
{"msg":"abc def3","time":"20:10","notneeded1":"xyz","notneeded2":"xyz"}

...

我可以使用等待标志跟踪日志文件:Get-content -tail 10 -Wait 'C:\Desktop\data.log'

我可以通过 jq 选择特定的 json 字段:Get-content -tail 10 'C:\Desktop\data.log'|jq '.time,.msg'

但是我不能同时使用 -Wait 和 jq。有关如何使其工作的任何建议?

【问题讨论】:

  • 我也试过这个,但它不起作用:Get-content -tail 10 -Wait 'C:\Desktop\data.log' | ConvertFrom-Json |选择时间,味精
  • 为我工作。文件是如何写入的?哦,我在 powershell 7 中。

标签: powershell tail


【解决方案1】:

您可以创建自己的函数来处理 powershell 管道。当然,您需要更新 jq 文件的路径。

Function JQ {
    Param([parameter(valuefrompipeline)]$line)

    begin{
        $jq = "C:\temp\jq-win64.exe"
    }
    process{
        $line | &$Jq '.time,.msg'
    }
}

Get-Content $jsonfile -tail 10 -Wait | JQ

您可以通过参数化所需的属性来扩展它,但这应该可以帮助您入门。

【讨论】:

  • 这适用于 JQ,谢谢 Doug。我试图对这个Function parse { Param([parameter(valuefrompipeline)]$line) process{ $line | &ConvertFrom-Json | select time, msg } } 做同样的事情。但是这个失败了,有什么建议吗?
  • 我认为最好在新问题中处理而不是在 cmets 中处理。如果可能,我会调查并回答您的问题。
  • 实际上这也有效,我的错误。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多