2014-07-14 51 views
1

我試圖設置正則表達式來從自定義服務器日誌中獲取變量。通過命名正則表達式的每個部分來獲取變量。這裏有一個例子:解析服務器追蹤的正則表達式

/^(?<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) 

所有我關心的是抓住各種成分在第一行,將它們放入變量,然後把整個追蹤中的變量。

我意識到這可能是一個問題太具體,但我覺得一個基本的正則表達式運行會覆蓋這將有利於許多人試圖解析服務器日誌。

+0

這是什麼變數? – Braj

+0

顯示您的代碼。 – furas

回答

2

你的意思是沿着這些線?

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

http://regex101.com/r/zS1fN5/1

作品爲給定的例子,但要看是什麼怪癖和異常有可能是該日誌格式。