You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.1 KiB
38 lines
1.1 KiB
import logging
|
|
import os
|
|
from logging.handlers import RotatingFileHandler
|
|
|
|
|
|
def log_init():
|
|
# 确保logs目录存在
|
|
if not os.path.exists('logs'):
|
|
os.makedirs('logs')
|
|
# 创建格式器
|
|
formatter = logging.Formatter(
|
|
fmt='%(asctime)s.%(msecs)03d %(name)s %(levelname)s %(module)s.%(funcName)s %(message)s',
|
|
datefmt='%Y-%m-%d %H:%M:%S'
|
|
)
|
|
|
|
# 配置根日志记录器
|
|
root_logger = logging.getLogger()
|
|
# 清除现有的处理器,避免重复添加
|
|
root_logger.handlers.clear()
|
|
|
|
# 创建文件处理器
|
|
file_handler = RotatingFileHandler(
|
|
filename='logs/app.log',
|
|
maxBytes=1024*1024, # 1MB
|
|
backupCount=10,
|
|
encoding='utf-8' # 指定编码
|
|
)
|
|
file_handler.setLevel(logging.INFO)
|
|
file_handler.setFormatter(formatter)
|
|
|
|
# 创建控制台处理器
|
|
console_handler = logging.StreamHandler()
|
|
console_handler.setLevel(logging.INFO)
|
|
console_handler.setFormatter(formatter)
|
|
|
|
root_logger.setLevel(logging.INFO)
|
|
root_logger.addHandler(file_handler)
|
|
root_logger.addHandler(console_handler)
|