JUL Logging Format Specification (JSON, XML, Custom)

Java Util Logging (JUL) is a built-in logging framework within the Java standard library, designed to provide a simple and efficient logging mechanism. However, in actual enterprise development, relying solely on the default text format often fails to meet requirements for structured data, searchability, and cross-system integration. Therefore, deeply understanding and mastering the multiple output formats supported by JUL—including JSON, XML, and custom formats—is crucial for building high-availability, easy-to-maintain logging systems. This article explores the characteristics, implementation methods, and applicable scenarios of these three core formats.

JSON Format: The Foundation of Modern Logging Systems

JSON (JavaScript Object Notation) has become the preferred format for modern logging frameworks due to its lightweight nature, readability, and powerful parsing capabilities. Unlike traditional Key-Value text formats, JSON can naturally express nested structures, making it ideal for efficient retrieval and analysis by log aggregation platforms such as the ELK Stack or Loki.

Implementing the JSON format in JUL primarily relies on the Formatter class and its subclass JsonFormatter from java.util.logging. Compared to XML or custom text formatters, the advantage of JSON lies in its structured key-value characteristics. For example, a standard log record containing multiple attributes will be clearly presented as an object in JSON output:

{
  "level": "INFO",
  "timestamp": "2023-10-27T10:00:00.000Z",
  "message": "User login successful",
  "userId": "12345",
  "ipAddress": "192.168.1.1"
}

This format not only preserves all metadata but also allows the logging system to process data directly without relying on language-specific parsers. Furthermore, the JSON format supports custom field mapping; developers can configure specific Java object properties to be automatically injected into log records, thereby reducing the workload of manually concatenating strings. For scenarios requiring large-scale log analysis, JSON is an indispensable standard.

XML Format: A Balance Between Tradition and Standardization

XML (Extensible Markup Language), as a mature markup language, held a significant position in early Java applications. Although its tag structure is more verbose than JSON, XML possesses strict syntax specifications, making it highly suitable for scenarios requiring rigorous data integrity validation. In certain legacy systems or specific industry standards, XML remains the de facto standard for log output.

JUL provides convenient XML formatting support through the XmlFormatter class. This format encapsulates log levels, timestamps, messages, and additional key-value pairs within standard XML tag structures. For instance, a log record containing user information will be rendered as:

<java.util.logging.Level>INFO</java.util.logging.Level>
<timestamp>2023-10-27T10:00:00.000Z</timestamp>
<message>User login successful</message>
<key>userId</key><value>12345</value>
<key>ipAddress</key><value>192.168.1.1</value>

Although XML parsing efficiency is slightly lower than JSON, its powerful self-describing capabilities and extensive tool support give it an advantage when exchanging data with external systems (such as legacy ERP systems or specific compliance audit tools). Developers using XmlFormatter can also configure whether stack trace information should be included to provide complete context when recording exceptions.

Custom Format: The Ultimate Solution for Flexible Customization

Beyond the preset JSON and XML formats, JUL's most powerful feature lies in its highly flexible custom formatting capabilities. By inheriting the java.util.logging.Formatter class and overriding relevant methods, developers can have full control over every character in the log output, including prefixes, delimiters, timestamp styles, and exception stack trace printing methods.

This flexibility allows custom formats to perfectly align with specific business requirements. For example, certain systems may require logs to be written in CSV format for database import, or include special encrypted identifiers. The core of implementing a custom Formatter lies in overriding the format method:

public class CustomFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
        StringBuilder sb = new StringBuilder();
        sb.append("[")
          .append(record.getLevel().toString())
          .append("] ")
          .append(record.getMessage());
        
        // Process exception stack trace
        if (record.isThrownException()) {
            Throwable t = record.getThrown();
            while (t != null) {
                sb.append("\n");
                sb.append(t.getClass().getName());
                sb.append(": ");
                sb.append(t.getMessage());
                t = t.getCause();
            }
        }
        
        return sb.toString();
    }
}

Through such custom logic, developers can ensure log output adheres to internal standards while avoiding conversion overhead between different formats. In practical applications, it is recommended to configure the custom Formatter as the default format, switching only to JSON or XML modes when exporting specific reports, thus balancing performance and functional requirements.

Summary and Recommendations

In summary, JUL's JSON, XML, and custom formats each have their merits. JSON has become the preferred choice for modern microservice architectures due to its structured and easily parsable nature; XML continues to play a vital role in legacy systems requiring strict data validation; and custom formats grant developers the freedom to handle special business scenarios. In actual projects, it is recommended to prioritize evaluating the requirements of the downstream recipients of the logging system: if interfacing with big data platforms or search engines, choose JSON; if compatibility with old systems is needed, XML is a safe choice; if pursuing extreme performance and customization, a custom Formatter is the optimal solution. Reasonably selecting and configuring log formats will significantly enhance system observability and operational efficiency.