我想写一些包含执行者信息的信息日志。假设我有这个SaveUser函数:
question <- "Which hormone concentrations are altered in patients with the Allan Herndon Dudley syndrome?"
searchMM <- function(x, remDr){
remDr$findElement("css","textarea")$clearElement()
remDr$findElement("css","textarea")$sendKeysToElement(list(x))
remDr$findElement("css", "#note > input[type='button']:nth-child(12)")$clickElement()
concept <- remDr$findElement("css","table:nth-child(31) pre")$getElementText()
remDr$goBack()
concept <- unlist(concept)
test <- unlist(str_split(concept, "\n"))
output <- list(test,concept)
return(output)
}
test <- searchMM(x=question, remDr=remDr)
我想在Controller层调用它:
public class UserDAO {
Logger logger = LogManager.getLogger();
public void SaveUser(User user, LoggerInfo info) {
logger.info("Executor {} trying to save user {}...", "Executor name comes here", user.name);
this.saveToFirstDB(user);
this.saveToSecondDB(user);
logger.info("Executor {} succesfully saved user {}.", "Executor name comes here", user.name);
}
private void SaveToFirstDB(User user) {
logger.info("Executor {}, enter SaveToFirstDB.", "Executor name comes here", user.name);
// save user to first db..
logger.info("Executor {}, exit SaveToFirstDB.", "Executor name comes here", user.name);
}
private void SaveToSecondDB(User user) {
logger.info("Executor {}, enter SaveToSecondDB.", "Executor name comes here", user.name);
I
// save user to second db..
logger.info("Executor {}, exit SaveToSecondDB.", "Executor name comes here", user.name);
}
}
当然我可以注入执行者名称,但我不认为我应该这样做(这只是一个简单的例子,我想注入更多细节,如日期,角色等等。)。
我不想注入细节,我不希望DAL(例如)知道Controller层的上下文对象(Play,Spark ..)。 那么在后端编写信息性日志的正确方法是什么?
答案 0 :(得分:2)
您可以使用Log4j映射诊断上下文。在此方法中,您可以编写请求拦截器或servlet过滤器以在Log4j MDC中设置其他属性。 您的servlet过滤器如下所示 -
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
/*
* This code puts the value "userName" to the Mapped Diagnostic
* context. Since MDc is a static class, we can directly access it
* with out creating a new object from it. Here, instead of hard
* coding the user name, the value can be retrieved from a HTTP
* Request object.
*/
MDC.put("userName", req.attribute("executor"));
MDC.put("date", System.currentTimeMilis());
MDC.put("role", getRole());
//Any other properties you want to set
chain.doFilter(request, response);
} finally {
MDC.remove("userName");
}
}
然后你可以为你的UserDao类编写cutomize log4j模式。
[%d{ISO8601}] %X{userName} %X{role} %p %c - %m%n
以上语法仅供参考。