Windows 使用 jq 跟踪日志文件

Windows tail a log file with jq

我正在使用 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"}

...

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

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

但是我不能同时使用 -Wait 和 jq。关于如何让它发挥作用有什么建议吗?

您可以创建自己的函数来处理 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

你可以通过参数化你想要的属性来扩展它,但这应该让你开始。