提供別人一個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
以上是如何使用java程式編寫logback配置的詳細內容。更多資訊請關注PHP中文網其他相關文章!