【发布时间】:2018-03-03 12:39:00
【问题描述】:
我有 catalina 日志:
oct 21, 2016 12:32:13 AM org.wso2.carbon.identity.sso.agent.saml.SSOAgentHttpSessionListener sessionCreated
WARNING: HTTP Session created without LoggedInSessionBean
oct 21, 2016 3:03:20 AM com.sun.jersey.spi.container.ContainerResponse logException
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException
at ais.api.rest.rdss.Resource.lookAT(Resource.java:22)
at sun.reflect.GeneratedMethodAccessor3019.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
我尝试在 python 中解析它。我的问题是我不知道日志中有多少行。最少为 2 行。我尝试从文件中读取,当第一行以 j、m、s、o 等开头时,这意味着它是日志的第一行,因为这是月份的第一个字母。但我不知道如何继续。当我停止阅读这些台词时?下一行何时以这些字母之一开头?但是我该怎么做呢?
import datetime
import re
SPACE = r'\s'
TIME = r'(?P<time>.*?M)'
PATH = r'(?P<path>.*?\S)'
METHOD = r'(?P<method>.*?\S)'
REQUEST = r'(?P<request>.*)'
TYPE = r'(?P<type>.*?\:)'
REGEX = TIME+SPACE+PATH+SPACE+METHOD+SPACE+TYPE+SPACE+REQUEST
def parser(log_line):
match = re.search(REGEX,log_line)
return ( (match.group('time'),
match.group('path'),
match.group('method'),
match.group('type'),
match.group('request')
)
)
db = MySQLdb.connect(host="localhost", user="myuser", passwd="mypsswd", db="Database")
with db:
cursor = db.cursor()
with open("Mylog.log","rw") as f:
for line in f:
if (line.startswith('j')) or (line.startswith('f')) or (line.startswith('m')) or (line.startswith('a')) or (line.startswith('s')) or (line.startswith('o')) or (line.startswith('n')) or (line.startswith('d')) :
logLine = line
result = parser(logLine)
sql = ("INSERT INTO ..... ")
data = (result[0])
cursor.execute(sql, data)
f.close()
db.close()
我的最佳想法是一次只阅读两行。但这意味着丢弃所有其他数据。一定有更好的办法。
我想读这样的行:
1.line - oct 21, 2016 12:32:13 AM org.wso2.carbon.identity.sso.agent.saml.SSOAgentHttpSessionListener sessionCreated WARNING: HTTP Session created without LoggedInSessionBean
2.line - oct 21, 2016 3:03:20 AM com.sun.jersey.spi.container.ContainerResponse logException SEVERE: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException at ais.api.rest.rdss.Resource.lookAT(Resource.java:22) at sun.reflect.GeneratedMethodAccessor3019.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl java:43)
3.line - oct 21, 2016 12:32:13 AM org.wso2.carbon.identity.sso.agent.saml.SSOAgentHttpSessionListener sessionCreated WARNING: HTTP Session created without LoggedInSessionBean
所以我想在行以 datetime 开头时开始阅读(这没问题)。问题是我想在下一行以日期时间开始时停止阅读。
【问题讨论】:
-
Caroline,这是否意味着,在这种情况下,您要捕获以 'javax.ws.rs.WebApplicationException' 开头的四行?
-
是的。但这只是一种情况。如果我将有另一个日志,可以有更多的行。例如它可以是 2 行(一个日志)+ 7 行(2 个日志)+ 2 行(3 个日志)等。
-
您是否希望行开始缩进行的集合,然后是所有缩进行?
-
我想在行以 datetime 开头时开始阅读(这没问题)。问题是我想在下一行以日期时间开始时停止阅读。我编辑问题。
标签: python regex parsing catalina