如何将多行日志异常合并到一行

How to combine log exception from multiple lines to one line

我有一个包含异常的日志文件,其中异常位于不同的行中。我想让 sed/awk/cut 把它们合二为一。规则。第一行的开头总是有一个日期时间戳。

示例:(5 行异常)

2017-04-24T04:26:58.728-0400 - VALUE {tomcat-device-http-1} none|none 
[{{0ecfe8a7}{Uri, - WARN Could not marshal entity
java.lang.ArrayIndexOutOfBoundsException: -1
    at com.sun..java:487)
    at com.sun:323)
    at com.sun.java:251)

最终结果:

2017-04-24T04:26:58.728-0400 - VALUE {tomcat-device-http-1} none|none [{{0ecfe8a7}{Uri, - WARN Could not marshal entity java.lang.ArrayIndexOutOfBoundsException: -1 at com.sun..java:487) at com.sun:323) at com.sun.java:251)

这个批处理文件做你想做的事:

@echo off
setlocal EnableDelayedExpansion

(
for /F "delims=" %%a in (input.txt) do (
   set "line=%%a"
   if "!line:~0,2!" equ "20" echo/
   set /P "=%%a "
)
echo/
) < NUL > output.txt

下面是使用 JREPL.BAT - a regular expression text processor 的简单高效(快速)解决方案。 JREPL.BAT 是纯脚本(混合 batch/JScript),可在 XP 及更高版本的任何 Windows 机器上本地运行 - 不需要第 3 方 exe 文件。

以下将直接从命令行运行,不需要批处理文件。

如果日志文件 test.log 已经存在并且您想在屏幕上查看输出,则:

jrepl "^(?:(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}-\d{4} -)|\s*)(.*)" "stdout.write((?'\n'+:'  ')+);$txt=false" /jmatchq /f test.log

如果要将结果写入文件"output.log",则追加/o output.log

如果要覆盖原文件,则追加/o -

如果要将命令放在批处理脚本中,请使用 call jrepl

如果您有一个将日志写入标准输出的程序,那么您可以将程序输出通过管道传输到命令并删除 /f 选项。

logGeneratingCommand | jrepl "^(?:(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d{3}-\d{4} -)|\s*)(.*)" "stdout.write((?'\n'+:'  ')+);$txt=false" /jmatchq 

显然您可以添加 /o outfile/o - 选项。

使用管道时,批处理脚本中不需要

CALL

完整的 JREPL 文档可通过 jrepl /? 从命令行获得,或 jrepl /?? 获取分页帮助。可通过 jrepl /?options 获得选项汇总列表。使用 jrepl /?help 获取所有帮助选项的完整列表。