import logging
from aliyun.log import LogClient, PutLogsRequest, LogItem


from decouple import config
# 配置阿里云日志服务的参数
LOG_PROJECT = config('ALIYUN_LOG_PROJECT')
LOG_STORE = config('ALIYUN_LOG_STORE')
ENDPOINT = config('ALIYUN_LOG_ENDPOINT')
ACCESS_KEY_ID = config('ALIYUN_LOG_ACCESS_KEY_ID')
ACCESS_KEY_SECRET = config('ALIYUN_LOG_ACCESS_KEY_SECRET')

# 初始化阿里云日志客户端
client = LogClient(endpoint=ENDPOINT, accessKeyId=ACCESS_KEY_ID, accessKey=ACCESS_KEY_SECRET)

class AliyunLogHandler(logging.Handler):
    def emit(self, record):
        log_item = LogItem()
        log_item.set_time(record.created)
        log_item.set_contents([
            ('level', record.levelname),
            ('levelno', str(record.levelno)),
            ('message', record.getMessage()),
            ('pathname', record.pathname),
            ('filename', record.filename),
            ('funcName', record.funcName),
            ('lineno', str(record.lineno)),
        ])
        request = PutLogsRequest(LOG_PROJECT, LOG_STORE, '', '', [log_item])
        client.put_logs(request)

def setup_logging():
    logger = logging.getLogger()
    handler = AliyunLogHandler()
    handler.setLevel(logging.INFO)
    logger.addHandler(handler)
