在Log4j2中动态/编程配置您自己的asynclogger

时间:2014-04-11 04:14:34

标签: logging asynchronous log4j log4j2

我的项目中已经实现了一个旧的log4j1.x,我们通过扩展类 org.apach.log4j.logger 创建了我们自己的logger。但是现在我们想要转移到Log4j2因为它有asynLogger。以下代码实现了以编程方式创建时支持我的log4j2的异步日志记录的所有功能

        import java.util.HashMap;

        import org.apache.logging.log4j.Level;
        import org.apache.logging.log4j.core.LoggerContext;
        import org.apache.logging.log4j.core.appender.ConsoleAppender;
        import org.apache.logging.log4j.core.appender.RandomAccessFileAppender;
        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;

        public final class MyLog4j2Logger extends
                org.apache.logging.log4j.core.async.AsyncLogger {

            private static HashMap<String, MyLog4j2Logger> logCache = new HashMap<String, MyLog4j2Logger>(4);

            private MyLog4j2Logger(LoggerContext context, String name,MessageFactory msgFactory) {
                super(context, name, msgFactory);
                System.out.println("Using AsyncLogger");

                // Set to all levels
                this.setLevel(Level.ALL);
            }

            /*
            * Factory Method that returns an instance of Logger. returns if the
            * instance is already present in the Hash Table else creates now and
            * returns it.
            */
            public final static MyLog4j2Logger getCustomLogger(String sCategory) {
                try {
                    System.setProperty("Log4jContextSelector",
                            "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
                    // Check if Instance is already present for the Category
                    if (logCache.containsKey(sCategory)) {
                        MyLog4j2Logger logger = logCache.get(sCategory);
                        logger.info("Getting already created logger for " + sCategory);
                        return logger;
                    } else {

                        // Create a new custom logger for this category
                        MyLog4j2Logger customLogger = configureCategoryLogger(sCategory);

                        // Add the custom logger to Table.
                        logCache.put(sCategory, customLogger);

                        customLogger.info("Created a New Logger for " + sCategory);

                        return (MyLog4j2Logger) customLogger;
                    }
                } catch (Exception exp) {
                    System.out
                            .println("Exception thrown while fetching Logger instance");
                    exp.printStackTrace();
                }

                return null;

            }

            private static MyLog4j2Logger configureCategoryLogger(String sCategory) {

                // Create logger context
                LoggerContext context = new AsyncLoggerContext(sCategory);

                // Create formatted message factory
                MessageFactory msgFactory = new FormattedMessageFactory();

                MyLog4j2Logger logger = new MyLog4j2Logger(context, sCategory,
                        msgFactory);

                RandomAccessFileAppender appender = RandomAccessFileAppender
                        .createAppender(
                                "C:\\temp\\App.log",// filename
                                "true",// append
                                "file_appender-" + sCategory,// name
                                "true",// immediateFlush
                                "",// bufferSize
                                "true",// ignoreExceptions
                                PatternLayout.createLayout(
                                        "%-5p - [%d] - [%t] - [%l]  : %m%n", null,
                                        null, "UTF-8", "true", sCategory), null,// filter
                                "false",// advertise
                                null,// advertiseURI
                                null// config
                        );

                ConsoleAppender consoleAppender = ConsoleAppender.createAppender(
                        PatternLayout.createLayout("%-5p - [%d] - [%t] - [%l]  : %m%n",
                                null, null, "UTF-8", null, null), null, null,
                        "Console", null, null);

                appender.start();
                consoleAppender.stop();
                logger.getContext().getConfiguration().getLoggerConfig(sCategory)
                        .addAppender(appender, Level.TRACE, null);
                logger.getContext().getConfiguration().getLoggerConfig(sCategory)
                        .addAppender(consoleAppender, Level.OFF, null);
                System.out.println(logger.getContext().getConfiguration()
                        .getAppenders());

                return logger;

            }

            public static void main(String[] args) {

                MyLog4j2Logger logger = MyLog4j2Logger.getCustomLogger("TESTING");
                logger.debug("Debug MSG");
                logger.error("Error MSG");
                logger.info("INFO msg");

            }

        }

1 个答案:

答案 0 :(得分:0)

Log4j2中的AsyncLogger执行您的代码片段所做的一切(以及更多)。我会检查并为您的应用程序配置它以降低代码的复杂性。