---
# System prepended metadata

title: 好用的LogUtils

---

# 好用的LogUtils
```java=\
package com.camiol.utils;


import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Log Forging 漏洞校正
 */

public class LogUtils {

	private static final Logger logger = LogManager.getLogger(LogUtils.class);
	
	public static String validLog(String log) {	
		try {
			if (log == null) {
				return "";
			}
			// 過濾特殊符號
			String filter = log.replaceAll("%0d", "_").replaceAll("\r", "_").replaceAll("%0a", "_").replaceAll("\n", "_");
			// 轉義特殊符號
			String escaped = StringEscapeUtils.escapeJava(filter);
			
			return escaped;
		} catch (IllegalArgumentException  e) {
			logger.error("e: {}", e);
			return null;
		}
	}
	
	
	public static String validLog(String log, Object... arguments) {
		if (log == null) {
		    return null;
		}

		if (arguments != null && arguments.length > 0) {
		    try {
		        for (int i=0; i < arguments.length; i++) {
		            if (arguments[i] != null) {
		                log = log.replaceAll("\\{\\}", arguments[i] + "");
		            }
		        }
		    } catch (PatternSyntaxException e) {
		        logger.error("e: {}", e);
		        return null;
		    } catch (Exception e) {
		        logger.error("e: {}", e);
		        return null;
		    }
		}

		return log;
	}

}

```