解析服务器回溯的正则表达式

时间:2014-07-14 23:09:20

标签: python regex

我正在尝试设置一个正则表达式来从自定义服务器日志中获取变量。通过命名正则表达式的每个部分来获取变量。这是一个例子:

/^(?<time>[^ ]+) (?<host>[^ ]+) (?<process>[^:]+): (?<message>((?<key>[^ :]+)[ :])? ?((to|from)=<(?<address>[^>]+)>)?.*)$/ 

我想为自定义格式做同样的事情。格式如下:

[11/Jul/2014 19:35:38] ERROR [django.request.tastypie:273] Internal Server Error: /v1/notes/
Traceback (most recent call last):
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 195, in wrapper
    response = callback(request, *args, **kwargs)
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 426, in dispatch_list
    return self.dispatch('list', request, **kwargs)
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 458, in dispatch
    response = method(request, **kwargs)
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 1320, in post_list
    updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 2084, in obj_create
    return self.save(bundle)
  File "/opt/client-api/venv/local/lib/python2.7/site-packages/tastypie/resources.py", line 2230, in save
    bundle.obj.save()
  File "./notification/models.py", line 193, in save
    handler.handle_notification()
  File "./notification/handler.py", line 31, in handle
    getattr(self, '_set_{}_payload'.format(preference))()
  File "./notification/notification_handler.py", line 89, in _set_payload
    raise Exception(error)

我所关心的只是抓住第一行的各个组件,将它们放入变量中,然后将整个回溯放入变量中。

我意识到这可能是一个问题的过于具体,但我觉得这将覆盖这个正则表达式的基本运行对许多人试图解析服务器日志是有益的。

1 个答案:

答案 0 :(得分:2)

你的意思是这些东西?

\[(?P<timestamp>.*?)\] (?P<level>\w+) \[(?P<location>.*?)\] (?P<message>.*?)\n(?P<details>.*?)(?=\n\[|$)

请参阅http://regex101.com/r/zS1fN5/1

适用于给定的示例,但取决于此日志格式可能存在的怪癖和异常。