我需要能够使用数据库池查看应用程序的查询日志。我发现DataSource允许我将setLogWriter与PrintWriter一起使用。
我必须处理将要输出的信息,所以我不想将它们发送到文件。是否可以通过在流式传输时将其转换为字符串来从数据源中读取信息流?
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://" + db_host + ":3306/" + db_name+"?logger=StandardLogger&profileSQL=true");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername(db_user);
p.setPassword(db_pwd);
p.setJmxEnabled(true);
//p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(maxActive);
p.setMaxIdle(5);
p.setInitialSize(minActive);
p.setMaxWait(30000);
p.setRemoveAbandonedTimeout(300);
p.setMinEvictableIdleTimeMillis(60000);
p.setMinIdle(3);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
ds = new DataSource();
ds.setPoolProperties(p);
ds.setLogWriter(new PrintWriter(...)); <-- Watch the output live of the PrintWriter
我想将setLogWriter重定向到watch函数,这将允许我在输出时以字符串形式读取和处理信息。例如:
Public void analyzeLog(String fromPrintWriter){
if(fromPrintWriter.startsWith("abc"){
CODE HERE... ETC
}
}
答案 0 :(得分:0)
在PipedWriter
的帮助下
和PipedReader
您可以为读取日志输出设置Reader
。
应用于您的案例代码可能与此类似:
ds = new DataSource();
ds.setPoolProperties(p);
PipedWriter pipedWriter = new PipedWriter();
ds.setLogWriter(new PrintWriter(pipedWriter));
Runnable runnable = () -> {
// setup a Reader for reading the DataSource's log output
try (BufferedReader bufferedReader = new BufferedReader(new PipedReader(pipedWriter))) {
// start reading from PipedReader, so that writing to PipedWriter will not block
String line = bufferedReader.readLine();
while (line != null) {
analyzeLog(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
};
new Thread(runnable).start();
答案 1 :(得分:0)
只需编写一个扩展PrintWriter
的类,并在执行代码后委托给另一个。