Building a Java application with Log4j 2 logging in NetBeans

Log4j 2 is a logging framework for Java applications. It separates log events from application code, then sends them to appenders such as the console or rolling files. Pattern layouts control timestamps, levels, logger names, and messages, giving NetBeans developers useful output while debugging a Maven project.

This guide builds a small Java application in Apache NetBeans, adds Log4j 2 through Maven, writes parameterised messages, and packages the result. The example suits Australian teams: an organisation might use a controlled .com.au domain, price work in AUD, and support customers across Sydney, Melbourne, Brisbane, and Perth.

Create the Maven project

Open Apache NetBeans and choose File > New Project, then Java with Maven and Java Application. Set the project name, Maven coordinates, and main class. Java 17 or 21 provides a sensible release target for a new service, while NetBeans generates the source package, main class, and pom.xml.

For an Australian-owned organisation, a package such as au.com.acme.orders reflects a controlled commercial domain. The site's NetBeans project background also gives useful context for newcomers choosing an IDE or project layout. Run the generated class before adding dependencies to confirm that Java compilation and execution work locally.

Add the logging dependencies

Open pom.xml and let NetBeans add log4j-api and log4j-core at the same 2.x version. The API lets application code create loggers; the core module supplies the implementation and appenders. Define the version property with a currently patched release rather than copying an obsolete version from an old tutorial.

<properties>
    <log4j.version>YOUR_CURRENT_2_X_VERSION</log4j.version>
</properties>

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>${log4j.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>${log4j.version}</version>
</dependency>

If existing classes use the SLF4J facade, add slf4j-api and the Log4j 2 SLF4J implementation instead of installing competing providers. The browse NetBeans categories area helps readers find related Java and IDE material. After Maven reloads, inspect the dependency tree to confirm that only one logging backend is active.

Configure runtime output

Create src/main/resources/log4j2.xml so the configuration is packaged with the application. A console appender and pattern layout provide a compact starting point, while a package-specific logger enables debug events without making every library verbose.

<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{1} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="au.com.acme.orders" level="debug"/>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

The root logger accepts informational messages, while the application package can emit debug details. WARN suppresses lower-priority records, and ERROR remains visible for failures. Keep credentials, payment details, and personal information out of log messages; useful event context is preferable to sensitive payloads.

Time-zone handling matters locally. Sydney and Melbourne change between AEST and AEDT, while Brisbane and Perth do not observe daylight saving. For consistent regional operations, decide whether timestamps should use the JVM default or UTC, then test that choice before deployment.

Write application log messages

Replace direct calls to System.out.println with a Log4j logger. Parameterised messages defer string construction until an enabled level is recorded, keeping normal application paths efficient.

private static final Logger LOG =
        LogManager.getLogger(OrderService.class);

public void acceptOrder(String orderId, BigDecimal total) {
    LOG.info("Order {} accepted for {} AUD", orderId, total);
}

Give each logger a stable class name so operators can trace an order or request without searching every line. Pass an exception as the final logging argument rather than formatted text, allowing Log4j 2 to retain its type, message, and stack trace.

For an Australian retail example, record totals as BigDecimal values labelled AUD and state how GST is handled. Avoid logging customer names merely to add context. A correlation identifier is usually a better way to connect messages across services.

Check the logging workflow

Before running the project, review the dependency and source choices:

  • Both Log4j modules use the same release version.
  • The XML configuration lives under src/main/resources.
  • Messages use placeholders rather than string concatenation.
  • Exceptions are passed as the final logger argument.

Then confirm the behaviour visible in the NetBeans Output window:

  • Each record includes a timestamp, severity, logger, and message.
  • INFO output appears, while DEBUG appears for the orders package.
  • A deliberate exception produces a complete stack trace.
  • No credentials, payment data, or unnecessary personal details appear.

Run and package the application

Press F6 to run the main class and inspect the Output window. Change the root or package level temporarily to trace startup, then return it to INFO for normal use. Configuration edits normally require a clean rebuild so the copied resource is refreshed.

Operational checks often sit beside application logging. A linked example explains how to monitor DNS query timings and alert on slow responses, complementing an order-service log during an incident. Correlation identifiers and timestamps make the diagnostic streams easier to compare.

Package the project with mvn clean package. If the executable JAR must include Log4j, configure Maven Shade and its main-class manifest transformer; otherwise, deployment needs the runtime dependencies on the classpath. External log4j2.xml files can be supplied through the log4j.configurationFile system property.

Use the wider NetBeans resources

NetBeans remains useful after the first successful log line. Its debugger, variable views, and profiler can reveal why a message was emitted, while the Maven dependency panel helps locate binding conflicts. The NetBeans Blog also mixes technical tutorials with occasional general-interest posts, such as a note on weekly cashback offers.

For an Australian team, a shared configuration profile can prevent each developer from seeing different log levels. Store only non-secret overrides in source control, keep production credentials in the deployment environment, and document who can retrieve server logs during an arvo support check.