private static <T, K extends ComponentBuilder <K>> void addAttributes (final ComponentBuilder <K> appender, final Map <String, T> attributes) { for (final Entry <String, T> entry : attributes.entrySet ()) { final String key = entry.getKey (); final T val = entry.getValue (); boolean isEnum = false; for (final Target target : ConsoleAppender.Target.values ()) if (target .name () .equalsIgnoreCase (val.toString ())) { appender.addAttribute (key, Target.valueOf (val.toString ())); isEnum = true; } if (!isEnum) { if (val instanceof Status) { appender.addAttribute (key, ((Status) val).getStatus ()); } else { appender.addAttribute (key, val); } } } }
@Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { // logging stuff. if (!FMLForgePlugin.RUNTIME_DEOBF) // not runtime deobf = dev env { String packageName = this.getClass().getPackage().getName(); Logger baseLogger = (Logger) LogManager.getLogger(packageName); ConsoleAppender appender = ConsoleAppender.createAppender(null, null, Target.SYSTEM_OUT.toString(), "console", "true", "false"); baseLogger.addAppender(appender); baseLogger.setLevel(Level.DEBUG); appender.start(); // testing levels.. for (Level l : Level.values()) { baseLogger.log(l, "TESTING {} on level {}", baseLogger.getName(), l); LogManager.getLogger().log(l, "TESTING {} on level {}", this.getClass().getName(), l); } } Configuration c = new Configuration(event.getSuggestedConfigurationFile()); OUR_SERVER = c.get("main", "globalbloodstain", 1, "Turn on global bloodstains?0=no, 1=yes").getInt() == 0 ? false : true; c.save(); }
@PluginFactory public static JLineConsoleAppender createAppender(@PluginElement("Layout") Layout<? extends Serializable> layout, @PluginElement("Filters") final Filter filter, @PluginAttribute("target") final String t, @PluginAttribute("name") final String name, @PluginAttribute("follow") final String follow, @PluginAttribute("ignoreExceptions") final String ignore) { if (name == null) { LOGGER.error("No name provided for ConsoleAppender"); return null; } if (layout == null) { layout = PatternLayout.newBuilder().build(); } final boolean isFollow = Boolean.parseBoolean(follow); final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); final Target target = t == null ? Target.SYSTEM_OUT : Target.valueOf(t); FactoryData data = new FactoryData(getStream(isFollow, target), layout); return new JLineConsoleAppender(name, layout, filter, getManager(isFollow, target, data), getHeldManager(isFollow, target, data), ignoreExceptions); }
private void testConsoleStreamManagerDoesNotClose(final PrintStream ps, final Target targetName, final SystemSetter systemSetter) { try { systemSetter.systemSet(psMock); final Layout<String> layout = PatternLayout.newBuilder().withAlwaysWriteExceptions(true).build(); final ConsoleAppender app = ConsoleAppender.newBuilder().withLayout(layout).setTarget(targetName) .withName("Console").withIgnoreExceptions(false).build(); app.start(); assertTrue("Appender did not start", app.isStarted()); final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("TestLogger") // .setLoggerFqcn(ConsoleAppenderTest.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Test")) // .build(); app.append(event); app.stop(); assertFalse("Appender did not stop", app.isStarted()); } finally { systemSetter.systemSet(ps); } then(psMock).should(atLeastOnce()).write(any(byte[].class), anyInt(), anyInt()); then(psMock).should(atLeastOnce()).flush(); }
public static ConsoleAppender createConsoleAppender(String name, Target target, String pattern){ PatternLayout layout = createLayout(pattern); return ConsoleAppender.newBuilder() .withLayout(layout) .setTarget(target) .withName(name) .build(); }
/** * Creates an instance of {@link ConsoleAppender}. * * @param layout the {@link PatternLayout} to use * @param name the name of the appender * @return an instance of {@link ConsoleAppender} */ protected static ConsoleAppender createConsoleAppender(PatternLayout layout, String name) { Filter filter = null; String targetStr = Target.SYSTEM_OUT.toString(); String follow = Boolean.FALSE.toString(); String ignore = Boolean.FALSE.toString(); return ConsoleAppender.createAppender(layout, filter, targetStr, name, follow, ignore); }
protected static OutputStream getStream(boolean follow, Target target) { OutputStream os; if (target == Target.SYSTEM_ERR) { os = follow ? new SystemErrStream() : new NeverClosingOutputStream(System.err); } else { os = follow ? new SystemOutStream() : new NeverClosingOutputStream(System.out); } return AnsiConsole.wrapOutputStream(os); }
private Layout<?> testConsole(final String configResource) throws Exception { final Configuration configuration = getConfiguration(configResource); final String name = "Console"; final ConsoleAppender appender = configuration.getAppender(name); assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration, appender); assertEquals(Target.SYSTEM_ERR, appender.getTarget()); // final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo"); assertNotNull(loggerConfig); assertEquals(Level.DEBUG, loggerConfig.getLevel()); configuration.start(); configuration.stop(); return appender.getLayout(); }
private void testFollowSystemPrintStream(final PrintStream ps, final Target target, final SystemSetter systemSetter) { final ConsoleAppender app = ConsoleAppender.newBuilder().setTarget(target).setFollow(true) .withIgnoreExceptions(false).withName("test").build(); Assert.assertEquals(target, app.getTarget()); app.start(); try { final LogEvent event = Log4jLogEvent.newBuilder() // .setLoggerName("TestLogger") // .setLoggerFqcn(ConsoleAppenderTest.class.getName()) // .setLevel(Level.INFO) // .setMessage(new SimpleMessage("Test")) // .build(); assertTrue("Appender did not start", app.isStarted()); systemSetter.systemSet(new PrintStream(baos)); try { app.append(event); } finally { systemSetter.systemSet(ps); } final String msg = baos.toString(); assertNotNull("No message", msg); assertTrue("Incorrect message: \"" + msg + "\"", msg.endsWith("Test" + Strings.LINE_SEPARATOR)); } finally { app.stop(); } assertFalse("Appender did not stop", app.isStarted()); }
public DatarouterLog4j2Configuration(){ Appender out = Log4j2Configurator.createConsoleAppender(CONSOLE_APPENDER_NAME, Target.SYSTEM_OUT, defaultPattern); addAppender(out); addLoggerConfig("", Level.WARN, false, out); //Indicate the root logger because blank name }
public void addConsoleAppender(String name, Target target, String pattern){ Appender appender = Log4j2Configurator.createConsoleAppender(name, target, pattern); addAppender(appender); }
@Test public void test() throws IOException{ logger.debug("hello"); logger.debug("password");//excluded by filter configurator.updateOrCreateLoggerConfig(getClass().getPackage(), Level.OFF, false, TestDatarouterLog4j2Configuration.TEST_APPENDER_NAME); logger.debug("goodbye");//excluded because Level is OFF configurator.updateOrCreateLoggerConfig(getClass(), Level.ALL, false, TestDatarouterLog4j2Configuration.TEST_APPENDER_NAME); logger.debug("foo"); configurator.updateOrCreateLoggerConfig(getClass().getName(), Level.ALL, false, (Iterable<String>)null); logger.debug("bar"); configurator.updateOrCreateLoggerConfig(getClass(), Level.ALL, false, "appender-not-found"); logger.debug("baz");//excluded because appender not found Assert.assertTrue(configurator.getConfigs().keySet().contains(getClass().getName())); configurator.deleteLoggerConfig(getClass().getName()); logger.debug("demat");//excluded because Level is OFF (package rule) Assert.assertFalse(configurator.getConfigs().keySet().contains(getClass().getName())); try(BufferedReader reader = new BufferedReader(new FileReader(TEST_FILE))){ Assert.assertTrue(reader.readLine().endsWith("hello")); Assert.assertTrue(reader.readLine().endsWith("foo")); Assert.assertTrue(reader.readLine().endsWith("bar")); Assert.assertNull(reader.readLine()); } Assert.assertNull(configurator.getAppender(TEST_APPENDER_2_NAME)); configurator.addFileAppender(TEST_APPENDER_2_NAME, TEST_FILE_2_NAME, BaseLog4j2Configuration.defaultPattern); Assert.assertNotNull(configurator.getAppender(TEST_APPENDER_2_NAME)); configurator.updateOrCreateLoggerConfig(getClass(), Level.ALL, false, TEST_APPENDER_2_NAME); logger.warn("degemer"); configurator.addConsoleAppender("second-console-appender", Target.SYSTEM_ERR, BaseLog4j2Configuration.defaultPattern); configurator.updateOrCreateLoggerConfig(getClass(), Level.ALL, false, ERR_CONSOLE_APPENDER_NAME); logger.warn("ar");//going to err console try(BufferedReader reader = new BufferedReader(new FileReader(TEST_FILE_2))){ Assert.assertTrue(reader.readLine().endsWith("degemer")); Assert.assertNull(reader.readLine()); } configurator.deleteAppender(TEST_APPENDER_2_NAME); Assert.assertNull(configurator.getAppender(TEST_APPENDER_2_NAME)); Assert.assertTrue(configurator.getAppenders().keySet().contains( TestDatarouterLog4j2Configuration.TEST_APPENDER_NAME)); Assert.assertTrue(configurator.getAppenders().keySet().contains( DatarouterLog4j2Configuration.CONSOLE_APPENDER_NAME)); Assert.assertEquals(configurator.getRootLoggerConfig().getName(), ""); }
public static void initialize(Application application) { // STORE APPLICATION FOR LATER USE Logging.application = application; // REDIRECT JAVA UTIL LOGGER TO LOG4J2 (MUST BE BEFORE ALL LOG4J2 CALLS) System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager"); // STARTING CONFIGURATION final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); org.apache.logging.log4j.core.config.Configuration configuration = loggerContext.getConfiguration(); LoggerConfig rootLogger = configuration.getLoggerConfig(""); rootLogger.setLevel(Level.ALL); // PATTERNS PatternLayout consolePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger{1}]: %msg%n", null, configuration, null, null, true, false, null, null); PatternLayout logfilePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger]: %msg%n", null, configuration, null, null, true, false, null, null); // LOG FILE STRINGS String logFilePrefix = PlatformData.installationDirectory.getAbsolutePath().replace("\\", "/") + "/logs/" + WordUtils.capitalizeFully(application.getName(), new char[] { '_', '-', ' ' }).replaceAll("_", "").replaceAll("_", "").replaceAll("-", "").replaceAll(" ", ""); // CLIENT LOG FILE APPENDER (ROLLING) RollingRandomAccessFileAppender clientInfoLogFile = RollingRandomAccessFileAppender.createAppender(logFilePrefix + "-0.log", logFilePrefix + "-%i.log", null, "InfoFile", null, null, OnStartupTriggeringPolicy.createPolicy(), DefaultRolloverStrategy.createStrategy("2", "1", "min", null, null, false, configuration), logfilePattern, null, null, null, null, configuration); clientInfoLogFile.start(); configuration.addAppender(clientInfoLogFile); rootLogger.addAppender(clientInfoLogFile, Level.INFO, null); // FINER DETAIL LOG FILE (REPLACED ON EACH RUN) RandomAccessFileAppender detailLogFile = RandomAccessFileAppender.createAppender(logFilePrefix + "-latest-fine.log", "false", "DetailFile", null, null, null, logfilePattern, null, null, null, configuration); detailLogFile.start(); configuration.addAppender(detailLogFile); rootLogger.addAppender(detailLogFile, Level.ALL, null); // CONSOLE APPENDER ConsoleAppender console = ConsoleAppender.createAppender(consolePattern, null, Target.SYSTEM_OUT, "Console", false, true); // must be named "Console" to work correctly console.start(); configuration.addAppender(console); rootLogger.addAppender(console, Level.INFO, null); // UPDATE LOGGERS loggerContext.updateLoggers(); // REDIRECT STDOUT AND STDERR TO LOG4J2 System.setOut(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.out"), Level.INFO))); System.setErr(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.err"), Level.ERROR))); // set main engine log log = LogManager.getLogger(); // print opening header log.info("==============================================================================================================="); log.info(" " + application.getName() + " v" + application.getVersion()); log.info(" (c) Robert James Dennington, " + Math.max(Calendar.getInstance().get(Calendar.YEAR), minCopyrightYear)); log.info("==============================================================================================================="); log.debug("The system log manager is " + System.getProperty("java.util.logging.manager")); log.info("Install path: " + PlatformData.installationDirectory.getAbsolutePath()); log.info("Computer name: " + PlatformData.computerName); log.info("Platform: " + PlatformData.platformName); }
protected static HookableOutputStreamManager getManager(boolean follow, Target target, FactoryData data) { return HookableOutputStreamManager.getHookableManager(target.name() + ".jline." + follow, data, FACTORY); }
protected static OutputStreamManager getHeldManager(boolean follow, Target target, FactoryData data) { return OutputStreamManager.getManager(target.name() + "." + follow, data, FACTORY); }
protected static HookableOutputStreamManager getManager(boolean follow, Target target, Layout<? extends Serializable> layout) { OutputStream stream; stream = getStream(follow, target); return HookableOutputStreamManager.getHookableManager(target.name() + ".jline." + follow, new FactoryData(stream, layout), FACTORY); }
@Test public void testFollowSystemErr() { testFollowSystemPrintStream(System.err, Target.SYSTEM_ERR, SystemSetter.SYSTEM_ERR); }
@Test public void testFollowSystemOut() { testFollowSystemPrintStream(System.out, Target.SYSTEM_OUT, SystemSetter.SYSTEM_OUT); }
@Test public void testSystemErrStreamManagerDoesNotClose() { testConsoleStreamManagerDoesNotClose(System.err, Target.SYSTEM_ERR, SystemSetter.SYSTEM_ERR); }
@Test public void testSystemOutStreamManagerDoesNotClose() { testConsoleStreamManagerDoesNotClose(System.out, Target.SYSTEM_OUT, SystemSetter.SYSTEM_OUT); }