Создание логгера log4j в виде объекта.
package your.package; import org.apache.log4j.*; import java.io.IOException; public class LoggerHelper { public Logger log; public LoggerHelper(String loggerName, String logFileName, String conversionPattern, String logLevel) { PatternLayout layout = new PatternLayout(); layout.setConversionPattern(conversionPattern); RollingFileAppender appender; try { appender = new RollingFileAppender(layout, logFileName); appender.setName(loggerName); appender.setFile(logFileName); appender.setMaxFileSize("1MB"); layout.activateOptions(); appender.activateOptions(); BasicConfigurator.configure(); log = LogManager.getLogger(loggerName); Logger.getRootLogger().addAppender(appender); Logger.getRootLogger().setLevel(getLevel(logLevel)); } catch (IOException e) { e.printStackTrace(); } } public void close() { log.getLoggerRepository().shutdown(); } private Level getLevel(String level) { Level loggerLevel; switch (level) { case "Info": loggerLevel = Level.INFO; break; case "Debug": loggerLevel = Level.DEBUG; break; default: loggerLevel = Level.INFO; break; } return loggerLevel; } }
Использование:
String loggerName = "loggerName"; String logName = @"C:\someFolder\logname.log"; LoggerHelper logger = new LoggerHelper(loggerName, logName, "%d %-5p %m%n", "Debug"); logger.log.info("Hello World!"); logger.log.debug("Hello World!"); // logger.close();
Содержимое лога:
2018-04-22 13:23:29,575 INFO Hello World! 2018-04-22 13:23:29,575 DEBUG Hello World!