简体   繁体   English

Log4j - 强制日志消息参数

[英]Log4j - Force log message parameters

I am trying to force the detail within log4j messages as opposed to just a string.我试图强制 log4j 消息中的细节,而不仅仅是一个字符串。 Ultimately I would like to have something like:最终我想有类似的东西:

logger.info("component", "error code", " error message"); logger.info("组件", "错误代码", "错误信息");

I may even use an enum for the component.我什至可以为组件使用枚举。

I would then expect the message to appear in the log as "time - component - code - message"然后我希望消息在日志中显示为“时间 - 组件 - 代码 - 消息”

Any ideas?有任何想法吗?

A very trivial solution (for this special case):一个非常简单的解决方案(对于这种特殊情况):

logger.info(
      String.format("%s - %s - %s", "component", "error code", "error message"));

or in an improved version:或改进版本:

logger.info(createMessage("component", "error code", "error message"));

with

public static String createMessage(
                 String component, String errorCode, String errorMessage) {
   return String.format("%s - %s - %s", 
                 "component", "error code", "error message");
}

For a more general solution, consider wrapping the original Logger class into a custom logger class and implement an info method that takes the three arguments and delegates to internalLogger.info(String message) with the new message based on the input.对于更通用的解决方案,考虑将原始记录器 class 包装到自定义记录器 class 并实现一个info方法,该方法采用三个 arguments 并将新消息委托给internalLogger.info(String message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM