private void registerLogFileTailThreads() throws IOException { final Collection<String> outputFileNames = new HashSet<>(); final Collection<Appender> loggerAppenders = this.loggerContext.getConfiguration().getAppenders().values(); loggerAppenders.forEach(appender -> { if (appender instanceof FileAppender) { outputFileNames.add(((FileAppender) appender).getFileName()); } else if (appender instanceof RandomAccessFileAppender) { outputFileNames.add(((RandomAccessFileAppender) appender).getFileName()); } else if (appender instanceof RollingFileAppender) { outputFileNames.add(((RollingFileAppender) appender).getFileName()); } else if (appender instanceof MemoryMappedFileAppender) { outputFileNames.add(((MemoryMappedFileAppender) appender).getFileName()); } else if (appender instanceof RollingRandomAccessFileAppender) { outputFileNames.add(((RollingRandomAccessFileAppender) appender).getFileName()); } }); outputFileNames.forEach(s -> { final Tailer t = new Tailer(new File(s), new LogTailerListener(), 100, false, true); final Thread thread = new Thread(t); thread.setPriority(Thread.MIN_PRIORITY); thread.setName(s); thread.start(); }); }
public Log4j2LoggerAdapter() { try { org.apache.logging.log4j.Logger logger = LogManager.getLogger(); if (logger != null) { Map<String, Appender> appenderMap = ((org.apache.logging.log4j.core.Logger) logger).getAppenders(); for (Map.Entry<String, Appender> entry : appenderMap.entrySet()) { if (entry.getValue() instanceof FileAppender) { String filename = ((FileAppender) entry.getValue()).getFileName(); file = new File(filename); break; } } } } catch (Throwable t) { } }
/** * 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); }
/** * File appender types do not share a "write-to-file" superclass. */ private String extractFileName(Appender a) { if (a instanceof FileAppender) { return ((FileAppender) a).getFileName(); } else if (a instanceof RollingFileAppender) { return ((RollingFileAppender) a).getFileName(); } else if (a instanceof RollingRandomAccessFileAppender) { return ((RollingRandomAccessFileAppender) a).getFileName(); } else if (a instanceof RandomAccessFileAppender) { return ((RandomAccessFileAppender) a).getFileName(); } else if (a instanceof MemoryMappedFileAppender) { return ((MemoryMappedFileAppender) a).getFileName(); } else { return null; } }
/** * 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(); }
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(); }
/** * 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(); }
@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(); }
@Override public void initTargetAppender() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); // get log file path from existing file appender RollingRandomAccessFileAppender mainFile = (RollingRandomAccessFileAppender) ctx.getConfiguration().getAppender("mainFile"); String pathPrefix = mainFile == null ? System.getProperty("user.dir") + StringUtils.replace("/target/log", "/", File.separator) + File.separator : StringUtils.replace(mainFile.getFileName(), "core.log", StringUtils.EMPTY); targetAppender = FileAppender.newBuilder() .withName(getTargetAppenderName()) .withAppend(true) .withFileName(pathPrefix + getTargetAppenderName() + ".log") .withLayout( PatternLayout.newBuilder() .withPattern("%d{HH:mm:ss.SSS} %-5level %logger - %msg%n") .build()). build(); }
@Override public void initTargetAppender() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); // get log file path from existing file appender RollingRandomAccessFileAppender mainFile = (RollingRandomAccessFileAppender) ctx.getConfiguration().getAppender("mainFile"); String pathPrefix = StringUtils.replace(mainFile.getFileName(), "core.log", StringUtils.EMPTY); targetAppender = FileAppender.newBuilder(). withName(getTargetAppenderName()). withAppend(true). withFileName(pathPrefix + getTargetAppenderName() + ".log"). withLayout( PatternLayout.newBuilder() .withPattern("%d{HH:mm:ss.SSS} %-5level %logger - %msg%n") .build()) .build(); }
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(); }
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"); }
@Test public void testConfiguration() { final Configuration configuration = context.getConfiguration(); assertNotNull(configuration); final FileAppender appender = configuration.getAppender("info"); assertNotNull(appender); final CompositeFilter compFilter = (CompositeFilter) appender.getFilter(); assertNotNull(compFilter); final Filter[] filters = compFilter.getFiltersArray(); assertNotNull(filters); boolean foundLevel = false; for (final Filter filter : filters) { final ThresholdFilter tFilter = (ThresholdFilter) filter; if (infom1Level.equals(tFilter.getLevel())) { foundLevel = true; break; } } Assert.assertTrue("Level not found: " + infom1Level, foundLevel); }
public static FileAppender createFileAppender(String name, String fileName, String pattern){ PatternLayout layout = createLayout(pattern); return FileAppender.newBuilder() .withFileName(fileName) .withName(name) .withLayout(layout) .build(); }
public TestDatarouterParentLog4j2Configuration() throws IllegalAccessException{ addFilter(RegexFilter.createFilter(".*password.*", null, true, Result.DENY, Result.NEUTRAL)); FileAppender testFileAppender = Log4j2Configurator.createFileAppender(TEST_APPENDER_NAME, TEST_FILE_NAME, defaultPattern); addAppender(testFileAppender); addLoggerConfig(getClass().getPackage().getName(), Level.ALL, false, testFileAppender); }
/** * The name of the file being appended to by the FILE Appender, if a FILE Appender is specified in the log4j2 configuration. * * @return the file being appended to by the FILE Appender, or null if a FILE Appender is <b>not</b> specified in the log4j2 configuration. */ public static URI getFileName() { final LoggerContext context = (LoggerContext) LogManager.getContext(false); final Configuration configuration = context.getConfiguration(); return new File(((FileAppender) configuration.getAppender("FILE")).getFileName()).toURI(); }
public static String addFileLogger(String logFile) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); // Default log layout Layout<? extends Serializable> layout = PatternLayout.createLayout("%d %p [%t] %m%n", null, null, null, true, true, null, null); // Create a new file appender for the given filename FileAppender appender = FileAppender.createAppender( logFile, "false", "false", "FileAppender", "false", "true", "true", null, layout, null, null, null, config); appender.start(); ((Logger) LogManager.getRootLogger()).addAppender(appender); return appender.getFileName(); }
/** {@inheritDoc} */ @Nullable @Override public String fileName() { for (Logger log = impl; log != null; log = log.getParent()) { for (Appender a : log.getAppenders().values()) { if (a instanceof FileAppender) return ((FileAppender)a).getFileName(); if (a instanceof RollingFileAppender) return ((RollingFileAppender)a).getFileName(); if (a instanceof RoutingAppender) { try { RoutingAppender routing = (RoutingAppender)a; Field appsFiled = routing.getClass().getDeclaredField("appenders"); appsFiled.setAccessible(true); Map<String, AppenderControl> appenders = (Map<String, AppenderControl>)appsFiled.get(routing); for (AppenderControl control : appenders.values()) { Appender innerApp = control.getAppender(); if (innerApp instanceof FileAppender) return normalize(((FileAppender)innerApp).getFileName()); if (innerApp instanceof RollingFileAppender) return normalize(((RollingFileAppender)innerApp).getFileName()); } } catch (IllegalAccessException | NoSuchFieldException e) { error("Failed to get file name (was the implementation of log4j2 changed?).", e); } } } } return null; }
public static void appendFileLogger(Level level, String name, Path filePath) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); Layout layout = PatternLayout.createLayout("%d{HH:mm} [%-5p] %msg%n", null, config, null, null, true, false, null, null); Appender appender = FileAppender.createAppender(filePath.toFile().getAbsolutePath(), "true", "false", name, "true", "false", "false", "8192", layout, null, "false", null, config); appender.start(); config.getRootLogger().addAppender(appender, level, null); ctx.updateLoggers(); }
public static String getLoggerFileName() { org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) log; Appender appender = loggerImpl.getAppenders().get("LogFile"); if (appender != null) return ((FileAppender) appender).getFileName(); else return "NOT_CONFIGURED"; }
public static void addFileAppender(String filename) { if (instance == null) { LOGGER.error("CustomFileAppender hasn't been initalized, ignoring output " + filename); return; } final AbstractOutputStreamAppender<? extends OutputStreamManager> appender; if (mmap_appender) appender = MemoryMappedFileAppender.createAppender(filename, "false", filename, "false", "8192", "false", instance.getLayout(), instance.getFilter(), "false", "false", new DefaultConfiguration()); else appender = FileAppender.createAppender(filename, "false", "false", filename, "false", "false", "true", "8192", instance.getLayout(), instance.getFilter(), "false", "false", new DefaultConfiguration()); LOGGER.info("registering custom logfile '{}'", appender); instance.appenders.add(appender); }
private Layout<?> testFile(final String configResource) throws Exception { final Configuration configuration = getConfiguration(configResource); final FileAppender appender = configuration.getAppender("File"); assertNotNull(appender); assertEquals("target/mylog.txt", appender.getFileName()); // final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo"); assertNotNull(loggerConfig); assertEquals(Level.DEBUG, loggerConfig.getLevel()); configuration.start(); configuration.stop(); return appender.getLayout(); }
@Test public void testLookup2() throws Exception { ContextAnchor.THREAD_CONTEXT.remove(); final ServletContext servletContext = new MockServletContext(); servletContext.setAttribute("TestAttr", "AttrValue"); servletContext.setInitParameter("myapp.logdir", "target"); servletContext.setAttribute("Name1", "Ben"); servletContext.setInitParameter("Name2", "Jerry"); servletContext.setInitParameter("log4jConfiguration", "WEB-INF/classes/log4j-webvar.xml"); final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext); initializer.start(); initializer.setLoggerContext(); final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get(); assertNotNull("No LoggerContext", ctx); assertNotNull("No ServletContext", ctx.getExternalContext()); final Configuration config = ctx.getConfiguration(); assertNotNull("No Configuration", config); final Map<String, Appender> appenders = config.getAppenders(); for (final Map.Entry<String, Appender> entry : appenders.entrySet()) { if (entry.getKey().equals("file")) { final FileAppender fa = (FileAppender) entry.getValue(); assertEquals("target/myapp.log", fa.getFileName()); } } initializer.stop(); ContextAnchor.THREAD_CONTEXT.remove(); }
@Test public void compositeLogger() { final LoggerContextRule lcr = new LoggerContextRule("classpath:log4j-comp-logger.xml,log4j-comp-logger.json"); final Statement test = new Statement() { @Override public void evaluate() throws Throwable { final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration(); Map<String, Appender> appendersMap = config.getLogger("cat1").getAppenders(); assertEquals("Expected 2 Appender references for cat1 but got " + appendersMap.size(), 2, appendersMap.size()); assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender); Filter loggerFilter = config.getLogger("cat1").getFilter(); assertTrue(loggerFilter instanceof RegexFilter); assertEquals(loggerFilter.getOnMatch(), Filter.Result.DENY); appendersMap = config.getLogger("cat2").getAppenders(); assertEquals("Expected 1 Appender reference for cat2 but got " + appendersMap.size(), 1, appendersMap.size()); assertTrue(appendersMap.get("File") instanceof FileAppender); appendersMap = config.getLogger("cat3").getAppenders(); assertEquals("Expected 1 Appender reference for cat3 but got " + appendersMap.size(), 1, appendersMap.size()); assertTrue(appendersMap.get("File") instanceof FileAppender); appendersMap = config.getRootLogger().getAppenders(); assertEquals("Expected 2 Appender references for the root logger but got " + appendersMap.size(), 2, appendersMap.size()); assertTrue(appendersMap.get("File") instanceof FileAppender); assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender); } }; runTest(lcr, test); }
/** * Gets configuration as JSON. * Depends on the log4j core API. * * @param request the request * @param response the response * @return the configuration * @throws Exception the exception */ @GetMapping(value = "/getConfiguration") @ResponseBody public Map<String, Object> getConfiguration(final HttpServletRequest request, final HttpServletResponse response) throws Exception { ensureEndpointAccessIsAuthorized(request, response); Assert.notNull(this.loggerContext); final Collection<Map<String, Object>> configuredLoggers = new HashSet<>(); getLoggerConfigurations().forEach(config -> { final Map<String, Object> loggerMap = new HashMap<>(); loggerMap.put("name", StringUtils.defaultIfBlank(config.getName(), LOGGER_NAME_ROOT)); loggerMap.put("state", config.getState()); if (config.getProperties() != null) { loggerMap.put("properties", config.getProperties()); } loggerMap.put("additive", config.isAdditive()); loggerMap.put("level", config.getLevel().name()); final Collection<String> appenders = new HashSet<>(); config.getAppenders().keySet().stream().map(key -> config.getAppenders().get(key)).forEach(appender -> { final ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE); builder.append("name", appender.getName()); builder.append("state", appender.getState()); builder.append("layoutFormat", appender.getLayout().getContentFormat()); builder.append("layoutContentType", appender.getLayout().getContentType()); if (appender instanceof FileAppender) { builder.append(FILE_PARAM, ((FileAppender) appender).getFileName()); builder.append(FILE_PATTERN_PARAM, "(none)"); } if (appender instanceof RandomAccessFileAppender) { builder.append(FILE_PARAM, ((RandomAccessFileAppender) appender).getFileName()); builder.append(FILE_PATTERN_PARAM, "(none)"); } if (appender instanceof RollingFileAppender) { builder.append(FILE_PARAM, ((RollingFileAppender) appender).getFileName()); builder.append(FILE_PATTERN_PARAM, ((RollingFileAppender) appender).getFilePattern()); } if (appender instanceof MemoryMappedFileAppender) { builder.append(FILE_PARAM, ((MemoryMappedFileAppender) appender).getFileName()); builder.append(FILE_PATTERN_PARAM, "(none)"); } if (appender instanceof RollingRandomAccessFileAppender) { builder.append(FILE_PARAM, ((RollingRandomAccessFileAppender) appender).getFileName()); builder.append(FILE_PATTERN_PARAM, ((RollingRandomAccessFileAppender) appender).getFilePattern()); } appenders.add(builder.build()); }); loggerMap.put("appenders", appenders); configuredLoggers.add(loggerMap); }); final Map<String, Object> responseMap = new HashMap<>(); responseMap.put("loggers", configuredLoggers); return responseMap; }
/** * 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); }
/** * 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); }
protected Log4J2Configuration(ConfigurationSource configurationSource) { super(ConfigurationSource.NULL_SOURCE); setName("Default"); PatternLayout layout = PatternLayout.newBuilder().withPattern(Log4J2.DEFALT_LAYOUT).withConfiguration(this).build(); Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout); appender.start(); addAppender(appender); String fileName = Config.getProperty(Log4J2.class,"file",""); String append = Boolean.TRUE.toString(); String locking = Boolean.TRUE.toString(); String immediateFlush = Boolean.TRUE.toString(); String ignore = Boolean.TRUE.toString(); String bufferedIo = Boolean.TRUE.toString(); String bufferSizeStr = "8192"; Filter filter = null; String advertise = null; String advertiseUri = null; Appender fileAppender = null; if(fileName.length() > 0) { String name = Config.getProperty(Log4J2.class,"name","default"); fileAppender = FileAppender.createAppender(fileName, append, locking, name, immediateFlush, ignore, bufferedIo, bufferSizeStr, layout, filter, advertise, advertiseUri, this); fileAppender.start(); addAppender(fileAppender); } LoggerConfig root = getRootLogger(); root.addAppender(appender, null, null); if(fileAppender != null) { root.addAppender(fileAppender, null, filter); } String levelName = PropertiesUtil.getProperties().getStringProperty("org.apache.logging.log4j.level"); Level level = levelName == null || Level.valueOf(levelName) == null ? Level.DEBUG : Level.valueOf(levelName); root.setLevel(level); }
/** * Creates a new file-logger for an addOn. The logger will log to a file with the addOnId as name in the logs folder * of Izou * * @param addOnId the Id of the addOn the logger is created for * @param level level of logger (at what level of log the logger should be activated * @return the new logger */ public synchronized ExtendedLogger createFileLogger(String addOnId, String level) { try { LoggerContext ctx = LogManager.getContext(false); Configuration config = ((org.apache.logging.log4j.core.LoggerContext) ctx).getConfiguration(); //creates a new pattern layout (what determines how the log is formated, i.e. date, thread etc.) Layout layout = PatternLayout.createLayout("%d %-5p [%t] %C{10} (%F:%L) - %m%n", config, null, null, true, false, null, null); //creates a file appender for the logger (so that it knows what file to log to) Appender fileAppender = FileAppender.createAppender("logs" + File.separator + addOnId + ".log", "true", "false", "file", "true", "false", "false", "4000", layout, null, "false", null, config); fileAppender.start(); config.addAppender(fileAppender); //creates also a console appender for the logger (so that the logger also outputs the log in the console) Appender consoleAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "console", null, null); consoleAppender.start(); config.addAppender(consoleAppender); //adds appenders to an array called refs. It will later serve as references to the logger as to what // appenders it has AppenderRef fileRef = AppenderRef.createAppenderRef("file", Level.DEBUG, null); AppenderRef consoleRef = AppenderRef.createAppenderRef("console", Level.DEBUG, null); AppenderRef[] refs = new AppenderRef[]{fileRef, consoleRef}; //creates the logger configurations for the logger, where the appender-references are also added LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.DEBUG, addOnId, "true", refs, null, config, null); loggerConfig.addAppender(fileAppender, Level.DEBUG, null); loggerConfig.addAppender(consoleAppender, Level.DEBUG, null); //finally creates the logger and returns it config.addLogger(addOnId, loggerConfig); ((org.apache.logging.log4j.core.LoggerContext) ctx).updateLoggers(); ctx.getLogger(addOnId); ExtendedLogger logger = ctx.getLogger(addOnId); return logger; } catch(Exception e) { fileLogger.error("Unable to create FileLogger",e); return null; } }
/** * Test case for MDC conversion pattern. */ @Test public void mdcPattern() throws Exception { final String mdcMsgPattern1 = "%m : %X%n"; final String mdcMsgPattern2 = "%m : %X{key1}%n"; final String mdcMsgPattern3 = "%m : %X{key2}%n"; final String mdcMsgPattern4 = "%m : %X{key3}%n"; final String mdcMsgPattern5 = "%m : %X{key1},%X{key2},%X{key3}%n"; // set up appender final PatternLayout layout = PatternLayout.createLayout(msgPattern, ctx.getConfiguration(), null, null, null); //FileOutputStream fos = new FileOutputStream(OUTPUT_FILE + "_mdc"); final FileAppender appender = FileAppender.createAppender(OUTPUT_FILE + "_mdc", "false", "false", "File", "false", "true", "false", layout, null, "false", null, null); appender.start(); // set appender on root and set level to debug root.addAppender(appender); root.setLevel(Level.DEBUG); // output starting message root.debug("starting mdc pattern test"); layout.setConversionPattern(mdcMsgPattern1); root.debug("empty mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); root.debug("empty mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); root.debug("empty mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); root.debug("empty mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); root.debug("empty mdc, key1, key2, and key3 in pattern"); ThreadContext.put("key1", "value1"); ThreadContext.put("key2", "value2"); layout.setConversionPattern(mdcMsgPattern1); root.debug("filled mdc, no key specified in pattern"); layout.setConversionPattern(mdcMsgPattern2); root.debug("filled mdc, key1 in pattern"); layout.setConversionPattern(mdcMsgPattern3); root.debug("filled mdc, key2 in pattern"); layout.setConversionPattern(mdcMsgPattern4); root.debug("filled mdc, key3 in pattern"); layout.setConversionPattern(mdcMsgPattern5); root.debug("filled mdc, key1, key2, and key3 in pattern"); ThreadContext.remove("key1"); ThreadContext.remove("key2"); layout.setConversionPattern(msgPattern); root.debug("finished mdc pattern test"); assertTrue(Compare.compare(this.getClass(), OUTPUT_FILE + "_mdc", WITNESS_FILE + "_mdc")); root.removeAppender(appender); appender.stop(); }
private void buildFileAppender(final String appenderName) { final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, FileAppender.PLUGIN_NAME); buildFileAppender(appenderName, appenderBuilder); builder.add(appenderBuilder); }
@Test public void testConfig() { // don't bother using "error" since that's the default; try another level final LoggerContext ctx = this.init.getLoggerContext(); ctx.reconfigure(); final Configuration config = ctx.getConfiguration(); assertThat(config, instanceOf(XmlConfiguration.class)); for (final StatusListener listener : StatusLogger.getLogger().getListeners()) { if (listener instanceof StatusConsoleListener) { assertSame(listener.getStatusLevel(), Level.INFO); break; } } final Layout<? extends Serializable> layout = PatternLayout.newBuilder() .withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN) .withConfiguration(config) .build(); // @formatter:off final FileAppender appender = FileAppender.newBuilder() .withFileName(LOG_FILE) .withAppend(false) .withName("File") .withIgnoreExceptions(false) .withBufferSize(4000) .withBufferedIo(false) .withLayout(layout) .build(); // @formatter:on appender.start(); config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j", "true", refs, null, config, null ); loggerConfig.addAppender(appender, null, null); config.addLogger("org.apache.logging.log4j", loggerConfig); ctx.updateLoggers(); final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName()); logger.info("This is a test"); final File file = new File(LOG_FILE); assertThat(file, exists()); assertThat(file, hasLength(greaterThan(0L))); }
@Before public void before() { fileApp = context.getRequiredAppender("File", FileAppender.class); }
@Test public void testFileName() { final FileAppender fileApp = (FileAppender) context.getRequiredAppender("File"); final String name = fileApp.getFileName(); Assert.assertEquals("target/value0.log", name); }