通过代码配置logback

import java.nio.charset.Charset;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.FileAppender;


/**
 * Hello world!1
 *
 */
public class MainApp
{
    public static void main( String[] args )
    {
    	Logger logger=MyLoggerFactory.getLogger();
    	logger.info("this is text log.");
        
    }
}
class MyLoggerFactory{

    private static Logger logger = null;
    public static Logger getLogger() {
    	return logger;
    }
	//在类加载时执行,保证执行一遍,不在执行,保证单实例。
	 static {
	      LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	      FileAppender fa=new FileAppender();
	      fa.setContext(loggerContext);
	      fa.setAppend(true);
	      fa.setName("FILE");
	      String s=System.getProperty("user.dir")+"\\log.txt";
	      fa.setFile(s);
	      ConsoleAppender ca=new ConsoleAppender();
	      ca.setName("CONSOLE");
	      //内容配置
	      PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	      encoder.setPattern("%msg");
	      encoder.setCharset(Charset.forName("UTF-8"));
	      encoder.setContext(loggerContext);
	      encoder.start();
	      /
	      fa.setEncoder(encoder);
	      ca.setEncoder(encoder);
	      fa.start();
	      ca.start();

	      ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger("rootLogLogger");
	      rootLogger.setLevel(Level.INFO);
	      rootLogger.addAppender(ca);
	      rootLogger.addAppender(fa);
	      rootLogger.setAdditive(false);
	      logger = rootLogger;
	  }
   
}

通过以上代码,就可以实现在命令行与文件同时输出信息,并且输出目录为当前文件夹

如果没打包之前,那么是项目根目录

如果打包后,是运行程序所在的目录

你可能感兴趣的:(Java)