Python日志端口514 folder/yyyy/mm/dd

2024-10-03 19:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想用python脚本记录514udp端口。日志地址不会随日期更改而更改。我要保存所有日志日志。我想每天把同名的日志记录在不同的文件夹里。你知道吗

#!/usr/bin/env python
import os, stat
import datetime
import logging
import SocketServer

HOST, PORT = "0.0.0.0", 514
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = bytes.decode(self.request[0].strip())
        socket = self.request[1]
        today = datetime.datetime.now()
        year = today.strftime("%Y")
        month=today.strftime("%m")
        day=today.strftime("%d")
        file_path = "/listen/"  + year +"/" + month + "/" + day 
        file= file_path + "/test.log"       
        if(not os.path.exists(file_path)):
            os.makedirs(file_path)
        logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=file, filemode='a')
        logging.info(str(data))

if __name__ == "__main__":
    try:
        server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print ("Crtl+C Pressed. Shutting down.")

Tags: pathimportselfhostdatatodaydatetimeos
2条回答

换行

logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=file, filemode=('a' if os.path.exists(file_path) else 'w'))

logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=file, filemode=('a' if os.path.exists(file_path) else 'w'))

最终代码

#!/usr/bin/env python
import os, stat
import datetime
import logging
import SocketServer

HOST, PORT = "0.0.0.0", 514
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = bytes.decode(self.request[0].strip())
        socket = self.request[1]
        today = datetime.datetime.now()
        year = today.strftime("%Y")
        month=today.strftime("%m")
        day=today.strftime("%d")
        file_path = "/listen/"  + year +"/" + month + "/" + day 
        file= file_path + "/test.log"       
        if(not os.path.exists(file_path)):
            os.makedirs(file_path)
        logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=file, filemode=('a' if os.path.exists(file_path) else 'w'))
        logging.info(str(data))

if __name__ == "__main__":
    try:
        server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print ("Crtl+C Pressed. Shutting down.")

我不能真正测试这个,但我认为问题可能是因为您的代码总是在日志文件中附加数据。所以试着这样做:

class SyslogUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = bytes.decode(self.request[0].strip())
        socket = self.request[1]

        today = datetime.datetime.now()
        year = today.strftime("%Y")
        month = today.strftime("%m")
        day = today.strftime("%d")
        file_path = "/listen/" + year + "/" + month + "/" + day
        file = file_path + "/test.log"
        if os.path.exists(file_path):
            filemode = 'a'  # Append to existing file.
        else:
            os.makedirs(file_path)
            filemode = 'w'  # Write to new file.

        logging.basicConfig(level=logging.INFO, format='%(message)s',
                            datefmt='', filename=file, filemode=filemode)
        logging.info(str(data))

相关问题 更多 >