简体   繁体   English

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

[英]How to log into a file for a python & bottle web server?

Following is my code for server. 以下是我的服务器代码。 I need to add logging to it . 我需要添加日志记录。 This is a very basic rest api server. 这是一个非常基本的rest api服务器。 I have deployed it on Amazon EC2 . 我已经在Amazon EC2上部署了它。 Sometimes due to errors or some other reason the http server shuts down. 有时由于错误或其他原因导致http服务器关闭。 If I am logged on to EC2 i can see the erros while they happen . 如果我登录到EC2,我可以看到它们发生时的错误。 But if I am not monitoring it realtime i don't know what error occurred. 但如果我没有实时监控它,我不知道发生了什么错误。 Therefore I want to add logging which would log the erros in a log file which I can look at later. 因此,我想添加日志记录,这将记录日志文件中的错误,我稍后可以查看。 Please suggest how do i do that. 请建议我该怎么做。

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)

Use the python Logging library. 使用python日志库。 To log exceptions, you'll need to use try and except blocks. 要记录异常,您需要使用tryexcept块。

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

Contents of log.txt : log.txt内容:

ERROR:root:OH NO!

You can add many different loggers that go to different places, have different names, or use different formats. 您可以添加许多不同的记录器,这些记录器可以转到不同的位置,具有不同的名称或使用不同的格式 However, the Python logging library is what you want. 但是,Python日志库就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM