DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Arrays in Java
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • Multithreading in Modern Java: Advanced Benefits and Best Practices
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory

Trending

  • Delta Lake UniForm to Snowflake: Cross-Platform Table Access Without a Second Copy
  • Designing for Hot Keys: When Distributed Systems Stop Distributing
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Prompt Caching for LLMs, Part 3: Model-Side Caching and Production Rollout

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Enhancing Java Application Logging: A Comprehensive Guide

Enhancing Java Application Logging: A Comprehensive Guide

Learn Java logging best practices: use proper log levels, include unique IDs for trackability, and secure logs to avoid sensitive data exposure.

By 
Otavio Santana
DZone Core CORE ·
Aug. 07, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Logging is crucial for monitoring and debugging Java applications, particularly in production environments. It provides valuable insights into application behavior, aids in issue diagnosis, and ensures smooth operation. This article will walk you through creating effective logs in Java applications, emphasizing three key aspects.

  1. Logging Good Information
  2. Creating Trackable Logs
  3. Ensuring Security and Avoiding Data Breaches

We will use the java.util.logging package for demonstration, but these principles apply to any logging framework.

1. Logging Good Information

When logging information in your application, it’s crucial to strike a balance. Too much information can overwhelm, while too little can leave gaps. Understanding and utilizing log levels effectively is key.

Log Levels in Java

Java’s logging API provides several log levels, each serving a specific purpose:

  • Severe: Used for critical issues; log exceptions and errors that require immediate attention
  • Warning: Indicates potential problems, such as deprecated API usage or performance bottlenecksInfo: Provides general information about the application’s running state, like the start and end of significant operations
  • Fine: Offers detailed information, such as request and response data, which can be invaluable for debugging

Example

Here’s an example of using different log levels in a credit card payment service:

Java
 
public class CreditCardService {

    private static final Logger LOGGER = Logger.getLogger(CreditCardService.class.getName());

    public void pay(CreditCard creditCard, Product product) {
        try {
            LOGGER.info("Paying with credit card: " + creditCard.getId());
            LOGGER.fine("Paying for product: " + product);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Payment failed: " + e.getMessage(), e);
        }
    }

    @Deprecated
    public void deprecated(CreditCard creditCard, Product product) {
        LOGGER.warning("Deprecated method is called, use pay() instead. It will be removed in the next release. The id: " + creditCard.getId());
    }
}


In this example, we combine different log levels to provide a comprehensive view of the method’s execution and potential issues.

2. Creating Trackable Logs

Trackability is essential in logs, especially when dealing with high volumes of requests. Including unique identifiers such as request IDs or entity IDs in log messages ensures that specific actions can be traced back to their source.

Example

Refactor the pay method to include both credit card and product IDs in the error message:

Java
 
public void pay(CreditCard creditCard, Product product) {
    try {
        LOGGER.info("Paying with credit card: " + creditCard.getId());
        LOGGER.fine("Paying for product: " + product);
    } catch (Exception e) {
        String errorMessage = String.format("Payment failed: card id: %s and product id: %s. Error message: %s", creditCard.getId(), 
                product.getId(), e.getMessage());
        LOGGER.log(Level.SEVERE, errorMessage, e);
    }
}


By including both the credit card ID and product ID in the error message, we enhance the log’s trackability, making it easier to identify and troubleshoot specific issues.

3. Ensuring Security and Avoiding Data Breaches

Logging sensitive information can lead to security breaches. It is vital to ensure that logs do not contain sensitive data such as passwords or credit card numbers. Overriding the toString method can help mask sensitive information.

Example

Here’s how you can modify the CreditCard class to hide the password in logs:

Java
 
public class CreditCard {

    private UUID id;
    private String number; // only the last four digits of the credit card number are stored
    private String password;

    public UUID getId() {
        return id;
    }

    @Override
    public String toString() {
        return "CreditCard{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", password= *****" +
                '}';
    }
}


By masking the password, we prevent sensitive information from being exposed in logs, ensuring compliance with security standards such as PCI DSS.

Conclusion

Effective logging is crucial for maintaining and debugging Java applications. By focusing on logging good information, creating trackable logs, and ensuring security, you can enhance the quality and usefulness of your logs.

For further reading on security in logging, check out this article by Brian Vermeer. Visit my YouTube channel and GitHub repository for additional insights and code examples.

Video


Java (programming language) Data Types Debug (command)

Opinions expressed by DZone contributors are their own.

Related

  • Arrays in Java
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • Multithreading in Modern Java: Advanced Benefits and Best Practices
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook