一、问题描述
velocity运行时会生成velocity.log文件用于记录运行日志但是此文件默认会保存在项目根目录下,不便与管理,希望将其生成到指定目录下。本文是将其配置到根目录下的log文件夹中
二、解决方案
在获取模板引擎初始化是传入相关配置,核心代码如下
Properties properties = new Properties(); properties.setProperty(Velocity.RUNTIME_LOG, "logs/velocity.log");
相关代码如下
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import static com.ldyx.constant.Constant.*;
/**
* @Description Velocity工具包
* @ClassName VelocityUtil
* @Date 2023/3/19
* @Version V1.0
* @Package com.ldyx
**/
public class VelocityUtil {
private static String runTimeLog = "logs/velocity.log";
public static void setRunTimeLog(String runTimeLog) {
VelocityUtil.runTimeLog = runTimeLog;
}
/**
* 生成模板
*
* @param templateName classpath下的模板路径
* @return
*/
public static Template getTemplate(String templateName) {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
Properties properties = new Properties();
properties.setProperty(Velocity.ENCODING_DEFAULT, UTF_8);
properties.setProperty(Velocity.INPUT_ENCODING, UTF_8);
properties.setProperty(Velocity.OUTPUT_ENCODING, UTF_8);
properties.setProperty(Velocity.RUNTIME_LOG, runTimeLog);
velocityEngine.init(properties);
return velocityEngine.getTemplate(templateName);
}
/**
* 生成文件
*
* @param template 模板
* @param velocityContext 文件参数
* @param filePath 文件输出全路径
*/
public static void generate(Template template, VelocityContext velocityContext, String filePath) {
PrintWriter writer = null;
try {
writer = new PrintWriter(filePath, UTF_8);
template.merge(velocityContext, writer);
writer.flush();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
}