package com.ruoyi.cron.runner;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.cron.TaskLog;
import com.ruoyi.cron.document.CronTaskLog;
import com.ruoyi.cron.event.CronTaskLogEvent;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TaskLogImpl implements TaskLog {

  public static final ThreadLocal<CronTaskLog> logHolder = new ThreadLocal<>();

  @Override
  public void log(String msg) {
    if (logHolder.get() == null) {
      return;
    }
    String ex = DateUtil.format(new Date(), "HH:mm:ss.SSS ")+ Thread.currentThread().getName()+ "\t : " + msg;
    if (StrUtil.isBlank(logHolder.get().getEx())) {
      logHolder.get().setEx(ex);
    } else {
      logHolder.get().setEx(logHolder.get().getEx() + "\n" + ex);
    }
    SpringUtils.publishEvent(new CronTaskLogEvent(logHolder.get().getTaskId(),logHolder.get().getGroupId(),ex));
  }
}
