DEBUG = False
if not DEBUG:
import os
os.environ["NTCHAT_LOG"] = "ERROR"
import ntchat_client
ntchat_client.init()
在这些代码中优化修改,打包可执行文件时要有图像界面,显示日志记录,日志文件都已经生成存放在同级目录logs目录中,log目录下分为debug,error,info三个目录目录记录不同情况的日志信息,日志生成方式按照日期格式生成例如2023-04-12.log,要求要实时读取所有的日志信息并显示到图形界面中
import os
import logging
import tkinter as tk
from tkinter import ttk
DEBUG = False
if not DEBUG:
os.environ["NTCHAT_LOG"] = "ERROR"
import ntchat_client
def init_logging():
log_dir = os.path.join(os.getcwd(), "logs")
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[
logging.FileHandler(os.path.join(log_dir, "debug", f"{datetime.datetime.now().date()}.log")),
logging.FileHandler(os.path.join(log_dir, "error", f"{datetime.datetime.now().date()}.log")),
logging.FileHandler(os.path.join(log_dir, "info", f"{datetime.datetime.now().date()}.log")),
]
)
def init_gui():
root = tk.Tk()
root.title("NT Chat Client")
root.geometry("800x600")
log_frame = ttk.Frame(root)
log_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
debug_log = tk.Text(log_frame, state=tk.DISABLED)
debug_log.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
error_log = tk.Text(log_frame, state=tk.DISABLED)
error_log.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
info_log = tk.Text(log_frame, state=tk.DISABLED)
info_log.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
logging.getLogger().addHandler(TextHandler(debug_log, logging.DEBUG))
logging.getLogger().addHandler(TextHandler(error_log, logging.ERROR))
logging.getLogger().addHandler(TextHandler(info_log, logging.INFO))
return root
class TextHandler(logging.Handler):
def init(self, text_widget, level=logging.NOTSET):
super().init(level)
self.text_widget = text_widget
def emit(self, record):
msg = self.format(record)
self.text_widget.configure(state=tk.NORMAL)
self.text_widget.insert(tk.END, msg + '\n')
self.text_widget.configure(state=tk.DISABLED)
self.text_widget.see(tk.END)
def main():
init_logging()
root = init_gui()
ntchat_client.init()
root.mainloop()
if name == "main":
main()