log 获取的时间是UTC时间,采用CST(中国标准时间)

This commit is contained in:
sityliu 2024-05-05 23:57:53 +08:00
parent 97366a5891
commit 384b33c825
3 changed files with 28 additions and 4 deletions

View File

@ -62,8 +62,7 @@ def run_local_status(mqtt_client):
return_data = local_status.status_main()
save_log_info.info(return_data)
data_up.mqtt_up(mqtt_client, Config.LOCAL_STATUS_UP, return_data)
time.sleep(1)
time.sleep(10)
if __name__ == '__main__':

View File

@ -1,4 +1,5 @@
-i https://pypi.tuna.tsinghua.edu.cn/simple
pyserial~=3.5
paho-mqtt
psutil
psutil
pytz

View File

@ -1,5 +1,28 @@
import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime
import pytz
class CSTFormatter(logging.Formatter):
"""自定义日志时间格式器采用CST中国标准时间)"""
def converter(self, timestamp):
"""转换时间戳为CST时区的datetime对象"""
utc_time = datetime.utcfromtimestamp(timestamp)
cst_tz = pytz.timezone('Asia/Shanghai') # CST实际上指的是中国标准时间这里使用'Asia/Shanghai'
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(cst_tz)
return local_time
def formatTime(self, record, datefmt=None):
"""格式化时间"""
ct_time = self.converter(record.created)
if datefmt:
s = ct_time.strftime(datefmt)
else:
t = ct_time.strftime(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s
class SaveLogger:
@ -7,7 +30,8 @@ class SaveLogger:
self.logger = logging.getLogger(name)
self.logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = CSTFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# DEBUG:
console_handler = logging.StreamHandler()