2013-03-16 47 views
4

以下是我的服務器代碼。我需要將日誌記錄添加到它。這是一個非常基本的休息api服務器。我已經在Amazon EC2上部署了它。有時候由於錯誤或其他原因http服務器關閉。如果我登錄到EC2,我可以在發生錯誤時看到它們。但是,如果我沒有實時監控它,我不知道發生了什麼錯誤。因此,我想添加日誌記錄,以便將日誌文件記錄到日誌文件中,以供日後查看。請建議我如何做到這一點。如何登錄到python和瓶子web服務器的文件?

import json 
import uuid # this is for generating unique id 
import datetime 
import bottle 
from bottle import route, run, request, abort 
from pymongo import Connection 

connection = Connection('localhost', 27017) 
db = connection.mydatabase 

@route('/documents', method='PUT') 
def put_document(): 
    data = request.body.readline() 
    if not data: 
     abort(400, 'No data received') 
    entity = json.loads(data) 
    if not entity.has_key('_id'): 
     abort(400, 'No _id specified') 
    try: 
     db['documents'].save(entity) 
    except ValidationError as ve: 
     abort(400, str(ve)) 

@route('/documents/:id', method='GET') 
def get_document(id): 
    entity = db['documents'].find_one({'_id':id}) 
    if not entity: 
     abort(404, 'No document with id %s' % id) 
    return entity 

@route('/startSession', method = 'GET') 
def startSession(): 
    #here we need to create a unique id and store it in the database. 
    date = str(datetime.datetime.utcnow()); 
    id = str(uuid.uuid4()) 
    reply = {'date' : date, 
       'user_id': id 
       } 

    response = {'date' : date, 
     'user_id': id 
     } 
    return_id = db['users'].save(reply) 
#print 'the id returned is', return_id 
#print 'the changed reply is',reply 
#print 'the NON changed respponse is ',response 
    return json.dumps(response) 

@route('/set_bus_location', method = 'PUT') 
def set_bus_location(): 
    data = request.body.readline() 
    print 'data is ',data 
    if not data: 
     abort(400, 'No data received') 
    entity = json.loads(data) 
    db['bus_locations'].save(entity) 

run(host='0.0.0.0', port=8080) 

回答

3

使用python Logging庫。要記錄異常,您需要使用tryexcept塊。

import logging 
logging.basicConfig(filename='log.txt', format=logging.BASIC_FORMAT) 
logging.error('OH NO!') 
try: 
    raise Exception('Foo') 
except: 
    logging.exception("Oops:") 

內容的log.txt

ERROR:root:OH NO! 

您可以添加許多不同的採伐是去不同的地方,有不同的名稱,或使用不同的格式。但是,Python日誌記錄庫就是你想要的。

+0

我需要的是我通常在手動監視服務器時看到的錯誤的堆棧跟蹤。以便我知道錯誤發生的位置。 所以對於那個應該我嘗試趕上每個塊我認爲會有錯誤,然後使用logging.error認爲你提到? – 2013-03-16 04:48:20

+0

是的。我已更新我的示例。 – 2013-03-16 05:05:36