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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Avoiding If-Else: Advanced Approaches and Alternatives
  • Dust: Open-Source Actors for Java
  • Redefining Java Object Equality

Trending

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Accelerating AI Inference With TensorRT
  • Why Documentation Matters More Than You Think
  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 user avatar
Otavio Santana
DZone Core CORE ·
Aug. 07, 24 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
10.3K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Avoiding If-Else: Advanced Approaches and Alternatives
  • Dust: Open-Source Actors for Java
  • Redefining Java Object Equality

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: