[log4j] 格式化eventLog

格式化log msg

Substituting Parameters

Frequently the purpose of logging is to provide information about what is happening in the system, which requires including information about the objects being manipulated. In Log4j 1.x this could be accomplished by doing:

   
   
  1. if (logger.isDebugEnabled()) {
  2. logger.debug("Logging in user " + user.getName() + " with birthday " + user.getBirthdayCalendar());
  3. }

Doing this repeatedly has the effect of making the code feel like it is more about logging than the actual task at hand. In addition, it results in the logging level being checked twice; once on the call to isDebugEnabled and once on the debug method. A better alternative would be:

logger.debug("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar());

With the code above the logging level will only be checked once and the String construction will only occur when debug logging is enabled.

如source code

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
    private static Logger logger = LogManager.getLogger("HelloWorld");
    public static void main(String[] args) {

        logger.debug("logginer is { } with {} .", "user", "QQ");
        logger.debug("logginer is {} with {} .", "user", "QQ");
 }
}
运行结果就是:

logginer is { } with [user, QQ] .

logginer is userwith QQ .

因此,使用{}做字符替换的占位符。 如果是多个字符串对应一个占位符的话,这些参数会被组织成一个字符数组。

函数原型

 /**
   * Logs a message with parameters at the {@link Level#DEBUG DEBUG} level.
   * @param message the message to log; the format depends on the message factory.
   * @param params parameters to the message.
   * @see #getMessageFactory()
   */
  void debug(String message, Object... params);


Formatting Parameters

Substituting parameters leaves formatting up to you if toString() is not what you want. To facilitate formatting, you can use the same format strings as Java's Formatter. For example:

   
   
  1. public static Logger logger = LogManager.getFormatterLogger("Foo");
  2.  
  3. logger.debug("Logging in user %s with birthday %s", user.getName(), user.getBirthdayCalendar());
  4. logger.debug("Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.getName(), user.getBirthdayCalendar());
  5. logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE);
  6. logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);

To use a formatter Logger, you must call one of the LogManager getFormatterLogger method. The output for this example shows that Calendar toString() is verbose compared to custom formatting:

例如:

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {
    private static Logger logger = LogManager.getFormatterLogger(HelloWorld.class.getName());
    public static void main(String[] args) {

        logger.debug("logginer is { } with {} .", "user", "QQ");
        logger.debug("logginer is {} with {} .", "user", "QQ");
        logger.debug("logginer is with %s .", "user", "QQ");
        logger.debug("logginer is %s with %s .", "user", "QQ");
        logger.debug("Integer: %,d. ",Integer.MAX_VALUE );
        logger.debug("Long: %,d. ",Long.MAX_VALUE );

    }
} 

输出结果:

logginer is { } with {} .
logginer is {} with {} . 这两行都没有替换,看来用{}表示的占位符对于getFormatterLogger类是不work的。
logginer is with user .
logginer is user with QQ .
Integer: 2,147,483,647.
Long: 9,223,372,036,854,775,807

getFormatterLogger能提供类似于C的格式化输出。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个简单的Java代码示例,可以解析log4j格式的日志文件: ```java import java.io.BufferedReader; import java.io.FileReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Log4jParser { public static void main(String[] args) { String logFile = "path/to/your/log/file.log"; try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split("\\s", 4); // 拆分日志行 if (parts.length >= 4) { String timestamp = parts[0] + " " + parts[1]; // 时间戳 String level = parts[2]; // 日志级别 String message = parts[3]; // 日志消息 Date date = parseTimestamp(timestamp); // 解析时间戳 System.out.printf("%s [%s] %s\n", date, level, message); // 打印解析结果 } } } catch (Exception e) { e.printStackTrace(); } } private static Date parseTimestamp(String timestamp) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); return format.parse(timestamp); } } ``` 在此示例中,我们使用BufferedReader类逐行读取日志文件,并使用String.split()方法拆分每一行,从而获取时间戳、日志级别和日志消息。我们将时间戳转换为Date对象,以便进行进一步的处理和格式化输出。 请注意,这只是一个简单的示例代码,实际的实现可能需要更复杂的逻辑来处理各种情况,例如多行消息或不同的日志级别格式。 ### 回答2: 要解析log4j格式的日志,可以使用Java中的正则表达式和字符串操作来提取日志中的各个字段。 首先,读取log文件并将每行日志存储在字符串数组中。可以使用Java中的文件读取和字符串操作方法来实现这一步骤。 接下来,对每一行日志应用正则表达式来提取需要的字段。log4j的日志格式通常包含时间戳、日志级别和具体日志消息。可以使用正则表达式来匹配这些字段并将其存储在对应的变量中。 例如,可以使用如下的正则表达式来匹配log4j日志的时间戳: String regexTimestamp = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"; 使用Java中的Pattern和Matcher类来进行匹配: Pattern patternTimestamp = Pattern.compile(regexTimestamp); Matcher matcherTimestamp = patternTimestamp.matcher(logLine); 然后,使用matcherTimestamp.find()方法来查找匹配的时间戳,并通过matcherTimestamp.group()方法来获取匹配的结果。 类似地,可以使用类似的步骤来提取日志级别和具体日志消息的字段。 最后,将提取的字段进行处理和存储,可以将它们打印出来或存储到其他地方,根据具体需求进行相应的操作。 以上就是使用Java解析log4j格式日志的一个简单示例。具体实现中可能还需要考虑异常处理、文件读取和写入等其他细节。 ### 回答3: 在Java中解析log4j格式的日志文件,我们可以使用log4j库提供的API方法来实现。以下是一个简单的代码示例: ```java import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Log4jParser { public static void main(String[] args) { String logFilePath = "path/to/logfile.log"; parseLog4jLog(logFilePath); } public static void parseLog4jLog(String filePath) { try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; Logger logger = Logger.getLogger(Log4jParser.class); PatternLayout layout = new PatternLayout(); while ((line = reader.readLine()) != null) { LoggingEvent logEvent = layout.parse(line); String logMessage = logEvent.getMessage().toString(); String logLevel = logEvent.getLevel().toString(); String logTimestamp = logEvent.getTimeStamp() + ""; ThrowableInformation throwableInfo = logEvent.getThrowableInformation(); if (throwableInfo != null) { String exceptionStacktrace = throwableInfo.getThrowableStrRep()[0]; // 对于包含异常信息的log,可以通过 throwableInfo 获取异常栈信息 } // 处理解析的日志信息,可根据需要进行相应的业务逻辑处理 System.out.println("Timestamp: " + logTimestamp); System.out.println("Level: " + logLevel); System.out.println("Message: " + logMessage); } } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码中,我们使用`BufferedReader`从日志文件中逐行读取日志内容。然后,我们通过`PatternLayout`的`parse`方法将每行日志内容解析为`LoggingEvent`对象。通过`LoggingEvent`对象,我们可以获取日志的时间戳、日志级别、日志消息以及可选的异常栈信息。 在代码示例中,我们简单示范了如何处理解析的日志信息,你可以根据实际需求进行业务逻辑处理或其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值