@PUT @Path("/log/change-level/{loggerName}/{newLevel}") public Response changeLogLevel(@PathParam("loggerName") String loggerName, @PathParam("newLevel") String newLevel) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(loggerName); if (loggerConfig.getName().equals(LogManager.ROOT_LOGGER_NAME)) { return Response.ok("Not found", MediaType.TEXT_PLAIN).build(); } loggerConfig.setLevel(Level.valueOf(newLevel)); ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig. return Response.ok("Done", MediaType.TEXT_PLAIN).build(); }
private void toggleCleanLogging() { this.cleanLogging = !cleanLogging; interactionHandler.sendText("clean logging: " + cleanLogging); String appenderToAdd = cleanLogging ? "Clean" : "Console"; String appenderToRemove = cleanLogging ? "Console" : "Clean"; final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); for (org.apache.logging.log4j.core.Logger logger : ctx.getLoggers()) { logger.removeAppender(config.getAppender(appenderToRemove)); config.addLoggerAppender(logger, config.getAppender(appenderToAdd)); } ctx.updateLoggers(); }
@Setup public void start() { counter = 0; if (log == null) { System.setProperty( "Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); LoggerContext context = LoggerContext.getContext(); log = context.getLogger("Log4j2"); log.setAdditive(false); ArrayList<Appender> list = new ArrayList<Appender>(); list.addAll(log.getAppenders().values()); for (Appender a : list) { log.removeAppender(a); } } }
/** * Build logger context logger context. * * @param environment the environment * @param resourceLoader the resource loader * @return the logger context */ public static Pair<Resource, LoggerContext> buildLoggerContext(final Environment environment, final ResourceLoader resourceLoader) { try { final String logFile = environment.getProperty("logging.config", "classpath:/log4j2.xml"); LOGGER.debug("Located logging configuration reference in the environment as [{}]", logFile); if (ResourceUtils.doesResourceExist(logFile, resourceLoader)) { final Resource logConfigurationFile = resourceLoader.getResource(logFile); LOGGER.debug("Loaded logging configuration resource [{}]. Initializing logger context...", logConfigurationFile); final LoggerContext loggerContext = Configurator.initialize("CAS", null, logConfigurationFile.getURI()); LOGGER.debug("Installing log configuration listener to detect changes and update"); loggerContext.getConfiguration().addListener(reconfigurable -> loggerContext.updateLoggers(reconfigurable.reconfigure())); return Pair.of(logConfigurationFile, loggerContext); } LOGGER.warn("Logging configuration cannot be found in the environment settings"); } catch (final Exception e) { throw Throwables.propagate(e); } return null; }
public void watch(Class<?> loggerClass, Level level) { this.loggerClass = loggerClass; Appender appender = new AbstractAppender(APPENDER_NAME, null, PatternLayout.createDefaultLayout()) { @Override public void append(LogEvent event) { logEvents.add(event); } }; appender.start(); final LoggerContext ctx = getLoggerContext(); LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(loggerClass.getName()); oldLevel = loggerConfig.getLevel(); loggerConfig.setLevel(level); loggerConfig.addAppender(appender, level, null); ctx.updateLoggers(); }
public static LoggerConfig getOrCreateLoggerConfig(String name) { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); LoggerConfig logConfig = config.getLoggerConfig(name); boolean update = false; if (!logConfig.getName().equals(name)) { List<AppenderRef> appenderRefs = logConfig.getAppenderRefs(); Map<Property, Boolean> properties = logConfig.getProperties(); Set<Property> props = properties == null ? null : properties.keySet(); logConfig = LoggerConfig.createLogger(String.valueOf(logConfig.isAdditive()), logConfig.getLevel(), name, String.valueOf(logConfig.isIncludeLocation()), appenderRefs == null ? null : appenderRefs.toArray(new AppenderRef[appenderRefs.size()]), props == null ? null : props.toArray(new Property[props.size()]), config, null); config.addLogger(name, logConfig); update = true; } if (update) { context.updateLoggers(); } return logConfig; }
public static LoggerConfig getOrCreateLoggerConfig(String name, boolean additive, boolean forceAdditivity) { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); LoggerConfig logConfig = config.getLoggerConfig(name); boolean update = false; if (!logConfig.getName().equals(name)) { List<AppenderRef> appenderRefs = logConfig.getAppenderRefs(); Map<Property, Boolean> properties = logConfig.getProperties(); Set<Property> props = properties == null ? null : properties.keySet(); logConfig = LoggerConfig.createLogger(String.valueOf(additive), logConfig.getLevel(), name, String.valueOf(logConfig.isIncludeLocation()), appenderRefs == null ? null : appenderRefs.toArray(new AppenderRef[appenderRefs.size()]), props == null ? null : props.toArray(new Property[props.size()]), config, null); config.addLogger(name, logConfig); update = true; } if (forceAdditivity && logConfig.isAdditive() != additive) { logConfig.setAdditive(additive); update = true; } if (update) { context.updateLoggers(); } return logConfig; }
@AfterClass public static void tearDownAfterClass() throws Exception { for (Handler handler : saveHandlers) { julLogger.addHandler(handler); } if (saveLog4j2Config == null) { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); } else { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, saveLog4j2Config); ((LoggerContext) LogManager.getContext(false)).reconfigure(); } if (saveUserDir == null) { System.clearProperty("user.dir"); } else { System.setProperty("user.dir", saveUserDir); } if (saveUserHome == null) { System.clearProperty("user.home"); } else { System.setProperty("user.home", saveUserHome); } }
/** * Add an appender to Log4j which sends all INFO+ messages to a separate file which will be used * later to scan for suspect strings. The pattern of the messages conforms to the original log * format so that hydra will be able to parse them. */ private static void addSuspectFileAppender(final String workspaceDir) { final String suspectFilename = new File(workspaceDir, SUSPECT_FILENAME).getAbsolutePath(); final LoggerContext appenderContext = ((org.apache.logging.log4j.core.Logger) LogManager.getLogger(LogService.BASE_LOGGER_NAME)) .getContext(); final PatternLayout layout = PatternLayout.createLayout( "[%level{lowerCase=true} %date{yyyy/MM/dd HH:mm:ss.SSS z} <%thread> tid=%tid] %message%n%throwable%n", null, null, null, Charset.defaultCharset(), true, false, "", ""); final FileAppender fileAppender = FileAppender.createAppender(suspectFilename, "true", "false", DUnitLauncher.class.getName(), "true", "false", "false", "0", layout, null, null, null, appenderContext.getConfiguration()); fileAppender.start(); LoggerConfig loggerConfig = appenderContext.getConfiguration().getLoggerConfig(LogService.BASE_LOGGER_NAME); loggerConfig.addAppender(fileAppender, Level.INFO, null); }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("i", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(MaPsarStrategy.class, new Integer[]{12, 500, 2}, new String[]{MA.MODE_EMA, MA.MODE_SMMA}, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.1f, 0.2f, 0.02f}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.DAY, "19980101 000000", "20160916 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(ChannelBreakStrategy.class, new Integer[]{4, 800, 2}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + entry.getValue().ProfitRatio + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("m", TIME_FRAME.MIN60, "19980101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(DblMaPsarStrategy.class, new Integer[]{3, 5, 1}, new Integer[]{10, 100, 2}, MA.MA_MODES, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.12f, 0.2f, 0.02f}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(MABreakStrategy.class, new Integer[]{8, 800, 2}, MA.MA_MODES); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
/** * We cannot presume that the default file name/location setting won't be changed by the user. * Therefore, we should be able to retrieve that info from the underlying logging mechanism * by iterating over appenders. */ private List<Path> getActiveLogFilePaths() { LoggerContextFactory factory = LogManager.getFactory(); ContextSelector selector = ((Log4jContextFactory) factory).getSelector(); List<Path> fileNameList = new ArrayList<>(); for (LoggerContext ctx : selector.getLoggerContexts()) { for (Appender appender : ctx.getConfiguration().getAppenders().values()) { String fileName = extractFileName(appender); if (fileName != null) { fileNameList.add(Paths.get(fileName)); } } } return fileNameList; }
public KafkaManager(final LoggerContext loggerContext, final String name, final String topic, final String zkServers, final String mail, final String rpc, final String app, final String host, final Property[] properties) { super(loggerContext, name); this.topic = topic; this.zkServers = zkServers; this.mail = mail; this.rpc = rpc; this.app = app; this.orginApp = app; this.host = host; this.checkAndSetConfig(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); this.checkAndSetConfig(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 设置分区类, 使用自定义的KeyModPartitioner,同样的key进入相同的partition this.checkAndSetConfig(ProducerConfig.PARTITIONER_CLASS_CONFIG, KeyModPartitioner.class.getName()); // xml配置里面的参数 for (final Property property : properties) { this.config.put(property.getName(), property.getValue()); } // 由于容器部署需要从外部获取host this.config.put(ProducerConfig.CLIENT_ID_CONFIG, this.app + Constants.MIDDLE_LINE + this.host + Constants.MIDDLE_LINE + "log4j2"); }
/** * Setup the file logger so that it outputs messages to the appropriately named file, * depending on the subtitle of the current program instance. */ private static void configureLoggers( String subtitle ) { // Remove all characters that are not allowed for Windows filenames. subtitle = subtitle.replaceAll( "[\\s" + Pattern.quote( "\\/:*?\"<>|" ) + "]", "" ); LoggerContext context = (LoggerContext)LogManager.getContext(); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.createLayout( "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%throwable%n", null, null, null, Charset.defaultCharset(), false, false, null, null ); FileAppender appender = FileAppender.createAppender( "logs/log-" + subtitle + ".txt", "false", "false", "LogFile-" + subtitle, "true", "true", "true", "8192", layout, null, "false", "", config ); org.apache.logging.log4j.core.Logger rootLogger = (org.apache.logging.log4j.core.Logger)LogManager.getRootLogger(); rootLogger.addAppender( appender ); appender.start(); }
public LindenServer(String conf) throws Exception { File lindenProperties = new File(FilenameUtils.concat(conf, LINDEN_PROPERTIES)); File schemaXml = new File(FilenameUtils.concat(conf, SCHEMA_XML)); Preconditions.checkArgument(lindenProperties.exists(), "can not find linden.properties."); lindenConf = LindenConfigBuilder.build(lindenProperties); if (schemaXml.exists()) { LindenSchema schema = LindenSchemaBuilder.build(schemaXml); lindenConf.setSchema(schema); } else { throw new Exception("schema.xml not found."); } port = lindenConf.getPort(); Preconditions.checkNotNull(lindenConf.getLogPath(), "log path can not be null."); System.setProperty(LOG_PATH, lindenConf.getLogPath()); System.setProperty(LOG4J_SHUTDOWN_HOOK_ENABLED, "false"); System.setProperty(LOG4J_CONTEXT_SELECTOR, "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.setConfigLocation(new File(FilenameUtils.concat(conf, LOG4j2_XML)).toURI()); ctx.reconfigure(); LOGGER = LoggerFactory.getLogger(LindenServer.class); }
@Override public void applyDelegate(Config config) { Security.addProvider(new BouncyCastleProvider()); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration ctxConfig = ctx.getConfiguration(); LoggerConfig loggerConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); if (isDebug()) { loggerConfig.setLevel(Level.DEBUG); } else if (isQuiet()) { loggerConfig.setLevel(Level.OFF); } else if (getLogLevel() != null) { loggerConfig.setLevel(getLogLevel()); } ctx.updateLoggers(); LOGGER.debug("Using the following security providers"); for (Provider p : Security.getProviders()) { LOGGER.debug("Provider {}, version, {}", p.getName(), p.getVersion()); } // remove stupid Oracle JDK security restriction (otherwise, it is not // possible to use strong crypto with Oracle JDK) UnlimitedStrengthEnabler.enable(); }
@Override protected void setUp() throws Exception { super.setUp(); initLogFormatter(); System.getProperties().setProperty(Logging.LOG_CLASS_NAME, "com.devexperts.logging.Log4j2Logging"); // Create log file in folder that will be eventually cleared - "deleteOnExit" does not work for log files. BUILD_TEST_DIR.mkdirs(); logFile = File.createTempFile("test.", ".log", BUILD_TEST_DIR); final Properties props = new Properties(); props.load(Log4jCompatibilityTest.class.getResourceAsStream("/test.log4j2.properties")); props.setProperty("appender.file.fileName", logFile.getPath()); LoggerContext context = (LoggerContext)LogManager.getContext(false); ConfigurationFactory.setConfigurationFactory(new PropertiesConfigurationFactory() { @Override public PropertiesConfiguration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { return new PropertiesConfigurationBuilder() .setConfigurationSource(source) .setRootProperties(props) .setLoggerContext(loggerContext) .build(); } }); context.setConfigLocation(Log4jCompatibilityTest.class.getResource("/test.log4j2.properties").toURI()); }
private static void addFileAppender() throws IOException { final String tempDir = System.getProperty("java.io.tmpdir"); final File logFile = new File(tempDir, "meghanada_server.log"); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final Configuration configuration = context.getConfiguration(); final LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); final FileAppender fileAppender = FileAppender.newBuilder() .withName("file") .withLayout( PatternLayout.newBuilder() .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n") .build()) .withFileName(logFile.getCanonicalPath()) .build(); configuration.addAppender(fileAppender); loggerConfig.addAppender(fileAppender, Level.ERROR, null); context.updateLoggers(); }
/** * This test asserts that after re-configuration of the log engine the total appenders are * different. The 'comparison' will be done between: * * - default config (src/main/resources/log4j2.xml) * - alternative config (src/test/resources/xml/config-for-LogManagerTest.xml) */ @Test (groups = { GROUP_CHANGE_CONFIG }, description = "Validate the numbers of Appenders associated with the LoggerContext") public void testLogReconfiguration() { LOGGER.debug("About to test re-configuration of the logger context"); final String pathToAlternativeLogConfig = "src/test/resources/config/log/config-for-LogManagerTest.xml"; LoggerContext loggerContext = LoggerContext.getContext(false); Configuration configuration = loggerContext.getConfiguration(); Map<String, Appender> appenderMap = configuration.getAppenders(); Assert.assertTrue(appenderMap.size() == 1, "Expected 1 appender"); Assert.assertTrue(appenderMap.containsKey("console")); LogManager.initializeLogging(pathToAlternativeLogConfig); // Refresh reference of configuration as it changed configuration = loggerContext.getConfiguration(); appenderMap = configuration.getAppenders(); Assert.assertTrue(appenderMap.size() == 2, "Expected 2 appenders"); Assert.assertTrue(appenderMap.containsKey("console")); Assert.assertTrue(appenderMap.containsKey("filterAppender")); }
/** * Update the log configuration based on command line options * * @param cl */ protected final void updateLogConfig(CommandLine cl) { String logFile = cl.getOptionValue(OPT_LOG_FILE.getLongOpt(), null); String logLevel = cl.getOptionValue(OPT_LOG_LEVEL.getLongOpt(), null); if (logFile != null || logLevel != null) { logFile = logFile != null ? logFile : getDefaultLogFileName(); logLevel = logLevel != null ? logLevel : DEFAULT_LOG_LEVEL; LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration configuration = context.getConfiguration(); FileAppender appender = FileAppender.newBuilder() .withName("File") .withFileName(logFile) .withLayout(PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build()) .withAppend(false) .build(); appender.start(); configuration.getRootLogger().addAppender(appender, Level.getLevel(logLevel), null); configuration.getRootLogger().setLevel(Level.getLevel(logLevel)); context.updateLoggers(); } }
protected void configureLogging() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, config, null, null, true, false, null, null); Appender appender = FileAppender.createAppender(workDir + "/logs/camel-standalone.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "StandaloneFileLoggerConfig", "true", refs, null, config, null ); loggerConfig.addAppender(appender, null, null); config.addLogger("StandaloneFileLoggerConfig", loggerConfig); ctx.updateLoggers(); }
@POST @Path("/getLevels") @Produces("application/json") public JsonLogLevels getLogLevels() { List<JsonLogLevel> logLevels = new ArrayList<>(); Logger rootLogger = LogManager.getRootLogger(); if (rootLogger instanceof org.apache.logging.log4j.core.Logger) { LoggerContext lc = ((org.apache.logging.log4j.core.Logger) rootLogger).getContext(); Collection<org.apache.logging.log4j.core.Logger> loggers = lc.getLoggers(); for (Logger logger : loggers) { addToLogLevels(logger, logLevels); } } else { LOG.warn("Cannot get log level because root logger is not an instance of org.apache.logging.log4j.core.Logger"); } addToLogLevels(rootLogger, logLevels); return new JsonLogLevels(logLevels); }
protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); if (logFile != null) { logFile.applyToSystemProperties(); } try { LoggerContext ctx = getLoggerContext(); URL url = ResourceUtils.getURL(location); ConfigurationSource source = getConfigurationSource(url); ctx.start(ConfigurationFactory.getInstance().getConfiguration(source)); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize Log4J2 logging from " + location, ex); } }
@Override public StringWriter addLoggingWriterAppender(String appenderName) { // Get the configuration final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); final Configuration configuration = loggerContext.getConfiguration(); // Create a string writer as part of the appender so logging will be written to it. StringWriter stringWriter = new StringWriter(); // Create and start the appender with the string writer. Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true); appender.start(); // Add the appender to the root logger. configuration.getRootLogger().addAppender(appender, null, null); // Return the string writer. return stringWriter; }
private static Logger configureLog4j() { LoggerContext context = (LoggerContext) LogManager.getContext(); Configuration config = context.getConfiguration(); PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null); Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null); AppenderRef[] refs = new AppenderRef[]{ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null); loggerConfig.addAppender(appender, null, null); config.addAppender(appender); config.addLogger("Main.class", loggerConfig); context.updateLoggers(config); return LogManager.getContext().getLogger("Main.class"); }
/** * Tests that {@link oc.io.base.DecoupledInputStream#read()} terminates * normally when IOException is thrown in wrapped InputStream * * @throws IOException */ @Test public void testReadException() throws IOException { final byte b[] = new byte[1]; // Temporary disable logging for avoiding annoying Exception trace final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); final Level currentLevel = loggerConfig.getLevel(); loggerConfig.setLevel(Level.FATAL); ctx.updateLoggers(); final TestInputStream testInputStream = new TestInputStream(new IOException( "This exception is thrown due to a test scenario. This is expected behaviour")); final DecoupledInputStream decInputStream = new DecoupledInputStream(testInputStream); assertEquals(-1, decInputStream.read(b)); decInputStream.close(); loggerConfig.setLevel(currentLevel); ctx.updateLoggers(); }
public static void bindLogger() { LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); Map<String, ESLogger> loggers = Maps.newConcurrentHashMap(); Appender appender = new AbstractAppender("", null, null) { @Override public void append(LogEvent event) { String name = event.getLoggerName(); ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key))); logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown()); } }; appender.start(); config.addAppender(appender); LoggerConfig loggerConfig = new LoggerConfig("", Level.ALL, false); loggerConfig.addAppender(appender, null, null); config.addLogger("", loggerConfig); context.updateLoggers(); }
@Before public void setup() throws Exception { // Create mock objects mockLog4jContextFactory = mock(Log4jContextFactory.class); whenNew(Log4jContextFactory.class).withNoArguments().thenReturn(mockLog4jContextFactory); mockLoggerContext = mock(LoggerContext.class); mockLogger = mock(Logger.class); when(mockLog4jContextFactory.getContext(anyString(), any(ClassLoader.class), any(), anyBoolean(), any(URI.class), anyString())).thenReturn(mockLoggerContext); when(mockLoggerContext.getRootLogger()).thenReturn(mockLogger); mockRequest = mock(Request.class); mockResponse = mock(Response.class); mockAccessLog = mock(AccessLog.class); whenNew(AccessLog.class).withArguments(mockRequest, mockResponse).thenReturn(mockAccessLog); // Create actual objects enabledSupplier = () -> true; disabledSupplier = () -> false; failedAccessLog = new TestLog4JAccessLog(NON_EXISTING_FILE_PATH, enabledSupplier); String filePath = getClass().getClassLoader().getResource(ACCESS_CONFIG_FILE_PATH).getPath(); enabledAccessLog = new TestLog4JAccessLog(filePath, enabledSupplier); disabledAccessLog = new TestLog4JAccessLog(filePath, disabledSupplier); }
public static void main(String[] args) throws UnRetriableException{ LoggerContext ctx = (LoggerContext) LogManager.getContext(false); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout()); appender.start(); config.addAppender(appender); AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); Runner runner = defaultRunner(); runner.init(); runner.start(); }
public static void main(String[] args) throws UnRetriableException { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration(); ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout()); appender.start(); config.addAppender(appender); AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.WARN, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); Runner runner = defaultRunner(); runner.init(); runner.start(); }
/** {@inheritDoc} */ @Override public void setNodeId(UUID nodeId) { A.notNull(nodeId, "nodeId"); this.nodeId = nodeId; // Set nodeId as system variable to be used at configuration. System.setProperty(NODE_ID, U.id8(nodeId)); if (inited) { final LoggerContext ctx = impl.getContext(); synchronized (mux) { inited = false; } addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() { @Override public Logger apply(Boolean init) { if (init) ctx.reconfigure(); return (Logger)LogManager.getRootLogger(); } }); } }
@Override public void setLogLevel(String category, String level) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); LoggerConfig loggerConfig = getLoggerConfig(ctx, category); if (loggerConfig != null) { boolean madeChanges = false; if (level == null || "unset".equals(level) || "null".equals(level)) { level = Level.OFF.toString(); loggerConfig.setLevel(Level.OFF); madeChanges = true; } else { try { loggerConfig.setLevel(Level.valueOf(level)); madeChanges = true; } catch (IllegalArgumentException iae) { watcherLog.error(level+" is not a valid log level! Valid values are: "+getAllLevels()); } } if (madeChanges) { ctx.updateLoggers(); watcherLog.info("Set log level to '" + level + "' for category: " + category); } } else { watcherLog.warn("Cannot set level to '" + level + "' for category: " + category + "; no LoggerConfig found!"); } }