r0ast3d
r0ast3d

Reputation: 2635

Generic Logging Method

Is this a good thing to do; to log via a method like this?

public static void log(final Object... messages) {
    logger.info(Joiner.on(',').useForNull("null").join(messages));
}

// Where in other parts of code we can call the logger method using commas instead of string concatenation. Please note Joiner is a guava class.

log(" Check ",obja.getXXX(),anotherObject.getMethod());

Expectation is clean code, convenience and performance.

Upvotes: 5

Views: 1827

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96394

SLF4J's interface is better, like other answers say.

I'm not understanding how this is a performance improvement. Maybe the OP has a specific use case in mind and some example code would explain it. If the idea is to collect messages upfront and send them together to a log method invocation, then you'd be better served using an appender that does buffering.

Upvotes: 2

adarshr
adarshr

Reputation: 62593

I use SLF4J's Logger interface (with Logback implementation), which I find much cleaner to read.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test {
    private static final Logger logger = LoggerFactory.getLogger(Test.class);

    public void method(String name, int age, Address address) {
        logger.info("Person {}, age {} years old resides at {}", name, age, address);
    }
}

Upvotes: 4

Aaron Digulla
Aaron Digulla

Reputation: 328644

You will probably want to join on ' ' (blank) rather than comma but the design approach is a nice idea.

Performance wise, it's not ideal. You create an additional object array and a joiner plus the internal buffers of the joiner.

So you can just get 2 of 3 with this approach. If you really care about performance, use slf4j which already uses a similar approach.

Upvotes: 2

Related Questions