여러 일치 조건이 있지만 일치 조건이 같은 줄에 있지 않은 크롤링 로그 파일 블록

여러 일치 조건이 있지만 일치 조건이 같은 줄에 있지 않은 크롤링 로그 파일 블록

암호:

grep -rI --exclude=*_*.log -B20 -A1 "Status:   Error" > /var/log/alertError.log

입력 로그 예:

[06/07/20 20:38:53.911]:loopback ST:                  token-src-name() 

[06/07/20 20:38:53.914]:loopback ST:                    Token Value: "DVADER". 

[06/07/20 20:38:53.916]:loopback ST:                  token-text(",OU=users,O=data") 

[06/07/20 20:38:53.919]:loopback ST:    Arg Value: "CN=DVADER,OU=users,O=data". 

[06/07/20 20:38:53.922]:loopback ST:                description("Removed by Termination Process") 

[06/07/20 20:38:53.926]:loopback ST:             token-text("Removed by Termination Process") 

[06/07/20 20:38:53.929]:loopback ST:                  Arg Value: "Removed by Termination Process". 

[06/07/20 20:38:53.943]:loopback ST: DirXML Log Event -------------------

     Driver:   \StarWars\system\Driver Set\User Processor

     Channel:  Subscriber

     Status:   Error

     Message:  Code(-9217) Error in

이 입력 로그에는 스크랩하려는 로그의 일부가 표시됩니다. 하지만 로그를 검색하려는 날짜와 일치시키고 싶습니다. 구조의 모든 로그 파일에 대해 재귀 검색을 수행할 수 있기 때문에 grep을 사용합니다. 내 grep은 내가 원하는 모든 데이터를 반환하지만 이제 이전 코드 블록을 제외하고 싶습니다. 따라서 날짜가 모든 행에 있는 것은 아닙니다. grep은 필요한 스위치 B와 A가 포함된 코드 조각을 반환합니다. 따라서 전체 행이 표시되면 메시지 및 상태 줄이 진행 중인 여러 작업과 일치하는 것입니다. 이 grep 명령을 사용하면 모든 유형의 메시지나 상태 값을 얻을 수 있지만, 주어진 날짜 범위에 대해서만 모든 결과를 코드 덩어리로 제거하는 방법을 모르겠습니다.

답변1

python해결책 은 다음과 같습니다 .

with open("log.txt") as f:                                  # open file log.txt
    lines = f.readlines()                                   # load lines
    nonempty = filter(lambda x: x.strip() != "", lines)     # filter out empty lines
    newlines = []                                           # list for out result lines
    for l in nonempty:                                      # iterate lines
        l = l.rstrip()                                      # cut '\n' from the right of each line
        last_idx = len(newlines) - 1                        # index of the last element in the list
        if l.startswith(" "):                               # this lines are lines with your traceback
            newlines[last_idx] += l                         # add to the "normal" log element
        else:                                               # this are "normal" elements
            newlines.append(l)                              # add them to the list

    print("\n".join(newlines))                              # create output and print to stdout

이 출력에는 같은 줄에 "상태"와 "날짜"가 포함되어 있습니다 grep.

normalize.py로그 파일 (예: ) 근처에 이를 배치하고(예 log.txt: ) 실행합니다.python3 normalize.py

답변2

귀하의 질문이 불분명하지만 이것이 귀하가 원하는 것입니까?

$ awk -v tgt='06/07/20' '
    /^\[/ { prt() }
    NF { rec = rec $0 ORS }
    END { prt() }

    function prt() {
        if ( index(rec,tgt) == 2 ) {
            printf "%s", rec
        }
        rec = ""
    }
' file
[06/07/20 20:38:53.911]:loopback ST:                  token-src-name()
[06/07/20 20:38:53.914]:loopback ST:                    Token Value: "DVADER".
[06/07/20 20:38:53.916]:loopback ST:                  token-text(",OU=users,O=data")
[06/07/20 20:38:53.919]:loopback ST:    Arg Value: "CN=DVADER,OU=users,O=data".
[06/07/20 20:38:53.922]:loopback ST:                description("Removed by Termination Process")
[06/07/20 20:38:53.926]:loopback ST:             token-text("Removed by Termination Process")
[06/07/20 20:38:53.929]:loopback ST:                  Arg Value: "Removed by Termination Process".
[06/07/20 20:38:53.943]:loopback ST: DirXML Log Event -------------------
     Driver:   \StarWars\system\Driver Set\User Processor
     Channel:  Subscriber
     Status:   Error
     Message:  Code(-9217) Error in

아니면 이게 아닐까?

$ awk -v tgt='06/07/20' '
    /^\[/ { prt() }
    NF { rec = rec $0 ORS }
    END { prt() }

    function prt() {
        if ( (index(rec,tgt) == 2) && (rec ~ /Status:[[:space:]]+Error/) ) {
            printf "%s", rec
        }
        rec = ""
    }
' file
[06/07/20 20:38:53.943]:loopback ST: DirXML Log Event -------------------
     Driver:   \StarWars\system\Driver Set\User Processor
     Channel:  Subscriber
     Status:   Error
     Message:  Code(-9217) Error in

다음과 같이 쉽게 awk를 호출할 수 있습니다 find.

find . -type f -name '*.log' -exec awk '....' {} +

관련 정보