如何将带有时间戳的日志记录添加到Raspberry Pi的Python TCP Server中 [英] How to add logging to a file with timestamps to a Python TCP Server for Raspberry Pi

查看:78
本文介绍了如何将带有时间戳的日志记录添加到Raspberry Pi的Python TCP Server中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点为我的项目而苦恼&我非常需要帮助.我需要一个简单的TCP服务器python代码,该代码具有诸如日志记录&可以用于Raspberry Pi的时间戳.这是我的最后一年"项目.

我看了一些示例,但是由于我在编写自己的脚本/代码方面没有太多经验,因此我不太确定该怎么做.如果有人可以在正确的方向上指导我,并提供解释和一些示例,我将不胜感激.

我正在使用HERCULES SETUP UTILITY,它充当我的TCP客户端,而我的visual studio python代码充当一个SERVER.我的SERVER现在可以接收到客户端发送的数据了,我似乎无法添加一个日志文件来将发送的数据保存到文本文件中.有人可以向我展示一些示例或参考吗?您的帮助将意味着很多.到目前为止,这是我的代码:

from socket import *
import thread

BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
    return 'Sent by client'

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF) # receive data(buffer).
        print 'data:' + repr(data)   #Server to recieve data sent by client.
        if not data: break           #If connection is closed by client, server will        break and stop recieving data.
        print 'sent:' + repr(response('')) # respond by saying "Sent By Client". 



if __name__=='__main__':
    ADDR = (HOST, PORT) #Define Addr
    serversock = socket(AF_INET, SOCK_STREAM) 
    serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and     port number)
    serversock.listen(0)
    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr #show its connected to which addr
        thread.start_new_thread(handler, (clientsock, addr ))

解决方案

要将日志记录添加到带有时间戳的文件中,可以使用logging模块:

import logging

logging.basicConfig(level=logging.INFO, 
                    filename='myserver.log', # log to this file
                    format='%(asctime)s %(message)s') # include timestamp
logging.info("some message")

如果您运行代码;您应该在myserver.log中看到(+/-时区和当前时间):

2013-12-24 09:20:17,739 some message

这是一个完整的TCP服务器示例,它使用"Sent by Client: "短语为从客户端收到的每行内容加上前缀并将其发送回去:

#!/usr/bin/env python
import logging
import sys
from SocketServer import ThreadingTCPServer, StreamRequestHandler

info = logging.getLogger(__name__).info

class EchoLineHandler(StreamRequestHandler):
    def handle(self):
        info("handling request from %s", self.client_address)
        # prepend each line (b'\n') and send it back
        for line in self.rfile:
            self.wfile.write(b"Sent by Client: ") # assume ascii-based encoding
            self.wfile.write(line)
        info("done %s", self.client_address)

def test(ServerClass=ThreadingTCPServer, HandlerClass=EchoLineHandler):
    # configure logging
    logging.basicConfig(level=logging.INFO,
                        filename='server.log', # log to this file
                        format='%(asctime)s %(message)s') # include timestamp

    # parse command line arguments
    host, port = 'localhost', 8826
    if len(sys.argv) > 1:
        host_, separator, port_ = sys.argv[1].rpartition(":")
        port = int(port_)
        if separator: # if ":" in sys.argv[1]
            host = host_ # accept any host, including empty

    # listen for connections
    server = ServerClass((host, port), HandlerClass)
    info("Serving on %s port %s", *server.server_address)
    try:
        server.serve_forever()
    finally:
        info("quit.")

if __name__=="__main__":
    test()

如果代码保存在echo_line_server.py中,则要运行服务器:

$ python -mecho_line_server localhost:8826 & tail -F server.log
2013-12-24 17:09:38,089 Serving on 127.0.0.1 port 8826

运行客户端:

$ echo abc | nc localhost 8826
Sent by Client: abc

I am kinda stuck for my project & I desperately need help. I need a simple TCP server python code that has features like logging & time stamp which I could use for my Raspberry Pi. Its for my Final Year Project.

I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not very sure how to go about doing this. I would appreciate if someone could guide me in the right direction with explanation and some examples if possible.

I am using HERCULES SETUP UTILITY , which acts as my TCP client, while my visual studio python code acts as a SERVER. My SERVER can receive the data which is sent by the client by now , I just can't seem to add in a logging file which can save the sent data into text file.Can someone please show me some examples or referance please? Your help would mean alot. This is my code so far :

from socket import *
import thread

BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
    return 'Sent by client'

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF) # receive data(buffer).
        print 'data:' + repr(data)   #Server to recieve data sent by client.
        if not data: break           #If connection is closed by client, server will        break and stop recieving data.
        print 'sent:' + repr(response('')) # respond by saying "Sent By Client". 



if __name__=='__main__':
    ADDR = (HOST, PORT) #Define Addr
    serversock = socket(AF_INET, SOCK_STREAM) 
    serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and     port number)
    serversock.listen(0)
    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr #show its connected to which addr
        thread.start_new_thread(handler, (clientsock, addr ))

解决方案

To add logging to a file with timestamps, you could use logging module:

import logging

logging.basicConfig(level=logging.INFO, 
                    filename='myserver.log', # log to this file
                    format='%(asctime)s %(message)s') # include timestamp
logging.info("some message")

If you run the code; you should see in myserver.log (+/- your timezone and current time):

2013-12-24 09:20:17,739 some message

Here's a complete example of TCP server that prepends each received line from a client with "Sent by Client: " phrase and sends it back:

#!/usr/bin/env python
import logging
import sys
from SocketServer import ThreadingTCPServer, StreamRequestHandler

info = logging.getLogger(__name__).info

class EchoLineHandler(StreamRequestHandler):
    def handle(self):
        info("handling request from %s", self.client_address)
        # prepend each line (b'\n') and send it back
        for line in self.rfile:
            self.wfile.write(b"Sent by Client: ") # assume ascii-based encoding
            self.wfile.write(line)
        info("done %s", self.client_address)

def test(ServerClass=ThreadingTCPServer, HandlerClass=EchoLineHandler):
    # configure logging
    logging.basicConfig(level=logging.INFO,
                        filename='server.log', # log to this file
                        format='%(asctime)s %(message)s') # include timestamp

    # parse command line arguments
    host, port = 'localhost', 8826
    if len(sys.argv) > 1:
        host_, separator, port_ = sys.argv[1].rpartition(":")
        port = int(port_)
        if separator: # if ":" in sys.argv[1]
            host = host_ # accept any host, including empty

    # listen for connections
    server = ServerClass((host, port), HandlerClass)
    info("Serving on %s port %s", *server.server_address)
    try:
        server.serve_forever()
    finally:
        info("quit.")

if __name__=="__main__":
    test()

To run the server if the code is save in echo_line_server.py:

$ python -mecho_line_server localhost:8826 & tail -F server.log
2013-12-24 17:09:38,089 Serving on 127.0.0.1 port 8826

To run a client:

$ echo abc | nc localhost 8826
Sent by Client: abc

这篇关于如何将带有时间戳的日志记录添加到Raspberry Pi的Python TCP Server中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆