Log4j2: Dynamic creation of log files for multiple logs

前端 未结 3 1069
挽巷
挽巷 2020-12-06 03:28

I am currently creating a system that can have modules (think of them as plugins), where each one of them can have their own log, dedicated.

I would like to use the

3条回答
  •  不知归路
    2020-12-06 04:09

    Even though Remko Popma's answer might be the most efficient way to do the logging, I built a small class that can create log files on it's own.

    I think I will use the accepted answer's solution, so here is the code I wrote to work around the XML file stuff:

    import gnu.trove.map.hash.THashMap;
    import org.apache.logging.log4j.Level;
    import org.apache.logging.log4j.core.Logger;
    import org.apache.logging.log4j.core.LoggerContext;
    import org.apache.logging.log4j.core.appender.FileAppender;
    import org.apache.logging.log4j.core.async.AsyncLoggerContext;
    import org.apache.logging.log4j.core.layout.PatternLayout;
    import org.apache.logging.log4j.message.FormattedMessageFactory;
    import org.apache.logging.log4j.message.MessageFactory;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Map;
    
    /**
     * Represents a manager for custom log files stored inside a log folder.
     */
    public class LoggingManager {
        /** The default log file extension */
        public static final String FILE_EXTENSION = "log";
    
        /** The global context used for all loggers */
        private final LoggerContext context;
    
        /** The global message factory used for all loggers */
        private final MessageFactory msgFactory;
    
        /** A map of all created logs */
        private final Map logCache;
    
        /** The folder containing the log files */
        private final File logFolder;
    
    
        public LoggingManager(String name, File logFolder) throws IOException {
            this.logFolder = logFolder;
    
            if(!logFolder.exists()) {
                if(!logFolder.mkdirs()) {
                    throw new IOException("Could not create log folder");
                }
            }
    
            this.logCache = new THashMap();
    
            // Create logger context
            this.context = new AsyncLoggerContext(name);
    
            // Create formatted message factory
            this.msgFactory = new FormattedMessageFactory();
        }
    
        public Logger getLogger(String name) {
            Logger logger = logCache.get(name);
    
            // Create a new one
            if(logger == null) {
                logger = new SimpleLogger(name);
    
                FileAppender appender = FileAppender.createAppender(
                        new File(logFolder, name + "." + FILE_EXTENSION).getAbsolutePath(),
                        "true",
                        "false",
                        "file_appender-" + name,
                        "true",
                        "false",
                        "true",
                        PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, null, "UTF-8", "true"),
                        null,
                        "false",
                        null,
                        null
                );
    
                appender.start();
                logger.getContext().getConfiguration().getLoggerConfig("root").addAppender(appender, Level.ALL, null);
    
                // Add to log cache
                logCache.put(name, logger);
            }
    
            // Return the logger
            return logger;
        }
    
        private class SimpleLogger extends Logger {
    
            public SimpleLogger(String name) {
                super(context, name, msgFactory);
    
                // Set to all levels
                this.setLevel(Level.ALL);
            }
    
        }
    
    }
    

    If you don't use trove you can replace it with a normal java HashMap if you want.

提交回复
热议问题