我对编写和/或理解python还是很陌生,但是非常上瘾,想完成这个项目。我能够从多种不同的资源中整理这段python代码,除了一些项目外,它几乎可以完成我需要做的所有事情。
下面是对该代码的基本理解;
当我启动树莓派时,此代码将启动。该代码使用USB FTDI电缆从微控制器驱动的设备中收集串行数据。然后将数据存储到USB驱动器,并在日志达到特定大小时对其进行压缩。
我希望添加的内容;
我希望逐行收集串行数据,以添加更新的时间戳(日期和时间)。我能够解决这个问题。从我的termainl窗口中查看数据和时间时,会显示这些数据和时间,但是相同的数据没有写入日志文件。
我想在文件压缩后立即在文件名上添加时间戳,以便我知道什么日志记录到了那天。
如果有人可以指导我,或者这是简单的解决方法,请提供帮助。
非常感谢!
亚当
[CODESTARTS]
#!/usr/bin/env python
# Import all the needed modules
import logging.handlers
import sys
import time
import gzip
import os
import shutil
import random
import string
import serial
import logging
__version__ = 1.0
__descr__ = "This logic is written keeping in mind UNIX/LINUX/OSX platforms only"
# Create a new class that inherits from RotatingFileHandler. This is where we add the new feature to compress the logs
class CompressedRotatingFileHandler(logging.handlers.RotatingFileHandler):
def doRollover(self):
"""
Do a rollover, as described in __init__().
"""
if self.stream:
self.stream.close()
if self.backupCount > 0:
for i in range(self.backupCount - 1, 0, -1):
sfn = "%s.%d.gz" % (self.baseFilename, i)
dfn = "%s.%d.gz" % (self.baseFilename, i + 1)
if os.path.exists(sfn):
# print "%s -> %s" % (sfn, dfn)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
dfn = self.baseFilename + ".1.gz"
if os.path.exists(dfn):
os.remove(dfn)
# These two lines below are the only new lines. I commented out the os.rename(self.baseFilename, dfn) and
# replaced it with these two lines.
with open(self.baseFilename, 'rb') as f_in, gzip.open(dfn, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# os.rename(self.baseFilename, dfn)
# print "%s -> %s" % (self.baseFilename, dfn)
self.mode = 'w'
self.stream = self._open()
# Specify which file will be used for our logs
log_filename = "/mnt/usbstick/DeviceDebugger/logs/ICORE_log.txt"
#Adding format by editing "basicConfig"
Format = logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s %(name)-5s %(levelname)-8s %(message)s')
# Create a logger instance and set the facility level
my_logger = logging.getLogger()
my_logger.setLevel(logging.DEBUG)
# Create a handler using our new class that rotates and compresses {maxbytes and backup count are configurable]
file_handler = CompressedRotatingFileHandler(filename=log_filename, maxBytes=90000, backupCount=10)
# Add all the handlers to the logging instance
my_logger.addHandler(file_handler)
#serial usb dev port and baud rate speed
ser1 = serial.Serial('/dev/ttyUSB0',38400)
while True:
#collect logs that are coming from ser1 to my_logger
my_logger.debug(ser1.readline())
[这是如何在已保存的日志文件中显示数据的示例] iAMG-4000 2019-02-18T11:38:41
CWebServiceTimeout线程已启动339D380
[这是如何在终端窗口上显示数据的示例] 2019-02-18 11:38:43,962根调试 iAMG-4000 2019 -02-18T11:38:41
2019-02-18 11:39:00,300根调试 CWebServiceTimeout线程已启动339D380