Created
May 19, 2020 07:59
-
-
Save MerleLiuKun/b022e6c3c1772afad624269f81cf5142 to your computer and use it in GitHub Desktop.
Nginx log 的解析
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
@dataclass | |
class LogInfo: | |
req: str | |
body: str | |
ua: str | |
def handle_line_by_re(line) -> LogInfo: | |
""" | |
follow by http://desert3.iteye.com/blog/1001568 | |
""" | |
ip_p = r"?P<ip>[\d.]*" | |
time_p = r"?P<time>\[[^\[\]]*\]" | |
request_p = r"?P<request>\"[^\"]*\"" | |
status_p = r"?P<status>\d+" | |
body_bytes_p = r"?P<bodyByteSent>\d+" | |
body_p = r"?P<pBody>.*" # If have request body. | |
refer_p = r"?P<refer>\"[^\"]*\"" | |
user_agent_p = r"?P<userAgent>\"[^\"]*\"" | |
log_pattern = re.compile( | |
r"({ip}) - - ({time}) ({req}) ({status}) ({body}) ({body_p}) ({refer}) ({ua})".format( | |
ip=ip_p, time=time_p, req=request_p, status=status_p, | |
body=body_bytes_p, body_p=body_p, refer=refer_p, ua=user_agent_p) | |
) | |
result = log_pattern.match(line) | |
if result: | |
log_line = LogInfo( | |
req=result.group('request'), | |
body=result.group("pBody"), | |
ua=result.group('userAgent') | |
) | |
return log_line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment