2

I'm new to Java, I'm testing some code for an existing project. I was wondering why they chose to use enums for their log messages. Any hint? Is it a good approach?

This is the class containing the log messages:

import com.myproject.logging.LogEntryDefinition;

import java.text.MessageFormat;
import java.util.logging.Level;

public enum LogEntries implements LogEntryDefinition {

    MsgProcessingError( Level.SEVERE, "RPS0001", "Exception during message processing: {0}. Message consumed: {1}" ),
    MessageConsumedFromPcuQueue( Level.INFO, "RPS0002", "Message extracted from queue: {0}" ),
    ResourceRetrievedFromParis( Level.INFO, "RPS0003", "Resource retrieved from db: {0}" ),
    IllegalMessageConsumed( Level.SEVERE, "RPS0004", "Illegal update message consumed by Agent. Message: {0}" ),
    ...

    private final String id;
    private final MessageFormat format;
    private final Level level;

    private LogEntries( final Level level, final String id, final String format ) {
        this.level = level;
        this.id = id;
        this.format = new MessageFormat( format );
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public MessageFormat getFormat() {
        return format;
    }

    @Override
    public Level getLevel() {
        return level;
    }
}

This is the interface:

package com.myproject.logging;

import java.text.MessageFormat;
import java.util.logging.Level;

public interface LogEntryDefinition {

    String getId();

    MessageFormat getFormat();

    Level getLevel();
}

And this an example of how it's used:

...

}catch(Exception e){
    LOGGER.log( LogEntries.MsgProcessingError, e.getMessage(), t.toString() );
}

Thanks!

  • What did you expect them to use? – Vince Mar 15 '16 at 03:29
  • Because there are a set (known) number of log levels, and an `enum` is *designed* to provide an efficient way to implement *enumerations* of *things*. – Elliott Frisch Mar 15 '16 at 03:30
  • @VinceEmigh A "normal" static class / singleton .. –  Mar 15 '16 at 03:31
  • For me it's one way to enforce (a little) "You will not litter MY pretty log file with your uncessary, ad-hoc log messages that no-one reads and makes it un-auditable" ;-) – VolkerK Mar 15 '16 at 03:32
  • Enums are used to implement safe singletons, which don't require double-checked locking to ensure thread-safe initialization. They basically are singletons. Check out [this article from Joshua Bloch](http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3), the author of Effective Java and the person who contributed to Java many times (such as the Collections Framework). Enums are an easier way to implement singletons. – Vince Mar 15 '16 at 03:32
  • Thanks! Now it's clearer –  Mar 15 '16 at 03:38

2 Answers2

2

You suggested they should use a Singleton in the comments. Enums are an easier way to implement singletons.

Enum singletons ensure thread-safe initialization without the need for double-checked locking. It's an easy alternative to the Initialize On-Demand idiom, which although ensures thread-safe initialization without synchronization overhead, it's quite verbose and requires you to create a helper class.

Enum singletons also protect against reflection attacks. Only one instance of a singleton should exist (due to the nature of the design). Using a class-based singleton, reflection could be used to change the accessability of the constructor from private to public, allowing multiple instances. An enum's constructor is implicitly private, and it's accessability cannot be modified via reflection.

As for your comment of comparing enums vs comparing ints, that is considered micro-optimization. You should focus more on maintainability than trying to save a few nanoseconds.

Hope this answers your question! :)

Vince
  • 14,470
  • 7
  • 39
  • 84
0

I don't think use Enum for message logging is the best way.I think Properties is better than Enum in this case.

Tinh Cao
  • 67
  • 6
  • For what reasons? You should always include a reason. Otherwise there's no real debate. Your opinion could be based on lack of information. Our opinion could be based on lack of information. How could we determine if there's no reason? – Vince Mar 15 '16 at 06:52
  • "enum comparison is slower that the integer comparison by around 1.5%" ( http://stackoverflow.com/questions/8029040/performance-of-java-enums/8029120 ) –  Mar 15 '16 at 16:20
  • "comparing enum values to other enum values can actually be faster that comparing strings to strings" ( http://stackoverflow.com/questions/2446135/is-there-a-performance-hit-when-using-enum-values-vs-string-arrays ) –  Mar 15 '16 at 16:22