public static PatternLayout createLayout(String logFormat) throws ReflectiveOperationException { try { Method builder = PatternLayout.class .getDeclaredMethod("createLayout", String.class, Configuration.class, RegexReplacement.class , String.class, String.class); return (PatternLayout) builder.invoke(null, logFormat, new DefaultConfiguration(), null , Charset.defaultCharset().name(), "true"); } catch (NoSuchMethodException methodEx) { return PatternLayout.newBuilder() .withCharset(Charset.defaultCharset()) .withPattern(logFormat) .withConfiguration(new DefaultConfiguration()) .withAlwaysWriteExceptions(true) .build(); } }
@BeforeClass public static void setupClass() { final Configuration config = ((LoggerContext)LogManager.getContext()).getConfiguration(); if (!DefaultConfiguration.DEFAULT_NAME.equals(config.getName())) { System.out.println("Configuration was " + config.getName()); ((LoggerContext)LogManager.getContext()).start(new DefaultConfiguration()); } for (int i=0; i < WARMUP; ++i) { overhead(); } System.gc(); final Timer timer = new Timer("Setup", LOOP_CNT); timer.start(); for (int i=0; i < (LOOP_CNT / 150); ++i) { overhead(); } timer.stop(); maxTime = timer.getElapsedNanoTime(); System.gc(); System.out.println(timer.toString()); }
protected void setUp(final String tableName, final String configFileName) throws SQLException { this.connection = this.newConnection(); final Statement statement = this.connection.createStatement(); try { statement.executeUpdate(this.toCreateTableSqlString(tableName)); } finally { statement.close(); } System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "org/apache/logging/log4j/core/appender/db/jdbc/" + configFileName); final LoggerContext context = (LoggerContext) LogManager.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); }
@Setup public void setup() throws Exception { connectionHSQLDB = getConnectionHSQLDB(); connectionH2 = getConnectionH2(); createTable(connectionHSQLDB, toCreateTableSqlStringHQLDB("fmLogEntry")); createTable(connectionH2, toCreateTableSqlStringH2("fmLogEntry")); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jdbc-appender.xml"); final LoggerContext context = LoggerContext.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); loggerH2 = LogManager.getLogger("H2Logger"); loggerHSQLDB = LogManager.getLogger("HSQLDBLogger"); }
@BeforeClass public static void setupClass() { final Configuration config = LoggerContext.getContext().getConfiguration(); if (!DefaultConfiguration.DEFAULT_NAME.equals(config.getName())) { System.out.println("Configuration was " + config.getName()); LoggerContext.getContext().start(new DefaultConfiguration()); } for (int i=0; i < WARMUP; ++i) { overhead(); } System.gc(); final Timer timer = new Timer("Setup", LOOP_CNT); timer.start(); for (int i=0; i < (LOOP_CNT / 150); ++i) { overhead(); } timer.stop(); maxTime = timer.getElapsedNanoTime(); System.gc(); System.out.println(timer.toString()); }
@Test public void testSelectFilesToDelete2() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager final List<PathWithAttributes> pathList = new ArrayList<>(); pathList.add(new PathWithAttributes(Paths.get("/path/1"), new DummyFileAttributes())); pathList.add(new PathWithAttributes(Paths.get("/path/2"), new DummyFileAttributes())); pathList.add(new PathWithAttributes(Paths.get("/path/3"), new DummyFileAttributes())); final String scriptText = "pathList.remove(1);" // + "pathList;"; final Script script = new Script("test", "javascript", scriptText); final ScriptCondition condition = new ScriptCondition(script, config); final Path base = Paths.get("baseDirectory"); final List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList); assertSame(result, pathList); assertEquals(2, result.size()); assertEquals(Paths.get("/path/1"), result.get(0).getPath()); assertEquals(Paths.get("/path/3"), result.get(1).getPath()); }
@Override public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { if (source != null && source != ConfigurationSource.NULL_SOURCE) { if (LoggingSystem.get(loggerContext.getClass().getClassLoader()) != null) { return new DefaultConfiguration(); } } return null; }
private boolean loadLogAppender() { Logger log = (Logger)LogManager.getRootLogger(); for(Appender appender : log.getAppenders().values()) { if(appender instanceof RConsoleAppender) log.removeAppender(appender); } mAppender = new RConsoleAppender(new DefaultConfiguration()); mAppender.start(); log.addAppender(mAppender); return true; }
@Test public void testReconfiguration() throws Exception { final Configuration cfg = ctx.getConfiguration(); assertNotNull("No configuration", cfg); assertTrue("Not set to default configuration", cfg instanceof DefaultConfiguration); final File file = new File(CONFIG); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(null, false, file.toURI()); assertNotNull("No Logger Context", loggerContext); final Configuration newConfig = loggerContext.getConfiguration(); assertTrue("Configuration not reset", cfg != newConfig); assertTrue("Reconfiguration failed", newConfig instanceof XMLConfiguration); ctx = (LoggerContext) LogManager.getContext(false); final Configuration sameConfig = ctx.getConfiguration(); assertTrue("Configuration should not have been reset", newConfig == sameConfig); }
public void setUp(final String configFileName) throws SQLException { this.connection = this.setUpConnection(); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "org/apache/logging/log4j/core/appender/db/jpa/" + configFileName); final LoggerContext context = (LoggerContext) LogManager.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); }
public static void addFileAppender(String filename) { if (instance == null) { LOGGER.error("CustomFileAppender hasn't been initalized, ignoring output " + filename); return; } final AbstractOutputStreamAppender<? extends OutputStreamManager> appender; if (mmap_appender) appender = MemoryMappedFileAppender.createAppender(filename, "false", filename, "false", "8192", "false", instance.getLayout(), instance.getFilter(), "false", "false", new DefaultConfiguration()); else appender = FileAppender.createAppender(filename, "false", "false", filename, "false", "false", "true", "8192", instance.getLayout(), instance.getFilter(), "false", "false", new DefaultConfiguration()); LOGGER.info("registering custom logfile '{}'", appender); instance.appenders.add(appender); }
protected String log(String pattern, MuleMessage message) { logger.info(message); assertThat(testLogAppender.getEvents().size(), is(1)); Configuration configuration = new DefaultConfiguration(); configuration.getPluginPackages().add(CONVERTER_PACKAGE); PatternLayout layout = PatternLayout.createLayout(pattern, configuration, null, null, true, false, null, null); return layout.toSerializable(testLogAppender.getEvents().iterator().next()); }
@Test public void createLayout_normal_combinedPatternUsed() { DefaultConfiguration configuration = new DefaultConfiguration(); configuration.getPluginPackages().add(AbstractAccessLogConverter.class.getPackage().getName()); Layout layout = CombinedAccessLogPatternLayout.createLayout(null, configuration, null, false, false, null, null); PatternLayout patternLayout = (PatternLayout) layout; assertThat(patternLayout.getConversionPattern(), is(CombinedAccessLogPatternLayout.PATTERN)); }
@Test public void createLayout_normal_commonLogPatternUsed() { DefaultConfiguration configuration = new DefaultConfiguration(); configuration.getPluginPackages().add(AbstractAccessLogConverter.class.getPackage().getName()); Layout layout = CommonAccessLogPatternLayout.createLayout(null, configuration, null, false, false, null, null); PatternLayout patternLayout = (PatternLayout) layout; assertThat(patternLayout.getConversionPattern(), is(CommonAccessLogPatternLayout.PATTERN)); }
@Setup public void setup() throws Exception { connectionHSQLDB = getConnectionHSQLDB(); connectionH2 = getConnectionH2(); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "log4j2-jpa-appender.xml"); final LoggerContext context = LoggerContext.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); loggerH2 = LogManager.getLogger("H2Logger"); loggerHSQLDB = LogManager.getLogger("HSQLDBLogger"); }
/** */ private static PatternFormatter[] createFormatters() { final Configuration config = new DefaultConfiguration(); final PatternParser parser = new PatternParser(config, "Converter", LogEventPatternConverter.class); final List<PatternFormatter> result = parser.parse(LOG4JPATTERN, false, true); return result.toArray(new PatternFormatter[result.size()]); }
@Setup public void setup() { final Configuration config = (LoggerContext.getContext()).getConfiguration(); if (!DefaultConfiguration.DEFAULT_NAME.equals(config.getName())) { System.out.println("Configuration was " + config.getName()); (LoggerContext.getContext()).start(new DefaultConfiguration()); } logger = LogManager.getLogger(SimpleBenchmark.class.getName()); }
public void setUp(final String configFileName) throws SQLException { this.connection = this.setUpConnection(); final String resource = "org/apache/logging/log4j/jpa/appender/" + configFileName; assertNotNull(getClass().getClassLoader().getResource(resource)); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, resource); PropertiesUtil.getProperties().reload(); final LoggerContext context = LoggerContext.getContext(false); if (context.getConfiguration() instanceof DefaultConfiguration) { context.reconfigure(); } StatusLogger.getLogger().reset(); }
private void maybeStartHelper(final Configuration config) { // If no log4j configuration was found, there are no loggers // and there is no point in starting the disruptor (which takes up // significant memory and starts a thread). if (config instanceof DefaultConfiguration) { StatusLogger.getLogger().debug("[{}] Not starting Disruptor for DefaultConfiguration.", getName()); } else { loggerDisruptor.start(); } }
@Test public void testReconfiguration() throws Exception { final Configuration cfg = context.getConfiguration(); assertNotNull("No configuration", cfg); assertTrue("Not set to default configuration", cfg instanceof DefaultConfiguration); final File file = new File(CONFIG); final LoggerContext loggerContext = LoggerContext.getContext(null, false, file.toURI()); assertNotNull("No Logger Context", loggerContext); final Configuration newConfig = loggerContext.getConfiguration(); assertTrue("Configuration not reset", cfg != newConfig); assertTrue("Reconfiguration failed", newConfig instanceof XmlConfiguration); context = LoggerContext.getContext(false); final Configuration sameConfig = context.getConfiguration(); assertTrue("Configuration should not have been reset", newConfig == sameConfig); }
@Test public void testDefaultLayout() throws Exception { // @formatter:off Assert.assertNotNull(RollingFileAppender.newBuilder() .withName(RollingFileAppenderLayoutTest.class.getName()) .setConfiguration(new DefaultConfiguration()) .withFileName("log.txt") .withFilePattern("FilePattern") .withPolicy(OnStartupTriggeringPolicy.createPolicy(1)) .withCreateOnDemand(true) // no need to clutter up test folder with another file .build().getLayout()); // @formatter:on }
@Test public void testPolicy() throws Exception { final Configuration configuration = new DefaultConfiguration(); final Path target = Paths.get(TARGET_FILE); target.toFile().getParentFile().mkdirs(); final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24); final String expectedDate = formatter.format(timeStamp); final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX; final Path rolled = Paths.get(rolledFileName); final long copied; try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) { copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING); } final long size = Files.size(target); assertTrue(size > 0); assertEquals(copied, size); Assert.assertTrue(target.toFile().setLastModified(timeStamp)); final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg").withConfiguration(configuration) .build(); final RolloverStrategy strategy = DefaultRolloverStrategy.createStrategy(null, null, null, "0", null, true, configuration); final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1); try (final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true, false, policy, strategy, null, layout, 8192, true, false, null, null, null, configuration)) { manager.initialize(); final String files = Arrays.toString(new File(TARGET_FOLDER).listFiles()); assertTrue(target.toString() + ", files = " + files, Files.exists(target)); assertEquals(target.toString(), 0, Files.size(target)); assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled)); assertEquals(rolled.toString(), size, Files.size(rolled)); } }
@Test public void testSelectFilesToDelete() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager final Script script = new Script("test", "javascript", "pathList;"); // script that returns pathList final ScriptCondition condition = new ScriptCondition(script, config); final List<PathWithAttributes> pathList = new ArrayList<>(); final Path base = Paths.get("baseDirectory"); final List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList); assertSame(result, pathList); }
@Test @Category(Scripts.Groovy.class) public void testSelectFilesToDelete3() { final Configuration config = new DefaultConfiguration(); config.initialize(); // creates the ScriptManager final List<PathWithAttributes> pathList = new ArrayList<>(); pathList.add(new PathWithAttributes(Paths.get("/path/1/abc/a.txt"), new DummyFileAttributes())); pathList.add(new PathWithAttributes(Paths.get("/path/2/abc/bbb.txt"), new DummyFileAttributes())); pathList.add(new PathWithAttributes(Paths.get("/path/3/abc/c.txt"), new DummyFileAttributes())); final String scriptText = "" // + "import java.nio.file.*;" // + "def pattern = ~/(\\d*)[\\/\\\\]abc[\\/\\\\].*\\.txt/;" // + "assert pattern.getClass() == java.util.regex.Pattern;" // + "def copy = pathList.collect{it};" + "pathList.each { pathWithAttribs -> \n" // + " def relative = basePath.relativize pathWithAttribs.path;" // + " println 'relative path: ' + relative;" // + " def str = relative.toString();" + " def m = pattern.matcher(str);" // + " if (m.find()) {" // + " def index = m.group(1) as int;" // + " println 'extracted index: ' + index;" // + " def isOdd = (index % 2) == 1;" + " println 'is odd: ' + isOdd;" // + " if (isOdd) { copy.remove pathWithAttribs}" + " }" // + "}" // + "println copy;" + "copy;"; final Script script = new Script("test", "groovy", scriptText); final ScriptCondition condition = new ScriptCondition(script, config); final Path base = Paths.get("/path"); final List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList); assertEquals(1, result.size()); assertEquals(Paths.get("/path/2/abc/bbb.txt"), result.get(0).getPath()); }
@Test public void testIncludeLocationDefaultsToFalse() { final LoggerConfig rootLoggerConfig = AsyncLoggerConfig.RootLogger.createLogger( null, "INFO", null, new AppenderRef[0], null, new DefaultConfiguration(), null); assertFalse("Include location should default to false for async logggers", rootLoggerConfig.isIncludeLocation()); final LoggerConfig loggerConfig = AsyncLoggerConfig.createLogger( null, "INFO", "com.foo.Bar", null, new AppenderRef[0], null, new DefaultConfiguration(), null); assertFalse("Include location should default to false for async logggers", loggerConfig.isIncludeLocation()); }
@Override public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { return new DefaultConfiguration(); }
private static PatternLayout getLayout(String pattern) { Configuration config = new DefaultConfiguration(); config.getPluginPackages().add(AbstractAccessLogConverter.class.getPackage().getName()); return PatternLayout.createLayout(pattern, config, null, null, true, false, null, null); }
@Test(expected = NullPointerException.class) public void testConstructorDisallowsNullScript() { new ScriptCondition(null, new DefaultConfiguration()); }
@Test public void testCreateConditionReturnsNullForNullScript() { assertNull(ScriptCondition.createCondition(null, new DefaultConfiguration())); }
/** * Creates a JSON Layout using the default settings. Useful for testing. * * @return A JSON Layout. */ public static ExtendedJsonLayout createDefaultLayout() { return new ExtendedJsonLayout(new DefaultConfiguration(), false, false, false, false, false, false, DEFAULT_HEADER, DEFAULT_FOOTER, StandardCharsets.UTF_8, true, DEFAULT_JSON_EXTENDER_CLASS); }
/** * Creates a JSON Layout using the default settings. Useful for testing. * * @return A JSON Layout. */ public static JsonLayout createDefaultLayout() { return new JsonLayout(new DefaultConfiguration(), false, false, false, false, false, false, DEFAULT_HEADER, DEFAULT_FOOTER, StandardCharsets.UTF_8, true, false, false, null, false); }
/** * Creates a YAML Layout using the default settings. Useful for testing. * * @return A YAML Layout. */ public static AbstractJacksonLayout createDefaultLayout() { return new YamlLayout(new DefaultConfiguration(), false, false, false, false, false, DEFAULT_HEADER, DEFAULT_FOOTER, StandardCharsets.UTF_8, true, false, false, null); }