Java Code Examples for org.apache.logging.log4j.core.config.AppenderRef#createAppenderRef()
The following examples show how to use
org.apache.logging.log4j.core.config.AppenderRef#createAppenderRef() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Log4j2Util.java From summerframework with Apache License 2.0 | 7 votes |
@SuppressWarnings({"rawtypes", "unchecked"}) private static void createAppenderAndStart(String loggerName, String fileName, String filePattern) { Layout layout = PatternLayout.newBuilder().withConfiguration(config) .withPattern("[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n").build(); TimeBasedTriggeringPolicy tbtp = TimeBasedTriggeringPolicy.createPolicy(null, null); TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("10M"); CompositeTriggeringPolicy policyComposite = CompositeTriggeringPolicy.createPolicy(tbtp, tp); String loggerDir = datalogDir + File.separator; String loggerPathPrefix = loggerDir + File.separator; RollingFileAppender.Builder builder = RollingFileAppender.newBuilder().withFilePattern(filePattern) .withStrategy(null).withPolicy(policyComposite).withConfiguration(config); RollingFileAppender appender = builder.build(); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef(loggerName, Level.INFO, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.ALL, loggerName, "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(loggerName, loggerConfig); ctx.updateLoggers(); }
Example 2
Source File: Main.java From homework_tester with MIT License | 7 votes |
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"); }
Example 3
Source File: ValidatingPluginWithFailoverTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager(Core.CATEGORY_NAME); manager.collectPlugins(); plugin = (PluginType<FailoverAppender>) manager.getPluginType("failover"); assertNotNull("Rebuild this module to make sure annotation processing kicks in.", plugin); AppenderRef appenderRef = AppenderRef.createAppenderRef("List", Level.ALL, null); node = new Node(null, "failover", plugin); Node failoversNode = new Node(node, "Failovers", manager.getPluginType("Failovers")); Node appenderRefNode = new Node(failoversNode, "appenderRef", manager.getPluginType("appenderRef")); appenderRefNode.getAttributes().put("ref", "file"); appenderRefNode.setObject(appenderRef); failoversNode.getChildren().add(appenderRefNode); failoversNode.setObject(FailoversPlugin.createFailovers(appenderRef)); node.getAttributes().put("primary", "CONSOLE"); node.getAttributes().put("name", "Failover"); node.getChildren().add(failoversNode); }
Example 4
Source File: RewriteAppenderBuilder.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private <T extends Log4j1Configuration> Appender createAppender(String name, String level, String[] appenderRefs, RewritePolicy policy, Filter filter, T configuration) { org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level, org.apache.logging.log4j.Level.TRACE); AppenderRef[] refs = new AppenderRef[appenderRefs.length]; int index = 0; for (String appenderRef : appenderRefs) { refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null); } org.apache.logging.log4j.core.Filter rewriteFilter = buildFilters(level, filter); org.apache.logging.log4j.core.appender.rewrite.RewritePolicy rewritePolicy; if (policy instanceof RewritePolicyWrapper) { rewritePolicy = ((RewritePolicyWrapper) policy).getPolicy(); } else { rewritePolicy = new RewritePolicyAdapter(policy); } return new AppenderWrapper(RewriteAppender.createAppender(name, true, refs, configuration, rewritePolicy, rewriteFilter)); }
Example 5
Source File: AsyncAppenderBuilder.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private <T extends Log4j1Configuration> Appender createAppender(String name, String level, String[] appenderRefs, boolean blocking, int bufferSize, boolean includeLocation, T configuration) { org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level, org.apache.logging.log4j.Level.TRACE); AppenderRef[] refs = new AppenderRef[appenderRefs.length]; int index = 0; for (String appenderRef : appenderRefs) { refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null); } return new AppenderWrapper(AsyncAppender.newBuilder() .setName(name) .setAppenderRefs(refs) .setBlocking(blocking) .setBufferSize(bufferSize) .setIncludeLocation(includeLocation) .setConfiguration(configuration) .build()); }
Example 6
Source File: MyServiceUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void testProgrammaticConfig() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build(); Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build(); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null); AppenderRef[] refs = new AppenderRef[] { ref }; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger("programmaticLogger", loggerConfig); ctx.updateLoggers(); Logger pLogger = LogManager.getLogger("programmaticLogger"); pLogger.info("Programmatic Logger Message"); }
Example 7
Source File: LoggerUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * <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"); }
Example 8
Source File: Main.java From homework_tester with MIT License | 6 votes |
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"); }
Example 9
Source File: Log4JController.java From GreenSummer with GNU Lesser General Public License v2.1 | 6 votes |
/** * Captures the given logger at the given level so it can be displayed directly by this controller. * * @param name the name * @param level the level * @param append the append * @return the response entity */ @RequestMapping(value = "capture/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET, headers = "Accept=application/json") @ResponseBody public ResponseEntity<LogResponse> capture(@PathVariable("name") final String name, @PathVariable("level") final Level level, @RequestParam(value = "append", defaultValue = "false") boolean append) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); synchronized (ctx) { if (inMemoryAppenderImpl != null) { final Configuration config = ctx.getConfiguration(); // if (name.equalsIgnoreCase(config.getLoggerConfig(name).getName())) { config.removeLogger(name); } // AppenderRef ref = AppenderRef.createAppenderRef("InMemoryAppenderImplAppenderRef", level, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(append, level, name, "true", refs, null, config, null); loggerConfig.addAppender(inMemoryAppenderImpl, null, null); config.addLogger(name, loggerConfig); ctx.updateLoggers(); } } return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK); }
Example 10
Source File: Log4j2Configuration.java From summerframework with Apache License 2.0 | 6 votes |
private void createBizLogger() { if (env.containsProperty(MonitorConfigSpringApplicationRunListener.LOG_KAFKA_BOOTSTRAPSERVERS)) { String appenderName = "AdvancedKafkaAppender"; LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false); Configuration configuration = loggerContext.getConfiguration(); AdvancedKafkaAppender kafkaAppender = AdvancedKafkaAppender.createAppender(CustomJsonLayout.createDefaultLayout(), null, configuration, appenderName, getKafkaTopic(), getBootstrapservers()); kafkaAppender.start(); AppenderRef ref = AppenderRef.createAppenderRef(appenderName, null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "BizLogger", null, refs, null, configuration, null); loggerConfig.addAppender(kafkaAppender, null, null); configuration.addLogger("BizLogger", loggerConfig); } }
Example 11
Source File: LogUtil.java From fix-orchestra with Apache License 2.0 | 5 votes |
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build(); config.addAppender(appender); final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null); final AppenderRef[] refs = new AppenderRef[] {ref}; final LoggerConfig loggerConfig = LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null); config.addLogger(clazz.getName(), loggerConfig); ctx.updateLoggers(); return LogManager.getLogger(clazz); }
Example 12
Source File: ActorLogger.java From actor4j-core with Apache License 2.0 | 5 votes |
private ActorLogger() { loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false); Configuration config = loggerContext.getConfiguration(); Appender systemConsoleAppender = ConsoleAppender.newBuilder() .setName(SYSTEM_CONSOLE_APPENDER_NAME) .setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build()) .setConfiguration(config) .build(); systemConsoleAppender.start(); AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)}; systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null); systemLoggerConfig.addAppender(systemConsoleAppender, null, null); Appender userConsoleAppender = ConsoleAppender.newBuilder() .setName(USER_CONSOLE_APPENDER_NAME) .setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build()) .setConfiguration(config) .build(); userConsoleAppender.start(); AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)}; userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null); userLoggerConfig.addAppender(userConsoleAppender, null, null); config.addAppender(systemConsoleAppender); config.addAppender(userConsoleAppender); config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig); config.addLogger(USER_LOGGER_NAME, userLoggerConfig); loggerContext.updateLoggers(config); }
Example 13
Source File: TestLoggerResource.java From flink with Apache License 2.0 | 5 votes |
@Override protected void before() throws Throwable { loggingEvents = new ConcurrentLinkedQueue<>(); Appender testAppender = new AbstractAppender("test-appender", null, null, false) { @Override public void append(LogEvent event) { loggingEvents.add(event.getMessage().getFormattedMessage()); } }; testAppender.start(); AppenderRef appenderRef = AppenderRef.createAppenderRef(testAppender.getName(), null, null); LoggerConfig logger = LoggerConfig.createLogger( false, Level.getLevel(level.name()), "test", null, new AppenderRef[]{appenderRef}, null, LOGGER_CONTEXT.getConfiguration(), null); logger.addAppender(testAppender, null, null); LOGGER_CONTEXT.getConfiguration().addLogger(loggerName, logger); LOGGER_CONTEXT.updateLoggers(); }
Example 14
Source File: BaseService.java From support-diagnostics with Apache License 2.0 | 5 votes |
protected void createFileAppender(String logDir, String logFile) { logPath = logDir + SystemProperties.fileSeparator + logFile; Layout layout = PatternLayout.newBuilder() .withConfiguration(logConfig) .withPattern("%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n") .build(); FileAppender.Builder builder = FileAppender.newBuilder(); builder.setConfiguration(logConfig); builder.withFileName(logPath); builder.withAppend(false); builder.withLocking(false); builder.setName("packaged"); builder.setIgnoreExceptions(false); builder.withImmediateFlush(true); builder.withBufferedIo(false); builder.withBufferSize(0); builder.setLayout(layout); Appender diagAppender = builder.build(); Appender oldAppender = logConfig.getAppender("packaged"); if(oldAppender != null && oldAppender.isStarted()){ oldAppender.stop(); logConfig.getRootLogger().removeAppender("packaged"); } diagAppender.start(); logConfig.addAppender(diagAppender); AppenderRef.createAppenderRef("packaged", null, null); logConfig.getRootLogger().addAppender(diagAppender, null, null); loggerContext.updateLoggers(); logger.info(Constants.CONSOLE, "Diagnostic logger reconfigured for inclusion into archive"); }
Example 15
Source File: Log4JLogConfigInitializer.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
private AppenderRef[] createAppenderRef( String refName ) { AppenderRef ref = AppenderRef.createAppenderRef( refName, Level.INFO, null ); return new AppenderRef[] { ref }; }
Example 16
Source File: LoggerLoader.java From Zebra with Apache License 2.0 | 4 votes |
@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; }
Example 17
Source File: ApsSystemUtils.java From entando-core with GNU Lesser General Public License v3.0 | 4 votes |
public void init() throws Exception { String active = (String) this.systemParams.get(INIT_PROP_LOG_ACTIVE_FILE_OUTPUT); if (StringUtils.isEmpty(active) || !active.equalsIgnoreCase("true")) { return; } String appenderName = "ENTANDO"; String conversionPattern = (String) this.systemParams.get("log4jConversionPattern"); if (StringUtils.isBlank(conversionPattern)) { conversionPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} - %-5p - %c - %m%n"; } String maxFileSize = (String) this.systemParams.get(INIT_PROP_LOG_FILE_SIZE); if (StringUtils.isBlank(maxFileSize)) { maxFileSize = "1MB"; //default size } else { long mega = new Long(maxFileSize) / KILOBYTE; maxFileSize = mega + "KB"; } String filePattern = (String) this.systemParams.get(INIT_PROP_LOG_FILE_PATTERN); String filename = (String) this.systemParams.get(INIT_PROP_LOG_NAME); int maxBackupIndex = Integer.parseInt((String) this.systemParams.get(INIT_PROP_LOG_FILES_COUNT)); String log4jLevelString = (String) this.systemParams.get(INIT_PROP_LOG_LEVEL); if (StringUtils.isBlank(log4jLevelString)) { log4jLevelString = "INFO"; //default level } Configurator.setRootLevel(Level.getLevel(log4jLevelString)); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.getRootLogger().setLevel(Level.getLevel(log4jLevelString)); Configurator.setAllLevels(loggerContext.getRootLogger().getName(), Level.getLevel(log4jLevelString)); Configuration configuration = loggerContext.getConfiguration(); RollingFileAppender fileAppender = (RollingFileAppender) configuration.getAppender(appenderName); if (null == fileAppender) { PathCondition[] pathConditions = new PathCondition[]{IfAccumulatedFileCount.createFileCountCondition(maxBackupIndex)}; String basePath = filePattern.substring(0, filePattern.lastIndexOf(File.separator)); DeleteAction deleteAction = DeleteAction.createDeleteAction(basePath, true, 1, false, null, pathConditions, null, configuration); SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize); PatternLayout layout = PatternLayout.newBuilder().withPattern(conversionPattern).build(); DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder() .withConfig(configuration).withMax(String.valueOf(maxBackupIndex)) .withCustomActions(new Action[]{deleteAction}).build(); fileAppender = RollingFileAppender.newBuilder() .withName(appenderName) .setConfiguration(configuration) .withLayout(layout) .withFileName(filename) .withFilePattern(filePattern) .withPolicy(policy) .withStrategy(strategy) .build(); configuration.addAppender(fileAppender); Configurator.setLevel(appenderName, Level.getLevel(log4jLevelString)); fileAppender.start(); } AsyncAppender async = (AsyncAppender) loggerContext.getRootLogger().getAppenders().get("async"); if (null == async) { AppenderRef ref = AppenderRef.createAppenderRef(appenderName, Level.getLevel(log4jLevelString), null); async = AsyncAppender.newBuilder().setName("async") .setConfiguration(configuration) .setAppenderRefs(new AppenderRef[]{ref}).build(); configuration.addAppender(async); loggerContext.getRootLogger().addAppender(async); async.start(); } loggerContext.updateLoggers(); }
Example 18
Source File: SmokeTestBase.java From log4j2-elasticsearch with Apache License 2.0 | 4 votes |
public final void createLoggerProgrammatically(Supplier<ElasticsearchAppender.Builder> appenderBuilder, Function<Configuration, AsyncLoggerConfigDelegate> delegateSupplier) { LoggerContext ctx = LoggerContext.getContext(false); final Configuration config = ctx.getConfiguration(); Appender appender = appenderBuilder.get().build(); appender.start(); AppenderRef ref = AppenderRef.createAppenderRef(DEFAULT_APPENDER_NAME, Level.INFO, null); AppenderRef[] refs = new AppenderRef[] {ref}; // set up disruptor forcefully ((LifeCycle)delegateSupplier.apply(config)).start(); AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) AsyncLoggerConfig.createLogger(false, Level.INFO, DEFAULT_LOGGER_NAME, "false", refs, null, config, null ); loggerConfig.addAppender(appender, Level.INFO, null); config.addAppender(appender); config.addLogger(DEFAULT_LOGGER_NAME, loggerConfig); }
Example 19
Source File: CloudStorageLoggerFactory.java From ambari-logsearch with Apache License 2.0 | 4 votes |
public static Logger createLogger(Input input, LoggerContext loggerContext, LogFeederProps logFeederProps) { boolean useJsonFormat = logFeederProps.isCloudStorageUseFilters(); String type = input.getLogType().replace(LogFeederConstants.CLOUD_PREFIX, ""); String uniqueThreadName = input.getThread().getName(); Configuration config = loggerContext.getConfiguration(); String baseDir = logFeederProps.getRolloverConfig().getRolloverArchiveBaseDir(); String destination = logFeederProps.getCloudStorageDestination().getText(); String clusterHostnameBaseDir = Paths.get(baseDir, destination, logFeederProps.getClusterName(), LogFeederUtil.hostName).toFile().getAbsolutePath(); String activeLogDir = Paths.get(clusterHostnameBaseDir, ACTIVE_FOLDER, type).toFile().getAbsolutePath(); String archiveLogDir = Paths.get(clusterHostnameBaseDir, ARCHIVED_FOLDER, type).toFile().getAbsolutePath(); boolean useGzip = logFeederProps.getRolloverConfig().isUseGzip(); final String archiveFilePattern; if (useJsonFormat) { archiveFilePattern = useGzip ? JSON_DATE_PATTERN_SUFFIX_GZ : JSON_DATE_PATTERN_SUFFIX; } else { archiveFilePattern = useGzip ? DATE_PATTERN_SUFFIX_GZ : DATE_PATTERN_SUFFIX; } String logSuffix = useJsonFormat ? ".json" : ".log"; String fileName = String.join(File.separator, activeLogDir, type + logSuffix); String filePattern = String.join(File.separator, archiveLogDir, type + archiveFilePattern); PatternLayout layout = PatternLayout.newBuilder() .withPattern(PatternLayout.DEFAULT_CONVERSION_PATTERN).build(); String rolloverSize = logFeederProps.getRolloverConfig().getRolloverSize().toString() + logFeederProps.getRolloverConfig().getRolloverSizeFormat(); SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(rolloverSize); final Integer thresholdMin = logFeederProps.getRolloverConfig().getRolloverThresholdTimeMins(); final Integer thresholdInterval = thresholdMin * 60000; // 1 min = 60000 milliseconds TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.newBuilder() .withInterval(thresholdInterval) .build(); final CompositeTriggeringPolicy compositeTriggeringPolicy; if (logFeederProps.getRolloverConfig().isRolloverOnStartup()) { OnStartupTriggeringPolicy onStartupTriggeringPolicy = OnStartupTriggeringPolicy.createPolicy(1); compositeTriggeringPolicy = CompositeTriggeringPolicy .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy, onStartupTriggeringPolicy); } else { compositeTriggeringPolicy = CompositeTriggeringPolicy .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy); } DefaultRolloverStrategy defaultRolloverStrategy = DefaultRolloverStrategy.newBuilder() .withMax(String.valueOf(logFeederProps.getRolloverConfig().getRolloverMaxBackupFiles())) .build(); boolean immediateFlush = logFeederProps.getRolloverConfig().isImmediateFlush(); RollingFileAppender appender = RollingFileAppender.newBuilder() .withFileName(fileName) .withFilePattern(filePattern) .withLayout(layout) .withName(type) .withPolicy(compositeTriggeringPolicy) .withStrategy(defaultRolloverStrategy) .withImmediateFlush(immediateFlush) .build(); appender.start(); config.addAppender(appender); AppenderRef ref = AppenderRef.createAppenderRef(type, null, null); AppenderRef[] refs = new AppenderRef[] {ref}; LoggerConfig loggerConfig = LoggerConfig .createLogger(false, Level.ALL, input.getThread().getName(), "true", refs, null, config, null); loggerConfig.addAppender(appender, null, null); config.addLogger(uniqueThreadName, loggerConfig); loggerContext.updateLoggers(); return loggerContext.getLogger(uniqueThreadName); }
Example 20
Source File: ExecutorLoggerFactory.java From liteflow with Apache License 2.0 | 4 votes |
/** * 创建并启动一个的logger */ private static void start(String loggerName, String logPath) { /** * 设置layout */ Layout layout = PatternLayout .newBuilder() .withConfiguration(config) .withPattern(LAYOUT_TEMPLATE) .build(); String fileName = logPath; /** * 设置appender */ FileAppender fileAppender = FileAppender.newBuilder() .withName(loggerName) .withFileName(fileName) .withLayout(layout) .build(); AppenderRef appenderRef = AppenderRef.createAppenderRef(APPRENDER_REF, APPRENDER_LEVEL, APPRENDER_FILTER); LoggerConfig loggerConfig = LoggerConfig.createLogger( LOGGER_ADDITIVITY, Level.ALL, loggerName, LOGGER_INCLUDE_LOCATIOIN, new AppenderRef[] {appenderRef}, LOGGER_PROPERTY, config, APPRENDER_FILTER ); loggerConfig.addAppender(fileAppender, APPRENDER_LEVEL, APPRENDER_FILTER); /** * 添加appender */ config.addLogger(loggerName, loggerConfig); ctx.updateLoggers(); LOG.info("create logger {}, path is {}", loggerName, logPath); /** * start */ loggerConfig.start(); }