@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(); }
/** * Looks up the logger in the logger factory, * and attempts to find the real logger instance * based on the underlying logging framework * and retrieve the logger object. Then, updates the level. * This functionality at this point is heavily dependant * on the log4j API. * * @param loggerName the logger name * @param loggerLevel the logger level * @param additive the additive nature of the logger * @param request the request * @param response the response * @throws Exception the exception */ @PostMapping(value = "/updateLoggerLevel") @ResponseBody public void updateLoggerLevel(@RequestParam final String loggerName, @RequestParam final String loggerLevel, @RequestParam(defaultValue = "false") final boolean additive, final HttpServletRequest request, final HttpServletResponse response) throws Exception { ensureEndpointAccessIsAuthorized(request, response); Assert.notNull(this.loggerContext); final Collection<LoggerConfig> loggerConfigs = getLoggerConfigurations(); loggerConfigs.stream(). filter(cfg -> cfg.getName().equals(loggerName)) .forEachOrdered(cfg -> { cfg.setLevel(Level.getLevel(loggerLevel)); cfg.setAdditive(additive); }); this.loggerContext.updateLoggers(); }
protected final void registerParent(Class<? extends BaseLog4j2Configuration> clazz){ BaseLog4j2Configuration configuration; try{ configuration = clazz.newInstance(); }catch(InstantiationException | IllegalAccessException e){ throw new RuntimeException(e); } for(Appender appender : configuration.getAppenders()){ addAppender(appender); } for(LoggerConfig loggerConfig : configuration.getLoggerConfigs()){ addLoggerConfig(loggerConfig.getName(), loggerConfig.getLevel(), loggerConfig.isAdditive(), loggerConfig .getAppenders().values()); } for(Filter filter : configuration.getFilters()){ addFilter(filter); } }
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 synchronized boolean removeAlertListener(final DistributedMember member) { final boolean memberWasFound = this.listeners.remove(new Listener(null, member)); if (memberWasFound) { if (this.listeners.size() == 0) { this.appenderContext.getLoggerContext().removePropertyChangeListener(this); this.appenderContext.getLoggerConfig().removeAppender(APPENDER_NAME); } else { LoggerConfig loggerConfig = this.appenderContext.getLoggerConfig(); loggerConfig.addAppender(this, this.listeners.get(0).getLevel(), null); } if (logger.isDebugEnabled()) { logger.debug("Removed alert listener for member {}", member); } } return memberWasFound; }
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; }
public static boolean hasLoggerFilter(final Configuration config) { for (LoggerConfig loggerConfig : config.getLoggers().values()) { boolean isRoot = loggerConfig.getName().equals(""); boolean isGemFire = loggerConfig.getName().startsWith(LogService.BASE_LOGGER_NAME); boolean hasFilter = loggerConfig.hasFilter(); boolean isGemFireVerboseFilter = hasFilter && (LogService.GEODE_VERBOSE_FILTER.equals(loggerConfig.getFilter().toString()) || LogService.GEMFIRE_VERBOSE_FILTER.equals(loggerConfig.getFilter().toString())); if (isRoot || isGemFire) { // check for Logger Filter if (hasFilter && !isGemFireVerboseFilter) { return true; } } } return false; }
public static boolean hasAppenderRefFilter(final Configuration config) { for (LoggerConfig loggerConfig : config.getLoggers().values()) { boolean isRoot = loggerConfig.getName().equals(""); boolean isGemFire = loggerConfig.getName().startsWith(LogService.BASE_LOGGER_NAME); if (isRoot || isGemFire) { // check for AppenderRef Filter for (AppenderRef appenderRef : loggerConfig.getAppenderRefs()) { if (appenderRef.getFilter() != null) { return true; } } } } return false; }
/** * 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); }
@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(); }
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(); }
/** * Constructor to create the default configuration. */ public StandaloneLoggerConfiguration(ConfigurationSource source) { super(source); setName(CONFIG_NAME); final Appender appender = StandaloneLogEventAppender.createAppender("StandaloneLogAppender", 1000); appender.start(); addAppender(appender); final LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL); final Level level = levelName != null && Level.valueOf(levelName) != null ? Level.valueOf(levelName) : Level.ALL; root.setLevel(level); }
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(); }
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(); }
/** * Ctor. The configuration is built using instance of * {@link Spec}: * * <ul> * <li>The name is set to {@link Spec#getName()}. * <li>Appenders from the parent object are cleared. * <li>{@link Appender}s are created * {@link #buildAppenders(Spec)}. * <li>{@link LoggerConfig}s are created using * {@link #buildLoggerConfigs(Spec)}. * <li>Every {@link LoggerConfig} is configured with its * {@link Appender} using * {@link #configureLoggerAppenders(Spec, Map, Map)}. * <li>Root loggers are configured. * </ul> * * @param spec */ EmbeddedConfiguration(Spec spec) { super(ConfigurationSource.NULL_SOURCE); setName(spec.getName()); // Clean up first getAppenders().clear(); getRootLogger().getAppenders().clear(); // Build Appenders final Map<String, Appender> appenders = buildAppenders(spec); final Map<String, SyslogAppender> syslogAppenders = buildSyslogAppenders(spec); // Build Logger Configs final Map<String, LoggerConfig> loggers = buildLoggerConfigs(spec); // Configure loggers with appenders configureLoggerAppenders(spec, appenders, loggers); // Configure root logger appenders configureRootLogger(spec, appenders, syslogAppenders); }
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(); }
@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!"); } }
@Override public void registerListener(ListenerConfig cfg) { if (history != null) throw new IllegalStateException("History already registered"); history = new CircularList<LogEvent>(cfg.size); Level threshold = (cfg.threshold != null) ? Level.toLevel(cfg.threshold) : Level.WARN; ThresholdFilter filter = ThresholdFilter.createFilter(threshold, Filter.Result.ACCEPT, Filter.Result.DENY); appender = new Log4j2Appender(this, filter, threshold); if (!appender.isStarted()) appender.start(); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); LoggerConfig config = getLoggerConfig(ctx, LoggerInfo.ROOT_NAME); config.addAppender(appender, threshold, filter); ctx.updateLoggers(); }
@Before public void setUpAppender() throws IOException { file = folder.newFile(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig root = ((AbstractConfiguration) config).getRootLogger(); PatternLayout layout = PatternLayout.createLayout("[%p] %m%n", config, null, null, true, false, null, null); FileAppender appender = FileAppender.createAppender(file.getAbsolutePath(), "true", "false", "TestLogFile", "true", "false", "false", "8192", layout, null, "false", null, config); appender.start(); config.addAppender(appender); root.addAppender(appender, null, null); ctx.updateLoggers(); }
private void setupLogging() { Level level = Level.getLevel(logLevel.name()); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); // Setup the root logger to the requested log level LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(level); // Dump the requests/responses when requested if (logRequests) { loggerConfig = config.getLoggerConfig("org.apache.cxf.services"); if (level.isLessSpecificThan(Level.INFO)) { loggerConfig.setLevel(level); } else { loggerConfig.setLevel(Level.INFO); } } ctx.updateLoggers(); }
/** * <p> * This method loads the required properties into log4j for the logger * </p> * * @param logFileDir * Log file directory * @param taskAttemptID * The task attempt id * * @throws IOException * If any error occurs * @throws URISyntaxException * @throws SAXException * @throws ParserConfigurationException * @throws TransformerException */ public static void loadLogger(String logFileDir, String taskAttemptID) throws IOException, URISyntaxException, ParserConfigurationException, SAXException, TransformerException { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.reconfigure(); Configuration config = ctx.getConfiguration(); MemoryMappedFileAppender memoryMappedfileAppender = createMemoryMappedFileAppender(config, LOG_APPENDER_NAME + taskAttemptID, logFileDir, taskAttemptID, 0); memoryMappedfileAppender.start(); AppenderRef[] ar = new AppenderRef [1]; ar[0] = AppenderRef.createAppenderRef(LOG_APPENDER_NAME + taskAttemptID , Level.INFO, null); LoggerConfig lgf = LoggerConfig.createLogger("false",Level.INFO , LOG_CATEGORY + taskAttemptID , null, ar, null, config, null); config.addLogger(LOG_CATEGORY + taskAttemptID, lgf); ctx.getLogger(LOG_CATEGORY + taskAttemptID).addAppender(memoryMappedfileAppender); ctx.updateLoggers(); ctx.start(); mapReduceLoggers = new ArrayList<Logger>(1); mapReduceLoggers.add(LogManager.getLogger(LOG_CATEGORY + taskAttemptID)); LOG.debug("Finished loading logger"); }
public void addAppenderToContext( final LoggerContext ctx, final AuditAppender auditAppender, final LoggerConfig eventLogConf) { Appender targetAppender = ctx.getConfiguration().getAppender(auditAppender.getTargetAppenderName()); if (targetAppender == null) { targetAppender = auditAppender.getTargetAppender(); } targetAppender.start(); ctx.getConfiguration().addAppender(targetAppender); if (auditAppender.isRewriteEnabled()) { RewriteAppender rewriteAppender = ctx.getConfiguration().getAppender(auditAppender. getTargetAppenderName() + "_rewrite"); if (rewriteAppender == null) { rewriteAppender = auditAppender.getRewriteAppender(); } rewriteAppender.start(); ctx.getConfiguration().addAppender(rewriteAppender); eventLogConf.addAppender(rewriteAppender, Level.DEBUG, null); } else { eventLogConf.addAppender(targetAppender, Level.DEBUG, null); } }
public static void setLevel(Level level) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(level); ctx.updateLoggers(); if (level == Level.ERROR) { logger.error("<- This level is successfully initialized"); } if (level == Level.WARN) { logger.warn("<- This level is successfully initialized"); } if (level == Level.DEBUG) { logger.debug("<- This level is successfully initialized"); } if (level == Level.INFO) { logger.info("<- This level is successfully initialized"); } }
public static void addFileAppender(final String loggerPath, final File logFile, final AppConfig appConfig) throws IOException { // retrieve the logger context LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration(); // retrieve the root logger config LoggerConfig loggerConfig = configuration.getLoggerConfig(loggerPath); loggerConfig.setLevel(Level.toLevel(appConfig.getTcLogLevel())); // Define log pattern layout PatternLayout layout = PatternLayout.createLayout(DEFAULT_LOGGER_PATTERN, null, null, null, Charset.defaultCharset(), false, false, null, null); // create the appenders FileAppender fileAppender = FileAppender.createAppender(logFile.getAbsolutePath(), "true", "false", "fileAppender", "true", "true", "true", "8192", layout, null, "false", null, null); fileAppender.start(); // add the appenders loggerConfig.addAppender(fileAppender, Level.toLevel(appConfig.getTcLogLevel()), null); loggerContext.updateLoggers(); }
public static void addServerAppender(final String loggerPath, final AppConfig appConfig) throws IOException { // retrieve the logger context LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration(); // retrieve the root logger config LoggerConfig loggerConfig = configuration.getLoggerConfig(loggerPath); loggerConfig.setLevel(Level.toLevel(appConfig.getTcLogLevel())); // create the appenders ServerLoggerAppender serverLoggerAppender = ServerLoggerAppender.createAppender("serverLoggerAppender"); serverLoggerAppender.start(); // add the appenders loggerConfig.addAppender(serverLoggerAppender, Level.toLevel(appConfig.getTcLogLevel()), null); loggerContext.updateLoggers(); }
public static void main(String[] args) throws Exception{ LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); MultiLabelClfDataSet dataSet = TRECFormat.loadMultiLabelClfDataSet(new File(DATASETS, "scene/train"), DataSetType.ML_CLF_DENSE, true); MultiLabelClfDataSet testSet = TRECFormat.loadMultiLabelClfDataSet(new File(DATASETS, "scene/test"), DataSetType.ML_CLF_DENSE, true); AugmentedLR augmentedLR = new AugmentedLR(dataSet.getNumFeatures(), 1); double[][] gammas = new double[dataSet.getNumDataPoints()][1]; for (int i=0;i<dataSet.getNumDataPoints();i++){ gammas[i][0]=1; } AugmentedLRLoss loss = new AugmentedLRLoss(dataSet, 0, gammas, augmentedLR, 1, 1); LBFGS lbfgs = new LBFGS(loss); for (int i=0;i<100;i++){ lbfgs.iterate(); System.out.println(loss.getValue()); } }
/** * Create a Loggers object to contain all the Loggers. * @param loggers An array of Loggers. * @return A Loggers object. */ @PluginFactory public static Loggers createLoggers(@PluginElement("Loggers") final LoggerConfig[] loggers) { final ConcurrentMap<String, LoggerConfig> loggerMap = new ConcurrentHashMap<String, LoggerConfig>(); LoggerConfig root = null; for (final LoggerConfig logger : loggers) { if (logger != null) { if (logger.getName().isEmpty()) { root = logger; } loggerMap.put(logger.getName(), logger); } } return new Loggers(loggerMap, root); }
@PluginFactory public static LoggerConfig createLogger( @PluginAttribute("additivity") final String additivity, @PluginAttribute("level") final String levelName, @PluginAttribute("includeLocation") final String includeLocation, @PluginElement("AppenderRef") final AppenderRef[] refs, @PluginElement("Properties") final Property[] properties, @PluginConfiguration final Configuration config, @PluginElement("Filters") final Filter filter) { final List<AppenderRef> appenderRefs = Arrays.asList(refs); Level level; try { level = Level.toLevel(levelName, Level.ERROR); } catch (final Exception ex) { LOGGER.error( "Invalid Log level specified: {}. Defaulting to Error", levelName); level = Level.ERROR; } final boolean additive = Booleans.parseBoolean(additivity, true); return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, level, additive, properties, config, includeLocation(includeLocation)); }
@Test public void resetLevel() { logger.entry(); List<LogEvent> events = app.getEvents(); assertTrue("Incorrect number of events. Expected 1, actual " + events.size(), events.size() == 1); app.clear(); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); /* You could also specify the actual logger name as below and it will return the LoggerConfig used by the Logger. LoggerConfig loggerConfig = getLoggerConfig("com.apache.test"); */ loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig. logger.entry(); events = app.getEvents(); assertTrue("Incorrect number of events. Expected 0, actual " + events.size(), events.size() == 0); app.clear(); }
/** * Constructor to create the default configuration. */ public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) { super(loggerContext, source); setName(CONFIG_NAME); final Layout<? extends Serializable> layout = PatternLayout.newBuilder() .withPattern(DEFAULT_PATTERN) .withConfiguration(this) .build(); final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout); appender.start(); addAppender(appender); final LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL); final Level level = levelName != null && Level.valueOf(levelName) != null ? Level.valueOf(levelName) : Level.ERROR; root.setLevel(level); }
private static void registerLoggerConfigs(final LoggerContext ctx, final MBeanServer mbs, final Executor executor) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { final Map<String, LoggerConfig> map = ctx.getConfiguration().getLoggers(); for (final String name : map.keySet()) { final LoggerConfig cfg = map.get(name); final LoggerConfigAdmin mbean = new LoggerConfigAdmin(ctx, cfg); register(mbs, mbean, mbean.getObjectName()); if (cfg instanceof AsyncLoggerConfig) { final AsyncLoggerConfig async = (AsyncLoggerConfig) cfg; final RingBufferAdmin rbmbean = async.createRingBufferAdmin(ctx.getName()); register(mbs, rbmbean, rbmbean.getObjectName()); } } }
@PluginFactory public static LoggerConfig createLogger( @PluginAttribute("additivity") final String additivity, @PluginAttribute("level") final String levelName, @PluginAttribute("includeLocation") final String includeLocation, @PluginElement("AppenderRef") final AppenderRef[] refs, @PluginElement("Properties") final Property[] properties, @PluginConfiguration final Configuration config, @PluginElement("Filter") final Filter filter) { final List<AppenderRef> appenderRefs = Arrays.asList(refs); Level level; try { level = Level.toLevel(levelName, Level.ERROR); } catch (final Exception ex) { LOGGER.error( "Invalid Log level specified: {}. Defaulting to Error", levelName); level = Level.ERROR; } final boolean additive = Booleans.parseBoolean(additivity, true); return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, level, additive, properties, config, AsyncLoggerConfig.includeLocation(includeLocation)); }
@Test public void resetLevel() { final org.apache.logging.log4j.Logger logger = context.getLogger("com.apache.test"); logger.traceEntry(); List<LogEvent> events = app.getEvents(); assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size()); app.clear(); final LoggerContext ctx = LoggerContext.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); /* You could also specify the actual logger name as below and it will return the LoggerConfig used by the Logger. LoggerConfig loggerConfig = getLoggerConfig("com.apache.test"); */ loggerConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); // This causes all Loggers to refetch information from their LoggerConfig. logger.traceEntry(); events = app.getEvents(); assertEquals("Incorrect number of events. Expected 0, actual " + events.size(), 0, events.size()); }
@Override public Statement apply(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { System.setProperty(Constants.LOG4J_LOG_EVENT_FACTORY, TestLogEventFactory.class.getName()); resetLogEventFactory(new TestLogEventFactory()); try { base.evaluate(); } finally { System.clearProperty(Constants.LOG4J_LOG_EVENT_FACTORY); resetLogEventFactory(new DefaultLogEventFactory()); } } private void resetLogEventFactory(final LogEventFactory logEventFactory) throws IllegalAccessException { final Field field = FieldUtils.getField(LoggerConfig.class, "LOG_EVENT_FACTORY", true); FieldUtils.removeFinalModifier(field, true); FieldUtils.writeStaticField(field, logEventFactory, false); } }; }
@Test public void testPropertiesConfiguration() { final Configuration config = context.getConfiguration(); assertNotNull("No configuration created", config); assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED); final Map<String, Appender> appenders = config.getAppenders(); assertNotNull(appenders); assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1); final Map<String, LoggerConfig> loggers = config.getLoggers(); assertNotNull(loggers); assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2); final Filter filter = config.getFilter(); assertNotNull("No Filter", filter); assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter); final Logger logger = LogManager.getLogger(getClass()); logger.info("Welcome to Log4j!"); }