Captura del log log4j en programa con WriterAppender
En unos de mis aplicaciones necesitaba capturar log de salida log4j, es decir enviar salida de stack log4j a un String. Se realiza con un WriterAppender.
DebugClass.java
import org.apache.log4j.Logger;
public class DebugClass {
static Logger logger = Logger.getLogger(DebugClass.class);
public DebugClass(){
logger.debug("Es un log de prueba");
}
}
LoggerString.java
import java.io.ByteArrayOutputStream;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
public class LoggerString {
private static Logger logger = Logger.getLogger(DebugClass.class);
private ByteArrayOutputStream out = new ByteArrayOutputStream();
public static void main(String[] args) {
LoggerString test = new LoggerString();
System.out.println("Log de salida:" + test.getMessage());
}
public LoggerString() {
logger.setLevel(Level.DEBUG);
WriterAppender writeappender = new WriterAppender(new SimpleLayout(),
out);
logger.addAppender(writeappender);
new DebugClass();
}
public String getMessage() {
String message = out.toString();
try {
out.close();
} catch (Exception er) {
}
return message;
}
}
DebugClass.java
import org.apache.log4j.Logger;
public class DebugClass {
static Logger logger = Logger.getLogger(DebugClass.class);
public DebugClass(){
logger.debug("Es un log de prueba");
}
}
LoggerString.java
import java.io.ByteArrayOutputStream;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
public class LoggerString {
private static Logger logger = Logger.getLogger(DebugClass.class);
private ByteArrayOutputStream out = new ByteArrayOutputStream();
public static void main(String[] args) {
LoggerString test = new LoggerString();
System.out.println("Log de salida:" + test.getMessage());
}
public LoggerString() {
logger.setLevel(Level.DEBUG);
WriterAppender writeappender = new WriterAppender(new SimpleLayout(),
out);
logger.addAppender(writeappender);
new DebugClass();
}
public String getMessage() {
String message = out.toString();
try {
out.close();
} catch (Exception er) {
}
return message;
}
}
0 comentarios