Files
macm1new/logger.py

94 lines
3.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import logging
import os
import sys
from datetime import datetime
class PrefixFormatter(logging.Formatter):
"""自定义格式化器,为 DEBUG 级别日志添加开源项目前缀"""
def format(self, record):
if record.levelno == 10: # DEBUG 级别的数值是 10
record.msg = f"[听泉助手https://cursorapi.nosqli.com] {record.msg}"
return super().format(record)
def setup_logger():
"""设置日志系统"""
# 获取用户的应用程序支持目录
if sys.platform == 'darwin':
app_support_dir = os.path.expanduser('~/Library/Application Support/听泉Cursor助手')
else:
app_support_dir = os.path.expanduser('~/.听泉Cursor助手')
# 创建应用程序支持目录
os.makedirs(app_support_dir, exist_ok=True)
# 创建日志目录
log_dir = os.path.join(app_support_dir, 'logs')
os.makedirs(log_dir, exist_ok=True)
# 设置日志文件路径
log_file = os.path.join(log_dir, f"{datetime.now().strftime('%Y-%m-%d')}.log")
# 创建日志记录器
logger = logging.getLogger('CursorHelper')
logger.setLevel(logging.WARNING) # 修改为WARNING级别
# 创建文件处理器
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.WARNING) # 文件处理器也设置为WARNING级别
file_handler.setFormatter(PrefixFormatter('%(asctime)s - %(levelname)s - %(message)s'))
# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING) # 控制台也设置为WARNING级别
console_handler.setFormatter(PrefixFormatter('%(levelname)s: %(message)s'))
# 添加处理器到日志记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# 记录初始化信息
logger.info('日志系统初始化成功')
logger.info(f'日志文件路径: {log_file}')
logger.debug('调试日志已启用')
return logger
# 导出日志记录器
logging = setup_logger()
def main_task():
"""
Main task execution function. Simulates a workflow and handles errors.
"""
try:
logging.info("Starting the main task...")
# Simulated task and error condition
if some_condition():
raise ValueError("Simulated error occurred.")
logging.info("Main task completed successfully.")
except ValueError as ve:
logging.error(f"ValueError occurred: {ve}", exc_info=True)
except Exception as e:
logging.error(f"Unexpected error occurred: {e}", exc_info=True)
finally:
logging.info("Task execution finished.")
def some_condition():
"""
Simulates an error condition. Returns True to trigger an error.
Replace this logic with actual task conditions.
"""
return True
if __name__ == "__main__":
# Application workflow
logging.info("Application started.")
main_task()
logging.info("Application exited.")