2017-09-28 9 views
0

내 응용 프로그램이 로그를 저장하는 파일 (application.log)이 있습니다. 때로 예외가 생겼으므로 에만 예외 ()를 다른 파일 (exception.log)에 저장하고 싶습니다.grep multiline stack trace? 결함이있는 스레드가 내 솔루션으로 작성되었습니다.

kill $(ps -ef | grep tail | awk '{print $2}') 
tail -f /path/to/my/application.log | pcregrep -M 'Exception[^\[]+' | while read line 
do 
(echo "$line" >> /path/to/my/exception.log) 
done & 

:

[2017-28-09 10:00:10,000] Text of Exception number 1 
at bla bla bla 
at bla bla bla  
at bla bla bla  
at bla bla bla 

내가 같은 방법으로 시도 : 보관해야 exception.log하는 등 siutation에서

[2017-28-09 10:00:00,000] Text of log number 1 
[2017-28-09 10:00:05,000] Text of log number 2 
[2017-28-09 10:00:10,000] Text of Exception number 1 
at bla bla bla 
at bla bla bla  
at bla bla bla  
at bla bla bla  
[2017-28-09 10:00:15,000] Text of log number 4 

: 로그의 각 줄은 같은 형식으로 날짜부터 시작 이 솔루션은 성공적으로 작업을 수행 할뿐만 아니라 많은 스레드를 생성했으며 시스템의 전체 스레드 수가 크게 증가했습니다. 그 때문에 다른 솔루션을 사용하거나 "문제가없는 문제"를 해결해야합니다.

혹시, 예외 추적 스택을 다른 파일로 잘라내거나 제거하지 못하도록 grep 또는 copy 만 할 수 있습니까?

+1

은 'tail -f /path/to/my/application.log |를 수행합니까? awk '/\[.*\]/{d=0; if ($ 0 ~ "Exception") d = 1} d '>>/path/to/my/exception.log'가 도움이됩니까? – CWLiu

+0

이것은 정확히 내가 물어 본 것입니다! 고마워 :-) –

+0

@CWLiu Hmmm ... 이제 마지막 줄도 잡았다는 것을 알았습니다 ("[2017-28-09 10 : 00 : 15,000] 로그 번호 4의 텍스트"를 의미 함). 이 코드를 변경하여 다음 코드가 아니라 Exception과 함께 줄만 쓰는 방법은 무엇입니까? –

답변

2
$ cat test.txt 
[2017-28-09 10:00:00,000] Text of log number 1 
[2017-28-09 10:00:05,000] Text of log number 2 
[2017-28-09 10:00:10,000] Text of Exception number 1 
at bla bla bla 
at bla bla bla  
at bla bla bla  
at bla bla bla  
[2017-28-09 10:00:15,000] Text of log number 4 

$ awk '/\[.*\]/{d=0; if($0 ~ "Exception")d=1}d' test.txt 
[2017-28-09 10:00:10,000] Text of Exception number 1 
at bla bla bla 
at bla bla bla  
at bla bla bla  
at bla bla bla 
+0

당신은 옳았습니다, 지금 그것은 나의 거짓이었습니다. 모든 것이 좋습니다, 감사합니다 .-) –

0

공백으로 시작하는 줄을 일치시키기 전에 한 줄을 인쇄하도록 grep에 지시하십시오.

grep -B1 '^ ' 
+0

내가 요청한 것이 아니지만 지원을 시도해 주셔서 감사합니다 –

+0

질문에있는 예제 데이터는 귀하가 요청한 것입니다. 그것은 당신이 받아 들인 답과 정확히 똑같은 출력을 생성합니다. 문제가 해결되지 않으면 문제가 귀하의 문제와 일치하지 않습니다. – ceving

0

다음은 "꼬리 -f"없이 @CWLiu 솔루션 및 솔루션의 종류이다. 간단하지만 유용하고 스레드 -f 놀고 없음 좀비 프로세스 또는 꼬리가 : 일부 예외가 발생했을 경우

#!/bin/bash 

# Below I checked if last.log file exists 
if [ ! -f /path/to/my/last.log ]; then 
    echo "" > /path/to/my/last.log 
fi 

# Thanks @CWLiu again for your below solution 
awk '/\[.*\]/{d=0; if($0 ~ "Exception")d=1}d' /path/to/my/application.log > /path/to/my/now.log 

# Creation differential file - now.log stores all exceptions, last.log stores all exceptions from previous check 
diff /path/to/my/now.log /path/to/my/last.log > /path/to/my/tmp.log 
diff /path/to/my/last.log /path/to/my/now.log | grep ">" | tr -d '>' >> /path/to/my/exception.log 

지금 내가 즉, 매 분마다 확인하는 crontab을이 파일의 실행을 추가 할 수 있습니다

* * * * * /path/to/my/file.sh