python - 如何登录 python 和 bottle web 服务器的文件?

标签 python logging webserver bottle

以下是我的服务器代码。我需要向它添加日志记录。这是一个非常基本的 rest api 服务器。我已经将它部署在 Amazon 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)

最佳答案

使用 python 日志库。要记录异常,您需要使用 tryexcept block 。

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 日志记录库正是您想要的。

关于python - 如何登录 python 和 bottle web 服务器的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444695/

相关文章:

python - 找不到包 "libapache2-mod-proxy-html"Ubuntu 16.04

python - 如何在Tensorflow 2.0中进行Cohen Kappa二次损失?

python - Cython:嵌套 typedef 的解决方法

java - 在文件中有效地存储易于解析的数据?

java - Log4j 记录到文件

java - 多线程 Java Web 服务器 - java.net.SocketTimeoutException

python - 带有 matplotlib 的 axvline 和 axhline 中的线条样式和线条颜色的 kwargs

ruby-on-rails - 调试 Delayed_Jobs

webserver - TortoiseHg Web 服务器说它已停止,尽管它仍在运行