Skip to content

Commit

Permalink
feat: update logger init
Browse files Browse the repository at this point in the history
  • Loading branch information
echonoshy committed Oct 16, 2024
1 parent 8516089 commit 9f2cbad
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 72 deletions.
29 changes: 0 additions & 29 deletions instances/fastapi_server/log/logger-1.py

This file was deleted.

66 changes: 23 additions & 43 deletions instances/fastapi_server/log/logger.py
Original file line number Diff line number Diff line change
@@ -1,54 +1,34 @@
import logging
import logging.handlers
import socket
from loguru import logger
import sys
import os
from datetime import datetime

def setup_logger(log_name, log_dir, log_level="INFO"):
if not os.path.exists(log_dir):
os.makedirs(log_dir)

def setup_logger(log_name, log_directory="logs", log_level="INFO"):
# 获取当前日期和主机名
hostname = socket.gethostname()
current_date = datetime.now().strftime("%Y-%m-%d")
log_file = os.path.join(log_dir, f"{log_name}.log")

# 日志文件路径
log_directory = log_directory
if not os.path.exists(log_directory):
os.makedirs(log_directory)
log_filename = log_name
# 移除所有现有的处理器
logger.remove()

# 创建日志记录器
logger = logging.getLogger()
logger.setLevel(log_level)

# 创建文件处理器,按天进行切分
file_handler = logging.handlers.TimedRotatingFileHandler(
log_filename, when='midnight', interval=1, backupCount=7
# 添加控制台输出
logger.add(
sys.stdout,
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
level=log_level
)
file_handler.setLevel(log_level)

# 创建终端处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)

# 定义日志输出格式
formatter = logging.Formatter(
'[%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d pid:%(process)d] %(message)s'
# 添加文件输出
logger.add(
log_file,
rotation="00:00", # 每天午夜切分
retention="7 days", # 保留7天的日志文件
level=log_level,
format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{line} - {message}",
compression="zip" # 可以选择压缩旧日志
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# 将处理器添加到日志记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

return logger


if __name__ == "__main__":
# 使用日志记录器
logger = setup_logger(log_name="test")

# 记录日志示例
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")
# 创建一个全局的logger实例
global_logger = setup_logger('CQA', 'logs')

0 comments on commit 9f2cbad

Please sign in to comment.