Explanation of the configuration of ConversionPattern in log4j

In the log4j configuration file, you can use ConversionPattern to define the format of log output. ConversionPattern is a string that can contain special conversion symbols such as:

  1. %m: Log message
  2. %p: Log level
  3. %c: the full name of the class to which the log belongs
  4. %C: Simple name of the class to which the log belongs.
  5. Thread Name: %t
  6. Duration since the application was launched (measured in milliseconds)
  7. %n: Newline character for the platform
  8. %d: date and time (formatted through SimpleDateFormat)

    %d{HH:mm:ss,SSS}: hour:minute:second, millisecond
    %d{dd MMM yyyy HH:mm:ss,SSS}: day month year hour:minute:second, millisecond

  9. Location of the log occurrence
  10. Percentage sign

For example, the following is a common ConversionPattern configuration:

log4j.appender.ConsoleAppender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %m%n

In the above setup, %d{yyyy-MM-dd HH:mm:ss} represents the output of date and time, [%t] represents the output of the thread name, %-5p represents the output of the log level (left-aligned, maximum of 5 characters), %c{1} represents the output of the simple name of the class (only showing the first word), %L represents the output of the line number where the log occurred, %m represents the output of the log message, and %n represents a newline character.

By using ConversionPattern, you can flexibly define the output format of the logs to meet different requirements.

bannerAds