Provide others with a jar package, which can print logs directly and collect logs to a fixed location. In most cases now, the logback.xml file is used. If this file is still used, it may cause conflicts (of course you can use other name), in order to avoid having to load files, write the configuration directly in Java, as follows:
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."); } }
The client can print the relevant logs by directly calling SecurityLoggerFactory.getLogger().info(). In addition to outputting the log on the console, the log will also be output to the specified file.
Note:
The file path is the Linux path. If the file cannot be generated when executed in Windows, the Windows path must be used, such as: c:/securitylog/securitylog.log
The above is the detailed content of How to write logback configuration using java code. For more information, please follow other related articles on the PHP Chinese website!