首页 > 代码库 > java程序中输出console的日志到文本
java程序中输出console的日志到文本
http://blog.sina.com.cn/s/blog_76a8411a01010u2h.html
首先:当我们引入data-integration\lib文件夹下的所有jar包后 运行java程序要求我们必须引入log4j,由此我们可以确认控制台输出的信息为log4j做的:
程序如下:
public static void main(String[] args) throws Exception{
KettleEnvironment.init();
try {
JobMeta
jobMeta = new JobMeta("E:\\BI\\sample.kjb", null,null);
Job job = new
Job(null, jobMeta);
jobMeta.setArguments(new
String[]{"aaaaa","bbbbbb"});//传参数
job.getJobMeta().setInternalKettleVariables(job);
job.setLogLevel(LogLevel.BASIC);
// Start the Job, as it is a Thread itself by Kettle.
job.start();
job.waitUntilFinished();
if (job.getResult() != null &&
job.getResult().getNrErrors() != 0) {
//Do something here.
}
// Now the job task is finished, mark it as finished.
job.setFinished(true);
// Cleanup the parameters used by the job. Post that invoke
GC.
jobMeta.eraseParameters();
job.eraseParameters();
} catch (Exception e) {
e.printStackTrace();
}
}
解决步骤:
1、首先想到查看输出这些日志的来源:Job类
2、通过反编译软件 或者 查看源文件 查看代码 找到:this.log = new LogChannel(this);
3、进入LogChannel找到: private static LogWriter log = LogWriter.getInstance();
可以看出是单例
4、查看LogWiter的构造方法:
private LogWriter()
{
this.pentahoLogger = Logger.getLogger("org.pentaho.di");
this.pentahoLogger.setAdditivity(false);
this.pentahoLogger.setLevel(Level.ALL);
layout = new Log4jKettleLayout();
boolean consoleAppenderFound = false;
Enumeration
appenders = this.pentahoLogger.getAllAppenders();
while
(appenders.hasMoreElements()) {
Appender appender = (Appender)appenders.nextElement();
if ((appender instanceof ConsoleAppender)) {
consoleAppenderFound = true;
break;
}
}
if
(!consoleAppenderFound) {
Layout patternLayout = new PatternLayout("%-5p %d{dd-MM
HH:mm:ss,SSS} - %m%n");
ConsoleAppender consoleAppender = new
ConsoleAppender(patternLayout);
consoleAppender.setName("ConsoleAppender:org.pentaho.di");
this.pentahoLogger.addAppender(consoleAppender);
}
LogManager.getLogger("org.apache.commons.vfs").setLevel(Level.WARN);
}
5、看出 原来 他们是判断有没有控制台输出的,如果没有就加入一个控制台输出的,
log的识别符为:Logger.getLogger("org.pentaho.di");
6、==============================================================
=================================================================
由此,我们可以再我们程序中加入一行代码: 手动的去加入一个FileAppender
在try中第一行加入:
Logger.getLogger("org.pentaho.di").addAppender(new FileAppender(new SimpleLayout(), "E:\\logger.log"));
这样我们就可以把console端打印出来的log 直接输入到一个log文件中去了
java程序中输出console的日志到文本