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 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; }
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"); }
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(); }
/** * <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"); }
private void createFileAppender(DiagnosticContext ctx) { String logDir = ctx.getTempDir() + SystemProperties.fileSeparator + "diagnostics.log"; final LoggerContext context = (LoggerContext) LogManager.getContext(false); final Configuration config = context.getConfiguration(); Layout layout = PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n", null, config, null, null,true, true, null, null ); Appender appender = FileAppender.createAppender(logDir, "false", "false", "File", "true", "false", "false", "0", layout, null, "false", null, config); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); AppenderRef[] refs = new AppenderRef[] {ref}; config.getRootLogger().addAppender(appender, null, null); context.updateLoggers(); Logger testLog = LogManager.getLogger(); testLog.error("Testing"); }
@Override public void start() { final Map<String, Appender> map = config.getAppenders(); for (final AppenderRef ref : appenderRefs) { final String name = ref.getRef(); final Appender appender = map.get(name); if (appender != null) { final Filter filter = appender instanceof AbstractAppender ? ((AbstractAppender) appender).getFilter() : null; appenders.put(name, new AppenderControl(appender, ref.getLevel(), filter)); } else { LOGGER.error("Appender " + ref + " cannot be located. Reference ignored"); } } super.start(); }
/** * Create a RewriteAppender. * @param name The name of the Appender. * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise * they are propagated to the caller. * @param appenderRefs An array of Appender names to call. * @param config The Configuration. * @param rewritePolicy The policy to use to modify the event. * @param filter A Filter to filter events. * @return The created RewriteAppender. */ @PluginFactory public static RewriteAppender createAppender( @PluginAttribute("name") final String name, @PluginAttribute("ignoreExceptions") final String ignore, @PluginElement("AppenderRef") final AppenderRef[] appenderRefs, @PluginConfiguration final Configuration config, @PluginElement("RewritePolicy") final RewritePolicy rewritePolicy, @PluginElement("Filter") final Filter filter) { final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); if (name == null) { LOGGER.error("No name provided for RewriteAppender"); return null; } if (appenderRefs == null) { LOGGER.error("No appender references defined for RewriteAppender"); return null; } return new RewriteAppender(name, filter, ignoreExceptions, appenderRefs, rewritePolicy, config); }
@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)); }
/** * Creates a RewriteAppender. * @param name The name of the Appender. * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise * they are propagated to the caller. * @param appenderRefs An array of Appender names to call. * @param config The Configuration. * @param rewritePolicy The policy to use to modify the event. * @param filter A Filter to filter events. * @return The created RewriteAppender. */ @PluginFactory public static RewriteAppender createAppender( @PluginAttribute("name") final String name, @PluginAttribute("ignoreExceptions") final String ignore, @PluginElement("AppenderRef") final AppenderRef[] appenderRefs, @PluginConfiguration final Configuration config, @PluginElement("RewritePolicy") final RewritePolicy rewritePolicy, @PluginElement("Filter") final Filter filter) { final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); if (name == null) { LOGGER.error("No name provided for RewriteAppender"); return null; } if (appenderRefs == null) { LOGGER.error("No appender references defined for RewriteAppender"); return null; } return new RewriteAppender(name, filter, ignoreExceptions, appenderRefs, rewritePolicy, config); }
@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)); }
/** * Instantiates a new Cas appender. * * @param name the name * @param config the config * @param appenderRef the appender ref */ public CasAppender(final String name, final Configuration config, final AppenderRef appenderRef) { super(name, null, PatternLayout.createDefaultLayout()); Assert.notNull(config, "Log configuration cannot be null"); Assert.notNull(config, "Appender reference configuration cannot be null"); this.config = config; this.appenderRef = appenderRef; }
private FailoverPolicy<String> createTestFailoverPolicy(String testAppenderRef, Configuration configuration) { AppenderRefFailoverPolicy.Builder builder = AppenderRefFailoverPolicy.newBuilder(); builder.withAppenderRef(AppenderRef.createAppenderRef( testAppenderRef, Level.ALL, null)); builder.withConfiguration(configuration); return builder.build(); }
/** * Creates an instance of {@link LoggerConfig} which may be * {@link AsyncLoggerConfig} if asynchronous loggers are used. * * @param configuration the owner configuration * @param asyncLoggers * @param loggerName the name of the logger * @param level the {@link Level} of the logger * @param additivity if additivity is enabled for the logger * @return an instance of {@link LoggerConfig} or * {@link AsyncLoggerConfig} */ protected static LoggerConfig createLoggerConfig(final Configuration configuration, boolean asyncLoggers, final String loggerName, final Level level, final boolean additivity) { final Filter filter = null; if (asyncLoggers) { // XXX Obscure static factory methods. return new AsyncLoggerConfig(loggerName, Collections.<AppenderRef>emptyList(), filter, level, additivity, new Property[0], configuration, false) { private static final long serialVersionUID = 1L; }; } else { return LoggerConfig.createLogger(String.valueOf(additivity), level, loggerName, null, new AppenderRef[0], new Property[0], configuration, filter); } }
@Override public void initRewriteAppender() { rewriteAppender = RewriteAppender.createAppender(getTargetAppenderName() + "_rewrite", "true", new AppenderRef[] { AppenderRef.createAppenderRef(getTargetAppenderName(), Level.DEBUG, null) }, ((LoggerContext) LogManager.getContext(false)).getConfiguration(), getRewritePolicy(), null); }
public static void configureConsoleAppender() { 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.ALL, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig); ctx.updateLoggers(); }
/** * Adds the specified appender to the root logger. * * @param appender * the appender * @param level * the logging level to assign to the appender. Default is INFO */ public static synchronized void addRootApender(Appender appender, String level) { Configuration config = getConfiguration(); appender.start(); config.addAppender(appender); Level l = Level.toLevel(level, Level.INFO); LoggerConfig root = config.getRootLogger(); if (!root.getLevel().isLessSpecificThan(l)) { if (originalRootLevel == null) { originalRootLevel = root.getLevel(); Iterator<AppenderRef> it = root.getAppenderRefs().iterator(); while (it.hasNext()) { AppenderRef ar = it.next(); if (ar.getLevel() == null) { Appender a = root.getAppenders().get(ar.getRef()); root.removeAppender(a.getName()); root.addAppender(a, originalRootLevel, ar.getFilter()); } } } root.setLevel(l); } root.addAppender(appender, l, null); addedAppenders++; getContext().updateLoggers(); }
@Override public String[] getAppenderRefs() { final List<AppenderRef> refs = loggerConfig.getAppenderRefs(); final String[] result = new String[refs.size()]; for (int i = 0; i < result.length; i++) { result[i] = refs.get(i).getRef(); } return result; }
private AsyncAppender(final String name, final Filter filter, final AppenderRef[] appenderRefs, final String errorRef, final int queueSize, final boolean blocking, final boolean ignoreExceptions, final Configuration config, final boolean includeLocation) { super(name, filter, null, ignoreExceptions); this.queue = new ArrayBlockingQueue<Serializable>(queueSize); this.blocking = blocking; this.config = config; this.appenderRefs = appenderRefs; this.errorRef = errorRef; this.includeLocation = includeLocation; }
@Override public void start() { final Map<String, Appender> map = config.getAppenders(); final List<AppenderControl> appenders = new ArrayList<AppenderControl>(); for (final AppenderRef appenderRef : appenderRefs) { if (map.containsKey(appenderRef.getRef())) { appenders.add(new AppenderControl(map.get(appenderRef.getRef()), appenderRef.getLevel(), appenderRef.getFilter())); } else { LOGGER.error("No appender named {} was configured", appenderRef); } } if (errorRef != null) { if (map.containsKey(errorRef)) { errorAppender = new AppenderControl(map.get(errorRef), null, null); } else { LOGGER.error("Unable to set up error Appender. No appender named {} was configured", errorRef); } } if (appenders.size() > 0) { thread = new AsyncThread(appenders, queue); thread.setName("AsyncAppender-" + getName()); } else if (errorRef == null) { throw new ConfigurationException("No appenders are available for AsyncAppender " + getName()); } thread.start(); super.start(); }
/** * Create an AsyncAppender. * @param appenderRefs The Appenders to reference. * @param errorRef An optional Appender to write to if the queue is full or other errors occur. * @param blocking True if the Appender should wait when the queue is full. The default is true. * @param size The size of the event queue. The default is 128. * @param name The name of the Appender. * @param includeLocation whether to include location information. The default is false. * @param filter The Filter or null. * @param config The Configuration. * @param ignore If {@code "true"} (default) exceptions encountered when appending events are logged; otherwise * they are propagated to the caller. * @return The AsyncAppender. */ @PluginFactory public static AsyncAppender createAppender(@PluginElement("AppenderRef") final AppenderRef[] appenderRefs, @PluginAttribute("errorRef") @PluginAliases("error-ref") final String errorRef, @PluginAttribute("blocking") final String blocking, @PluginAttribute("bufferSize") final String size, @PluginAttribute("name") final String name, @PluginAttribute("includeLocation") final String includeLocation, @PluginElement("Filter") final Filter filter, @PluginConfiguration final Configuration config, @PluginAttribute("ignoreExceptions") final String ignore) { if (name == null) { LOGGER.error("No name provided for AsyncAppender"); return null; } if (appenderRefs == null) { LOGGER.error("No appender references provided to AsyncAppender {}", name); } final boolean isBlocking = Booleans.parseBoolean(blocking, true); final int queueSize = AbstractAppender.parseInt(size, DEFAULT_QUEUE_SIZE); final boolean isIncludeLocation = Boolean.parseBoolean(includeLocation); final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); return new AsyncAppender(name, filter, appenderRefs, errorRef, queueSize, isBlocking, ignoreExceptions, config, isIncludeLocation); }
private RewriteAppender(final String name, final Filter filter, final boolean ignoreExceptions, final AppenderRef[] appenderRefs, final RewritePolicy rewritePolicy, final Configuration config) { super(name, filter, null, ignoreExceptions); this.config = config; this.rewritePolicy = rewritePolicy; this.appenderRefs = appenderRefs; }
/** * Returns the appender references. * @param refs The references to return. * @return The appender references. */ @PluginFactory public static String[] createFailovers(@PluginElement("AppenderRef") final AppenderRef... refs) { if (refs == null) { LOGGER.error("failovers must contain an appender reference"); return null; } final String[] arr = new String[refs.length]; for (int i = 0; i < refs.length; ++i) { arr[i] = refs[i].getRef(); } return arr; }
protected AsyncLoggerConfig(final String name, final List<AppenderRef> appenders, final Filter filter, final Level level, final boolean additive, final Property[] properties, final Configuration config, final boolean includeLocation) { super(name, appenders, filter, level, additive, properties, config, includeLocation); }
/** * Factory method to create a LoggerConfig. * * @param additivity True if additive, false otherwise. * @param levelName The Level to be associated with the Logger. * @param loggerName The name of the Logger. * @param includeLocation "true" if location should be passed downstream * @param refs An array of Appender names. * @param properties Properties to pass to the Logger. * @param config The Configuration. * @param filter A Filter. * @return A new LoggerConfig. */ @PluginFactory public static LoggerConfig createLogger( @PluginAttribute("additivity") final String additivity, @PluginAttribute("level") final String levelName, @PluginAttribute("name") final String loggerName, @PluginAttribute("includeLocation") final String includeLocation, @PluginElement("AppenderRef") final AppenderRef[] refs, @PluginElement("Properties") final Property[] properties, @PluginConfiguration final Configuration config, @PluginElement("Filters") final Filter filter) { if (loggerName == null) { LOGGER.error("Loggers cannot be configured without a name"); return null; } 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 String name = loggerName.equals("root") ? "" : loggerName; final boolean additive = Booleans.parseBoolean(additivity, true); return new AsyncLoggerConfig(name, appenderRefs, filter, level, additive, properties, config, includeLocation(includeLocation)); }
private AsyncAppender(final String name, final Filter filter, final AppenderRef[] appenderRefs, final String errorRef, final int queueSize, final boolean blocking, final boolean ignoreExceptions, final long shutdownTimeout, final Configuration config, final boolean includeLocation, final BlockingQueueFactory<LogEvent> blockingQueueFactory) { super(name, filter, null, ignoreExceptions); this.queue = blockingQueueFactory.create(queueSize); this.queueSize = queueSize; this.blocking = blocking; this.shutdownTimeout = shutdownTimeout; this.config = config; this.appenderRefs = appenderRefs; this.errorRef = errorRef; this.includeLocation = includeLocation; }
@Override public void start() { for (final AppenderRef ref : appenderRefs) { final String name = ref.getRef(); final Appender appender = config.getAppender(name); if (appender != null) { final Filter filter = appender instanceof AbstractAppender ? ((AbstractAppender) appender).getFilter() : null; appenders.put(name, new AppenderControl(appender, ref.getLevel(), filter)); } else { LOGGER.error("Appender " + ref + " cannot be located. Reference ignored"); } } super.start(); }
protected AsyncLoggerConfig(final String name, final List<AppenderRef> appenders, final Filter filter, final Level level, final boolean additive, final Property[] properties, final Configuration config, final boolean includeLocation) { super(name, appenders, filter, level, additive, properties, config, includeLocation); delegate = config.getAsyncLoggerConfigDelegate(); delegate.setLogEventFactory(getLogEventFactory()); }
/** * Factory method to create a LoggerConfig. * * @param additivity True if additive, false otherwise. * @param levelName The Level to be associated with the Logger. * @param loggerName The name of the Logger. * @param includeLocation "true" if location should be passed downstream * @param refs An array of Appender names. * @param properties Properties to pass to the Logger. * @param config The Configuration. * @param filter A Filter. * @return A new LoggerConfig. */ @PluginFactory public static LoggerConfig createLogger( @PluginAttribute("additivity") final String additivity, @PluginAttribute("level") final String levelName, @PluginAttribute("name") final String loggerName, @PluginAttribute("includeLocation") final String includeLocation, @PluginElement("AppenderRef") final AppenderRef[] refs, @PluginElement("Properties") final Property[] properties, @PluginConfiguration final Configuration config, @PluginElement("Filter") final Filter filter) { if (loggerName == null) { LOGGER.error("Loggers cannot be configured without a name"); return null; } 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 String name = loggerName.equals(LoggerConfig.ROOT) ? Strings.EMPTY : loggerName; final boolean additive = Booleans.parseBoolean(additivity, true); return new AsyncLoggerConfig(name, appenderRefs, filter, level, additive, properties, config, includeLocation(includeLocation)); }
@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()); }
/** * Get the logger used for output * * @param validatedArgs with output file, silent, and verbose options that * are used to configure the logger * @return Logger with dynamically-generated configuration */ public static Logger getLogger(ValidatedArgs validatedArgs) { // This approach is ugly, but it circumvents the need for multiple log4j // configuration files and simplifies writing results to the console and the output file // Silence StatusLogger System.setProperty("org.apache.logging.log4j.simplelog.StatusLogger.level", "FATAL"); // Setup context LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration(); // Define layout PatternLayout patternLayout = PatternLayout.newBuilder() .withConfiguration(configuration) // uncomment this pattern for debugging //.withPattern("%d{ISO8601} [%level] [%F:%L] %msg%n") .build(); // Add appenders AppenderRef[] appenderRefs; //// Create console appender unless silent ConsoleAppender consoleAppender = null; AppenderRef consoleAppenderRef = null; if (!validatedArgs.silent) { consoleAppender = ConsoleAppender.newBuilder() .setConfiguration(configuration) .withLayout(patternLayout) .withName(CONSOLE_APPENDER) .build(); consoleAppender.start(); configuration.addAppender(consoleAppender); consoleAppenderRef = AppenderRef.createAppenderRef(CONSOLE_APPENDER, null, null); } //// Create file appender if output file specified FileAppender fileAppender = null; AppenderRef fileAppenderRef = null; if (validatedArgs.outputFile != null) { fileAppender = FileAppender.newBuilder() .setConfiguration(configuration) .withLayout(patternLayout) .withName(FILE_APPENDER) .withFileName(validatedArgs.outputFile.getAbsolutePath()) .build(); fileAppender.start(); configuration.addAppender(fileAppender); fileAppenderRef = AppenderRef.createAppenderRef(FILE_APPENDER, null, null); } if ((consoleAppenderRef != null) && (fileAppenderRef != null)) { appenderRefs = new AppenderRef[]{consoleAppenderRef, fileAppenderRef}; } else if (consoleAppenderRef != null) { appenderRefs = new AppenderRef[]{consoleAppenderRef}; } else if (fileAppenderRef != null) { appenderRefs = new AppenderRef[]{fileAppenderRef}; } else { throw new IllegalStateException("At least one appender must be configured to provide output!"); } // Build and update the LoggerConfig Level levelToUse = validatedArgs.verbose ? VERBOSE_LEVEL : DEFAULT_LEVEL; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, levelToUse, LOGGER_NAME, "true", appenderRefs, null, configuration, null); if (consoleAppender != null) { loggerConfig.addAppender(consoleAppender, null, null); } if (fileAppender != null) { loggerConfig.addAppender(fileAppender, null, null); } configuration.addLogger(LOGGER_NAME, loggerConfig); loggerContext.updateLoggers(); return (Logger) LogManager.getLogger(LOGGER_NAME); }
/** * {@inheritDoc} * @see com.heliosapm.streams.tracing.AbstractMetricWriter#configure(java.util.Properties) */ @Override public void configure(final Properties config) { super.configure(config); final String loggerName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_LOGGER_NAME, null, config); if(loggerName==null || !LogManager.getContext(true).hasLogger(loggerName)) { /* * =================================================== * FIXME: this is super ugly * =================================================== * TODO: * - log4j2 async appender * - low gc message objects */ final String entryPrefix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_PREFIX, DEFAULT_ENTRY_PREFIX, config); this.config.put("entryPrefix", entryPrefix); final String entrySuffix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_SUFFIX, DEFAULT_ENTRY_SUFFIX, config); this.config.put("entrySuffix", entrySuffix); final boolean randomAccessFile = ConfigurationHelper.getBooleanSystemThenEnvProperty(CONFIG_RA_FILE, DEFAULT_RA_FILE, config); this.config.put("randomAccessFile", randomAccessFile); final String fileName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_FILE_NAME, DEFAULT_FILE_NAME, config); this.config.put("fileName", fileName); final File file = new File(fileName); final File dir = file.getParentFile(); if(dir.exists()) { if(!dir.isDirectory()) throw new IllegalArgumentException("The logging directory is a file [" + dir + "]"); } else { if(!dir.mkdirs()) throw new IllegalArgumentException("Cannot create the logging directory [" + dir + "]"); } LoggerContext context= (LoggerContext) LogManager.getContext(); Configuration loggingConfig = context.getConfiguration(); PatternLayout layout= PatternLayout.createLayout(entryPrefix + "%m" + entrySuffix + "%n" , null, loggingConfig, null, UTF8, false, false, null, null); final DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("10", "1", null, null, null, true, loggingConfig); // final int lastIndex = fileName.lastIndexOf('.'); final String format = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ROLL_PATTERN, DEFAULT_ROLL_PATTERN, config); this.config.put("format", format); final StringBuilder b = new StringBuilder(fileName).append(format); // if(lastIndex==-1) { // b.append(".").append(format); // } else { // b.insert(lastIndex, format); // } final String rolledFileFormat = b.toString(); final TriggeringPolicy trigger = TimeBasedTriggeringPolicy.createPolicy("1", "true"); if(randomAccessFile) { appender = createRollingRandomAccessFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger); } else { appender = createRollingFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger); } loggingConfig.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef(getClass().getSimpleName(), Level.INFO, null); AppenderRef[] refs = new AppenderRef[] { ref }; LoggerConfig loggerConfig = LoggerConfig.createLogger( false, Level.INFO, getClass().getSimpleName() + "Logger", "false", refs, null, loggingConfig, null); loggerConfig.addAppender(appender, Level.INFO, null); loggingConfig.addLogger(getClass().getSimpleName() + "Logger", loggerConfig); context.updateLoggers(); org.apache.logging.log4j.core.Logger xlogger = context.getLogger(getClass().getName() + "Logger"); for(Appender app: xlogger.getAppenders().values()) { xlogger.removeAppender(app); } xlogger.addAppender(appender); metricLog = context.getLogger(getClass().getName() + "Logger"); } else { metricLog = LogManager.getLogger(loggerName); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) public static synchronized void init() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n") .withConfiguration(config).withRegexReplacement(null).withCharset(null).withAlwaysWriteExceptions(true) .withNoConsoleNoAnsi(false).withHeader(null).withFooter(null).build(); // file info Filter fileInfoFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.ACCEPT); Appender fileInfoAppender = RollingFileAppender.createAppender(LOG_ROOT + "/zebra.log", LOG_ROOT + "/zebra.log.%d{yyyy-MM-dd}.gz", "true", "FileInfo", "true", "4000", "true", TimeBasedTriggeringPolicy.createPolicy("1", "true"), ZebraRolloverStrategy.createStrategy("30", "1", null, Deflater.DEFAULT_COMPRESSION + "", config), layout, fileInfoFilter, "false", null, null, config); config.addAppender(fileInfoAppender); fileInfoAppender.start(); AppenderRef fileInfoRef = AppenderRef.createAppenderRef("FileInfo", null, fileInfoFilter); // console error Appender consoleErrorAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_ERR", "ConsoleError", "false", "false"); config.addAppender(consoleErrorAppender); consoleErrorAppender.start(); // console info Filter consoleWarnFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.NEUTRAL); Appender consoleWarnAppender = ConsoleAppender.createAppender(layout, consoleWarnFilter, "SYSTEM_OUT", "ConsoleWarn", "false", "false"); config.addAppender(consoleWarnAppender); consoleWarnAppender.start(); AppenderRef consoleWarnAppenderRef = AppenderRef.createAppenderRef("ConsoleWarn", Level.WARN, consoleWarnFilter); AppenderRef consoleErrorAppenderRef = AppenderRef.createAppenderRef("ConsoleError", Level.WARN, null); AppenderRef[] refs = new AppenderRef[] { consoleErrorAppenderRef, consoleWarnAppenderRef, fileInfoRef }; LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.dianping.zebra", "true", refs, null, config, null); loggerConfig.addAppender(consoleErrorAppender, Level.ERROR, null); loggerConfig.addAppender(consoleWarnAppender, Level.INFO, null); loggerConfig.addAppender(fileInfoAppender, Level.INFO, null); config.addLogger("com.dianping.zebra", loggerConfig); ctx.updateLoggers(); context = ctx; }