我正在研究一种方法,尝试使用 log4j 将默认的放心日志(转到控制台)更改为文件。
这是一个 JUnit 项目,其方法最终调用 REST 外观,该外观具有类似这样的方法。
private ResponseSpecification responseSpecification(RequestSpecification requestSpecification, Matcher matcher, int statusCode) {
ResponseSpecification responseSpecification = requestSpecification.expect().statusCode(StatusCode).body(".", is(matcher));
if (log) {
responseSpecification = responseSpecification.log().all();
}
return responseSpecification;
}
继官方文档,我改变了这样的方法:
private ResponseSpecification responseSpecification(RequestSpecification requestSpecification, Matcher matcher, int statusCode) {
final StringWriter writer = new StringWriter();
final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
ResponseSpecification responseSpecification = requestSpecification.filter(logResponseTo(captor)).expect().statusCode(statusCode).body(".", is(matcher));
System.out.println("writer = " + writer.toString() + " <-");
return responseSpecification;
}
But writer.toString()
始终打印一个空字符串(旧的实现工作正常)。也许我做错了什么,但是什么? :(
我需要获得可以通过 log4j 以这种或其他方式管理的可打印内容。
谁能帮我?
可能也有用:这里有一个类,它将restAssured log() 调用重定向到提供的记录器:
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import org.slf4j.Logger;
/**
* A wrapper class which takes a logger as constructor argument and offers a PrintStream whose flush
* method writes the written content to the supplied logger (debug level).
* <p>
* Usage:<br>
* initializing in @BeforeClass of the unit test:
* <pre>
* ToLoggerPrintStream loggerPrintStream = new ToLoggerPrintStream( myLog );
* RestAssured.config = RestAssured.config().logConfig(
* new LogConfig( loggerPrintStream.getPrintStream(), true ) );
* </pre>
* will redirect all log outputs of a ValidatableResponse to the supplied logger:
* <pre>
* resp.then().log().all( true );
* </pre>
*
* @version 1.0 (28.10.2015)
* @author Heri Bender
*/
public class ToLoggerPrintStream
{
/** Logger for this class */
private Logger myLog;
private PrintStream myPrintStream;
/**
* @return printStream
*/
public PrintStream getPrintStream()
{
if ( myPrintStream == null )
{
OutputStream output = new OutputStream()
{
private StringBuilder myStringBuilder = new StringBuilder();
@Override
public void write(int b) throws IOException
{
this.myStringBuilder.append((char) b );
}
/**
* @see java.io.OutputStream#flush()
*/
@Override
public void flush()
{
myLog.debug( this.myStringBuilder.toString() );
myStringBuilder = new StringBuilder();
}
};
myPrintStream = new PrintStream( output, true ); // true: autoflush must be set!
}
return myPrintStream;
}
/**
* Constructor
*
* @param aLogger
*/
public ToLoggerPrintStream( Logger aLogger )
{
super();
myLog = aLogger;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)