如何在Python和Bottle服务器中记录到文件?

4 投票
1 回答
5700 浏览
提问于 2025-04-17 19:17

以下是我的服务器代码。我需要在其中添加日志记录。这是一个非常基础的REST API服务器。我已经把它部署在亚马逊的EC2上。有时候因为错误或者其他原因,HTTP服务器会关闭。如果我登录到EC2上,我可以看到错误发生时的情况。但是如果我没有实时监控,就不知道发生了什么错误。因此,我想添加日志记录,把错误记录在一个日志文件里,以便我可以稍后查看。请建议我该怎么做。

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)

1 个回答

3

使用Python的日志库来记录信息。如果你想记录错误信息,就需要用到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的日志库就是你需要的工具。

撰写回答