自定义python日志 存入本地.txt记事本文件方法
自定义python日志
import datetime
import json
def tolog(text):
try:
# 判断 text 是否为列表或字典类型
if isinstance(text, (list, dict)):
# 将列表或字典转换为字符串
text = json.dumps(text, ensure_ascii=False, indent=4)
# 获取当前日期和时间
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 构建要写入的完整内容,包含日期、文本和分隔线
new_content = f"{current_time}\n{text}\n--------------------------------\n"
# 读取文件原有内容
try:
with open('diylog.txt', 'r', encoding='utf-8') as file:
old_content = file.read()
except FileNotFoundError:
old_content = ''
# 以写入模式打开文件,将新内容写在前面,原有内容追加到后面
with open('diylog.txt', 'w', encoding='utf-8') as file:
file.write(new_content)
file.write(old_content)
print("文本已成功写入 diylog.txt 文件。")
except Exception as e:
print(f"写入文件时出现错误: {e}")读取日志:
@app.route('/getlog')
def get_log():
try:
# 检查文件是否存在
if os.path.exists('diylog.txt'):
# 以只读模式打开文件
with open('diylog.txt', 'r', encoding='utf-8') as file:
# 读取文件内容
log_content = file.read()
# 返回文件内容作为响应
return Response(log_content, content_type='text/plain; charset=utf-8')
else:
return "文件 diylog.txt 不存在。", 404
except Exception as e:
return f"读取文件时出现错误: {e}", 500