Rumah >Java >javaTutorial >如何使用java代码编写logback配置
给别人提供一个jar包,可以直接打印日志,将日志采集到固定位置,现在大多数的情况都是使用的logback.xml文件,如果还用这个文件可能会造成冲突(当然可以用其他名字),为了避免还得加载文件,直接用Java编写配置,如下:
public class SecurityLoggerFactory { private static final String logPath = "/export/Logs/securityLog/securityLog.log"; private static final String logPathHistory = "/export/Logs/securityLog/securityLog.log.%d"; private static Logger logger = null; public static Logger getLogger(){ return logger; } /** * 构造Logger * 设置路径 * 设置滚动方式 */ static { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); //loggerContext.reset(); RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<ILoggingEvent>(); rollingFileAppender.setContext(loggerContext); rollingFileAppender.setAppend(true); rollingFileAppender.setName("jdSecurityLogAppender"); rollingFileAppender.setFile(logPath); TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy<>(); rollingPolicy.setFileNamePattern(logPathHistory); rollingPolicy.setMaxHistory(10); rollingPolicy.setContext(loggerContext); rollingPolicy.setParent(rollingFileAppender); rollingPolicy.start(); rollingFileAppender.setRollingPolicy(rollingPolicy); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setPattern("%msg%n"); encoder.setCharset(Charset.forName("UTF-8")); encoder.setContext(loggerContext); encoder.start(); rollingFileAppender.setEncoder(encoder); rollingFileAppender.start(); ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger("securityLogLogger"); rootLogger.setLevel(Level.INFO); rootLogger.addAppender(rollingFileAppender); logger = rootLogger; } public static void main(String[] args) { SecurityLoggerFactory.getLogger().info("this is text log."); } }
客户端直接调用SecurityLoggerFactory.getLogger().info()就能打印相关的日志了。而日志除了在控制台输出,还会输出到指定文件。
注意:
文件路径是Linux路径,如果在Windows执行并不能生成文件,得用Windows路径,如:c:/securitylog/securitylog.log
Atas ialah kandungan terperinci 如何使用java代码编写logback配置. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!