import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.message.SimpleMessage;
/**
* Created by lanhuajian on 2017/3/29.
*/
public class StringLogger {
private String loggerName;
private static String FQCN = StringLogger.class.getName();
private static final PatternLayout PATTERN_LAYOUT = PatternLayout.newBuilder()
.withPattern("%d %t %-5p [%c]%L %m%n")
.build();
private StringLogger(String loggerName) {
this.loggerName = loggerName;
}
public static StringLogger getLogger(Class loggerClass) {
return new StringLogger(loggerClass.getName());
}
public static StringLogger getLogger(String loggerName) {
return new StringLogger(loggerName);
}
public String info(String msg) {
return PATTERN_LAYOUT.toSerializable(buildEvent(msg, Level.INFO));
}
public String warn(String msg) {
return PATTERN_LAYOUT.toSerializable(buildEvent(msg, Level.WARN));
}
public String debug(String msg) {
return PATTERN_LAYOUT.toSerializable(buildEvent(msg, Level.DEBUG));
}
public String error(String msg) {
return PATTERN_LAYOUT.toSerializable(buildEvent(msg, Level.ERROR));
}
private Log4jLogEvent buildEvent(String msg, Level level) {
return Log4jLogEvent.newBuilder()
.setIncludeLocation(true)
.setLoggerName(loggerName)
.setLoggerFqcn(FQCN)
.setLevel(level)
.setMessage(new SimpleMessage(msg))
.build();
}
}