/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.util.StringUtils;

/**
 * <pre>slf4j字符串格式化，类似log.xx的模式</pre>
 *
 * @author 田平 create 2020/9/14 8:31
 */
public class Slf4jUtil {

	public static final int ERROR_DESC_MAX_LENGTH = 255;// 错误信息的最大长度

	public static FormattingTuple format(String msg, Object... args) {
		FormattingTuple formattingTuple = MessageFormatter.arrayFormat(msg, args);
		return formattingTuple;
	}

	public static String formatMsg(String msg, Object... args) {
		return format(msg, args).getMessage();
	}

	public static String formatException(String msg, Object... args) {
		FormattingTuple tuple = format(msg, args);
		if (tuple.getThrowable() != null) {
			return tuple.getMessage() + ",Exception:" + getErrorMsg(tuple.getThrowable());
		} else {
			return tuple.getMessage();
		}
	}

	public static String getErrorMsg(Throwable e) {
		if (e == null) {
			return null;
		}
		if (e instanceof NullPointerException) {
			return "java.lang.NullPointerException";
		}
		String msg = null;
		if (e.getCause() != null) {
			msg = e.getCause().getMessage();
		}
		if (!StringUtils.hasText(msg)) {
			msg = e.getMessage();
		}
		return getMaxDesc(msg);
	}

	public static String getMaxDesc(Object desc) {
		if (desc != null) {
			String s = desc.toString();
			if (s.length() > ERROR_DESC_MAX_LENGTH) {
				return s.substring(0, ERROR_DESC_MAX_LENGTH - 1);
			} else {
				return s;
			}
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(formatException("id:{},name:{}", 1111L, "abc", new RuntimeException("RRRRRRRRRRRR")));
	}

}
