# -*- coding: utf-8 -*-
import sys
from os import makedirs
from os.path import join, exists
from loguru import logger
from util.RWUtils import getConfigs


# 初始化日志配置
def init_log(base_dir, env):
    log_config = getConfigs(join(base_dir, 'config/logger/dsp_%s_logger.yml' % env))
    # 判断日志文件是否存在，不存在创建
    base_path = join(base_dir, log_config.get("base_path"))
    if not exists(base_path):
        makedirs(base_path)
    # 移除日志设置
    logger.remove(handler_id=None)
    # 打印日志到文件
    if bool(log_config.get("enable_file_log")):
        logger.add(join(base_path, log_config.get("log_name")),
                   rotation=log_config.get("rotation"),
                   retention=log_config.get("retention"),
                   format=log_config.get("log_fmt"),
                   level=log_config.get("level"),
                   enqueue=True,
                   encoding=log_config.get("encoding"))
    # 控制台输出
    if bool(log_config.get("enable_stderr")):
        logger.add(sys.stderr,
                   format=log_config.get("log_fmt"),
                   level=log_config.get("level"),
                   enqueue=True)
