private void toggleCleanLogging() { this.cleanLogging = !cleanLogging; interactionHandler.sendText("clean logging: " + cleanLogging); String appenderToAdd = cleanLogging ? "Clean" : "Console"; String appenderToRemove = cleanLogging ? "Console" : "Clean"; final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); for (org.apache.logging.log4j.core.Logger logger : ctx.getLoggers()) { logger.removeAppender(config.getAppender(appenderToRemove)); config.addLoggerAppender(logger, config.getAppender(appenderToAdd)); } ctx.updateLoggers(); }
@Override public boolean init(String botId, Map<String, String> configs, String[] channels) { logger = LogManager.getLogger(TelegramBot.class.getSimpleName() + ":" + botId); this.configs = configs; try { telegramBotsApi.registerBot(this); } catch (TelegramApiRequestException e) { logger.error(e); return false; } this.botId = botId; return true; }
public DebeziumPipeLine(Context cxt, SourceConfig conf, String topic) throws BiremeException { super(cxt, conf, "Debezium-" + conf.name + "-" + topic); this.conf = conf; List<TopicPartition> topicPartition = consumer.partitionsFor(topic) .stream() .map(p -> new TopicPartition(p.topic(), p.partition())) .collect(Collectors.toList()); consumer.subscribe(Arrays.asList(topic)); logger = LogManager.getLogger("Bireme." + myName); logger.info("Create new Debezium PipeLine. Name: {}", myName); if (topicPartition.size() > 1) { logger.error("Topic {} has {} partitions", topic, topicPartition.size()); String message = "Topic has more than one partitions"; throw new BiremeException(message); } }
@Test public void test() { { Logger logger = LogManager.getLogger("test.logger"); logger.error("This is an error!"); logger.error("This is another error!"); logger.error("This is a third error!"); } assertThat(collector.getLogs()).hasSize(3) .contains("This is an error!", "This is another error!", "This is a third error!"); List<LogEvent> rawLogs = (List<LogEvent>) collector.getRawLogs(); assertThat(rawLogs).hasSize(3); assertTrue(rawLogs.stream().allMatch(l -> l.getLevel() == Level.ERROR)); }
public List<PoloniexChartData> mapChartData(String chartDataResult) { if (INVALID_CHART_DATA_DATE_RANGE_RESULT.equals(chartDataResult) || INVALID_CHART_DATA_CURRENCY_PAIR_RESULT.equals(chartDataResult)) { return Collections.EMPTY_LIST; } List<PoloniexChartData> results; try { PoloniexChartData[] chartDataResults = gson.fromJson(chartDataResult, PoloniexChartData[].class); results = Arrays.asList(chartDataResults); } catch (JsonSyntaxException | DateTimeParseException ex) { LogManager.getLogger().error("Exception mapping chart data {} - {}", chartDataResult, ex.getMessage()); results = Collections.EMPTY_LIST; } return results; }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("m", TIME_FRAME.MIN60, "19980101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(DblMaPsarStrategy.class, new Integer[]{3, 5, 1}, new Integer[]{10, 100, 2}, MA.MA_MODES, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.12f, 0.2f, 0.02f}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
@Override public PoloniexLendingResult toggleAutoRenew(String orderNumber) { long start = System.currentTimeMillis(); PoloniexLendingResult result = null; try { String res = tradingClient.toggleAutoRenew(orderNumber); result = mapper.mapLendingResult(res); LogManager.getLogger(PoloniexLendingService.class).trace("Executed and mapped toggleAutoRenew for {} in {} ms", orderNumber, System.currentTimeMillis() - start); } catch (Exception ex) { LogManager.getLogger(PoloniexLendingService.class).error("Error executing toggleAutoRenew for {} - {}", orderNumber, ex.getMessage()); } return result; }
@Override public boolean init(String botId, Map<String, String> configs, String[] channels) { logger = LogManager.getLogger(IrcBot.class.getSimpleName() + ":" + botId); if (!configs.containsKey(USERNAME_KEY)) return false; if (!configs.containsKey(HOST_KEY)) return false; client = Client.builder() .nick(configs.get(USERNAME_KEY)) .serverHost(configs.get(HOST_KEY)) .listenInput(line -> logger.debug("[I]: " + line)) .listenOutput(line -> logger.debug("[O]: " + line)) .listenException(logger::error) .defaultMessageMap(new SimpleDefaultMessageMap()) .build(); client.getEventManager().registerEventListener(this); this.botId = botId; this.configs = configs; this.channels = channels; return true; }
private void func_181670_b(int p_181670_1_) { if (p_181670_1_ > this.rawIntBuffer.remaining()) { int i = this.byteBuffer.capacity(); int j = i % 2097152; int k = j + (((this.rawIntBuffer.position() + p_181670_1_) * 4 - j) / 2097152 + 1) * 2097152; LogManager.getLogger().warn("Needed to grow BufferBuilder buffer: Old size " + i + " bytes, new size " + k + " bytes."); int l = this.rawIntBuffer.position(); ByteBuffer bytebuffer = GLAllocation.createDirectByteBuffer(k); this.byteBuffer.position(0); bytebuffer.put(this.byteBuffer); bytebuffer.rewind(); this.byteBuffer = bytebuffer; this.rawFloatBuffer = this.byteBuffer.asFloatBuffer().asReadOnlyBuffer(); this.rawIntBuffer = this.byteBuffer.asIntBuffer(); this.rawIntBuffer.position(l); this.field_181676_c = this.byteBuffer.asShortBuffer(); this.field_181676_c.position(l << 1); } }
@Before public void setUp() throws Exception { registry = RegistryService.getMetricRegistry(); meters = new HashMap<>(); meters.put("total", getMeter(APPENDS_BASE_NAME.submetric("total"))); meters.put("trace", getMeter(APPENDS_BASE_NAME.withTags("level", "trace"))); meters.put("debug", getMeter(APPENDS_BASE_NAME.withTags("level", "debug"))); meters.put("info", getMeter(APPENDS_BASE_NAME.withTags("level", "info"))); meters.put("warn", getMeter(APPENDS_BASE_NAME.withTags("level", "warn"))); meters.put("error", getMeter(APPENDS_BASE_NAME.withTags("level", "error"))); meters.put("fatal", getMeter(APPENDS_BASE_NAME.withTags("level", "fatal"))); meters.put("throwCount", getMeter(THROWABLES_BASE_NAME.submetric("total"))); meters.put("throw[RuntimeException]", getMeter(THROWABLES_BASE_NAME .withTags("class", RuntimeException.class.getName()) )); logger = LogManager.getLogger(Log4J2InstrumentationTest.class.getName()); origLevel = logger.getLevel(); setLogLevel(logger, Level.ALL); }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("i", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(MaPsarStrategy.class, new Integer[]{12, 500, 2}, new String[]{MA.MODE_EMA, MA.MODE_SMMA}, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.1f, 0.2f, 0.02f}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
protected static void initLog(){ if (AschSDK.Config.isDebugMode()) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.getConfiguration() .getRootLogger() .setLevel(Level.ALL); } }
/** * Gets the {@link LoggerContext} associated with the given caller class. * * @param callerClass the caller class * @return the LoggerContext for the calling class */ protected LoggerContext getContext(final Class<?> callerClass) { ClassLoader cl = null; if (callerClass != null) { cl = callerClass.getClassLoader(); } if (cl == null) { cl = LoaderUtil.getThreadContextClassLoader(); } return LogManager.getContext(cl, false); }
/** * When the user changes the log level and new {@link Runnable} command is added to {@link Settings}. * <p> * Command run when the user applies the change in setting. * * @param event action event */ @FXML public void onLogLevelChanged(final ActionEvent event) { settings.addRunnable(() -> { final String logLevel = choiceBox.getSelectionModel().getSelectedItem(); final Logger logger = LogManager.getRootLogger(); Configurator.setLevel(logger.getName(), Level.toLevel(logLevel)); LOGGER.info("Log level was set to: " + Level.toLevel(logLevel)); }); event.consume(); }
/** * This test will set the value of {@link LoggingSettingsViewController} {@link ChoiceBox} to value to different * from the current {@link Level}. * <p> * The {@link LoggingSettingsViewController#onLogLevelChanged(ActionEvent)} method * will be called which creates a new {@link Runnable} containing the command to update the {@link Level}. * <p> * The {@link Runnable} will be added to the {@link Settings} using {@link Settings#addRunnable(Runnable)}. * {@link Settings} has been mocked and and a {@link ArgumentCaptor} has been added to intercept the runnable. After * then runnable has been intercepted it can be invoked. * <p> * This test will then succeed if the log {@link Level} has been changed accordingly. */ @Test void testChangeLogLevelRunnable() { final ChoiceBox<String> choiceBox = new ChoiceBox<>(); String currentLevel = LogManager.getRootLogger().getLevel().toString(); final String newLevel; if (currentLevel.equals("ERROR")) { choiceBox.setValue("DEBUG"); newLevel = "DEBUG"; } else { choiceBox.setValue("ERROR"); newLevel = "ERROR"; } assertThat(currentLevel).isNotEqualTo(newLevel); loggingSettingsViewController.setChoiceBox(choiceBox); final ActionEvent event = new ActionEvent(); interact(() -> loggingSettingsViewController.onLogLevelChanged(event)); final ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); verify(settingsMock).addRunnable(captor.capture()); final Runnable command = captor.getValue(); command.run(); currentLevel = LogManager.getRootLogger().getLevel().toString(); assertThat(currentLevel).isEqualTo(newLevel); }
@Test public void test_serialized_event() throws IOException { String lookupTestKey = "lookup_test_key"; String lookupTestVal = String.format("lookup_test_value_%d", (int) (1000 * Math.random())); System.setProperty(lookupTestKey, lookupTestVal); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration loggerConfig = loggerContext.getConfiguration(); for (LogEvent logEvent : LogEventFixture.LOG_EVENTS) { checkLogEvent(loggerConfig, logEvent, lookupTestKey, lookupTestVal); } }
private Logger getLogger(String name) { Logger logger = cachedLoggers.get(name); if (logger == null) { logger = LogManager.getLogger(name); cachedLoggers.put(name, logger); } return logger; }
public static void main(String[] args) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN); ctx.updateLoggers(config); final CommonParam cp = ParamManager.getCommonParam("ru", TIME_FRAME.DAY, "20100101 000000", "20160101 170000"); StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class); so.setInstrumentParam(cp.instrument, cp.tf); so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date)); int num = so.setStrategyParamRange(AlligatorDivergent.class, new Float[]{0.01f, 0.01f, 0.01f}, new Float[]{0.1999f, 0.1999f, 0.01f}, new Integer[]{4, 10, 1}, new Float[]{1.0f, 3.0f, 0.5f}, new Float[]{10.0f, 1100.0f, 5.0f}); System.out.println(num); so.StartOptimization(); Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet(); for (Entry<Object[],Performances> entry : entryset) { for (Object obj : entry.getKey()) { System.out.print(obj + ",\t"); } System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown); } }
/** * Creates a new logger. * * @return logger */ public static PetBlockFilter create() { final PetBlockFilter petBlockFilter = new PetBlockFilter(); petBlockFilter.start(); ((org.apache.logging.log4j.core.Logger) LogManager.getRootLogger()).addFilter(petBlockFilter); return petBlockFilter; }
/** * Activates the app silent mode. */ private static void activateSilent() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(Level.OFF); ctx.updateLoggers(); }
public static void main(String[] args) throws InterruptedException { System.setProperty("log4j.configurationFile", "log4j2.xml"); Logger logger = LogManager.getLogger("elasticsearch"); AtomicInteger counter = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(10); for (int thIndex = 0; thIndex < 100; thIndex++) { new Thread(() -> { for (int msgIndex = 0; msgIndex < 10000; msgIndex++) { logger.info("Message " + counter.incrementAndGet()); try { sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } latch.countDown(); }).start(); } while (latch.getCount() != 0) { sleep(1000); System.out.println("Added " + counter + " messages"); } sleep(5000); // LogManager.shutdown(); }
private static void configure(final Settings settings, final Path configsPath, final Path logsPath) throws IOException, UserException { Objects.requireNonNull(settings); Objects.requireNonNull(configsPath); Objects.requireNonNull(logsPath); setLogConfigurationSystemProperty(logsPath, settings); // we initialize the status logger immediately otherwise Log4j will complain when we try to get the context configureStatusLogger(); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final List<AbstractConfiguration> configurations = new ArrayList<>(); final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory(); final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (file.getFileName().toString().equals("log4j2.properties")) { configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri())); } return FileVisitResult.CONTINUE; } }); if (configurations.isEmpty()) { throw new UserException( ExitCodes.CONFIG, "no log4j2.properties found; tried [" + configsPath + "] and its subdirectories"); } context.start(new CompositeConfiguration(configurations)); configureLoggerLevels(settings); }
public static Appender findAppender(final Logger logger, final Class<? extends Appender> clazz) { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); final LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); for (final Map.Entry<String, Appender> entry : loggerConfig.getAppenders().entrySet()) { if (entry.getValue().getClass().equals(clazz)) { return entry.getValue(); } } return null; }
/** * Creates a new deprecation logger based on the parent logger. Automatically * prefixes the logger name with "deprecation", if it starts with "org.elasticsearch.", * it replaces "org.elasticsearch" with "org.elasticsearch.deprecation" to maintain * the "org.elasticsearch" namespace. */ public DeprecationLogger(Logger parentLogger) { String name = parentLogger.getName(); if (name.startsWith("org.elasticsearch")) { name = name.replace("org.elasticsearch.", "org.elasticsearch.deprecation."); } else { name = "deprecation." + name; } this.logger = LogManager.getLogger(name); }
@Override public void onApplicationEvent(final ContextClosedEvent event) { logger.info("Gracefully shutting down application."); manager.stop(); try { manager.tearDown(); logger.info("JOAL gracefully shut down."); } catch (final IOException e) { logger.error("Failed to gracefully shut down JOAL.", e); } // Since we disabled log4j2 shutdown hook, we need to handle it manually. final LifeCycle loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.stop(); }
public void testIndexWriterInfoStream() throws IllegalAccessException, IOException { assumeFalse("who tests the tester?", VERBOSE); MockAppender mockAppender = new MockAppender("testIndexWriterInfoStream"); mockAppender.start(); Logger rootLogger = LogManager.getRootLogger(); Level savedLevel = rootLogger.getLevel(); Loggers.addAppender(rootLogger, mockAppender); Loggers.setLevel(rootLogger, Level.DEBUG); rootLogger = LogManager.getRootLogger(); try { // First, with DEBUG, which should NOT log IndexWriter output: ParsedDocument doc = testParsedDocument("1", "test", null, testDocumentWithTextField(), B_1, null); engine.index(indexForDoc(doc)); engine.flush(); assertFalse(mockAppender.sawIndexWriterMessage); // Again, with TRACE, which should log IndexWriter output: Loggers.setLevel(rootLogger, Level.TRACE); engine.index(indexForDoc(doc)); engine.flush(); assertTrue(mockAppender.sawIndexWriterMessage); } finally { Loggers.removeAppender(rootLogger, mockAppender); mockAppender.stop(); Loggers.setLevel(rootLogger, savedLevel); } }
/** * Configure the FML logger and inject tracing printstreams. */ private static void configureLogging() { log.myLog = LogManager.getLogger("FML"); // Default side to client for test harness purposes if (side == null) side = Side.CLIENT; ThreadContext.put("side", side.name().toLowerCase(Locale.ENGLISH)); configured = true; FMLRelaunchLog.fine("Injecting tracing printstreams for STDOUT/STDERR."); System.setOut(new TracingPrintStream(LogManager.getLogger("STDOUT"), System.out)); System.setErr(new TracingPrintStream(LogManager.getLogger("STDERR"), System.err)); }
@Override public String returnTicker() { try { String url = PUBLIC_URL + "command=returnTicker"; return client.getHttp(url, null); } catch (IOException ex) { LogManager.getLogger(PoloniexPublicAPIClient.class).warn("Call to return ticker API resulted in exception - " + ex.getMessage(), ex); } return null; }
public Log4j2Impl(String clazz) { Logger logger = LogManager.getLogger(clazz); if (logger instanceof AbstractLogger) { log = new Log4j2AbstractLoggerImpl((AbstractLogger) logger); } else { log = new Log4j2LoggerImpl(logger); } }
/** * Initializes default values. This is called by ConfigHandler. * @param tickTime */ public static void initConfig(int tickTime, String[] dimensionList){ tickSpeed = tickTime; for(String s:dimensionList){ if(ConfigHandler.LOGGING)LogManager.getLogger().log(Level.INFO, "Dimension added to tick list: " + s); dimensionsToTick.add(Integer.parseInt(s)); } }
public static void main(String[] args) { Log4J2Fix.applyHotFix(); version = Version.getInstance(); LOGGER = LogManager.getLogger(ReqmanApplication.class); LOGGER.info(LoggingUtils.REQMAN_MARKER, "Starting reqman @ v" + version.getFullVersion()); launch(args); }
@Test public void test() { { Logger logger = LogManager.getLogger("test.logger"); logger.error("This is an error!"); logger.error("This is another error!"); } assertThat(collector.getLogs()) .hasSize(2) .contains("This is an error!", "This is another error!"); }
/** * Constructor * * @param p_shortName * Short name of the service (used for terminal) */ protected AbstractDXRAMService(final String p_shortName, final Class<T> p_configClass) { LOGGER = LogManager.getFormatterLogger(getClass().getSimpleName()); m_shortName = p_shortName; // create default configuration try { m_config = p_configClass.newInstance(); } catch (final InstantiationException | IllegalAccessException e) { throw new DXRAMRuntimeException(e); } }
/** * Set the log level for the logger. * Method is used in js script. * * @param p_logLevel * Log level to set. */ @SuppressWarnings("WeakerAccess") public static void setLogLevel(final Level p_logLevel) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); loggerConfig.setLevel(p_logLevel); // This causes all Loggers to refetch information from their LoggerConfig ctx.updateLoggers(); }
/** * Handles minecraft starting. */ public static void handleMinecraftStart() { Logger novousStart = LogManager.getLogger("NovousStart"); novousStart.info("Reached Implementation::handleMinecraftStart()"); handleLoggingImplementation(novousStart); handleModLoading(novousStart); handleModPreInit(novousStart); handleBlockRegistration(novousStart); }
private static void configureLogMetrics() { InstrumentedAppender appender = InstrumentedAppender.createAppender("PROMETHEUS"); appender.start(); LoggerContext context = (LoggerContext) LogManager.getContext(false); Configuration config = context.getConfiguration(); config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, null, null); context.updateLoggers(config); }
protected Logger createLogger() throws IOException { // create configuration with log-file and log-level this.configDirectory = new File(getUniqueName()); this.configDirectory.mkdir(); assertTrue(this.configDirectory.isDirectory() && this.configDirectory.canWrite()); // copy the log4j2-test.xml to the configDirectory // final URL srcURL = // getClass().getResource("/org/apache/geode/internal/logging/log4j/log4j2-test.xml"); final URL srcURL = getClass().getResource("log4j2-test.xml"); final File src = new File(srcURL.getFile()); FileUtils.copyFileToDirectory(src, this.configDirectory); this.config = new File(this.configDirectory, "log4j2-test.xml"); assertTrue(this.config.exists()); this.logFile = new File(this.configDirectory, DistributionConfig.GEMFIRE_PREFIX + "log"); final String logFilePath = IOUtils.tryGetCanonicalPathElseGetAbsolutePath(logFile); final String logFileName = FileUtil.stripOffExtension(logFilePath); setPropertySubstitutionValues(logFileName, DEFAULT_LOG_FILE_SIZE_LIMIT, DEFAULT_LOG_FILE_COUNT_LIMIT); final String configPath = "file://" + IOUtils.tryGetCanonicalPathElseGetAbsolutePath(this.config); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, configPath); final Logger logger = LogManager.getLogger(); return logger; }
public static void main(String[] args) { final Logger logger = LogManager.getLogger(StartSECC.class.getSimpleName()); MiscUtils.setV2gEntityConfig(GlobalValues.SECC_CONFIG_PROPERTIES_PATH.toString()); UDPServer udpServer = UDPServer.getInstance(); TCPServer tcpServer = TCPServer.getInstance(); TLSServer tlsServer = TLSServer.getInstance(); if (!udpServer.initialize() || !tlsServer.initialize() || !tcpServer.initialize()) { logger.fatal("Unable to start SECC because UDP, TCP or TLS server could not be initialized"); } else { Thread udpServerThread = new Thread(udpServer); udpServerThread.setName("UDPServerThread"); Thread tcpServerThread = new Thread(tcpServer); tcpServerThread.setName("TCPServerThread"); Thread tlsServerThread = new Thread(tlsServer); tlsServerThread.setName("TLSServerThread"); // All transport layer threads need to be initialized before initializing the SECC session handler. new V2GCommunicationSessionHandlerSECC(); /* * To avoid possible race conditions, the transport layer threads need to be started AFTER the SECC * session handler has been initialized. Otherwise the situation might occur that the UDPServer is * receiving a UDP client packet and tries to access the MessageHandler object before this object has * been created by the SECC session handler. */ udpServerThread.start(); tcpServerThread.start(); tlsServerThread.start(); } }
@SubscribeEvent public static void worldTick(WorldTickEvent event){ // I only want to tick on the server if(event.world.isRemote){return;} // If I don't have this code everything runs twice per tick if(event.phase == Phase.END){return;} if(Math.floorMod(event.world.getTotalWorldTime(), tickSpeed) != 0){return;} TickTracker tickTracker = getTickTrackerForDimension(event.world.provider.getDimension()); if(!tickTracker.trackedWorldHasPlayers()){ if(tickTracker.worldToTick == nextWorldToTick){ tickTracker.hasTicked = true; findNextWorldToTick(); } return; } if(!tickTracker.hasTicked && tickTracker.worldToTick == nextWorldToTick && event.world.getTotalWorldTime() > lastTickProcessed){ if(dimensionsToTick.contains(tickTracker.worldToTick)){ if(ConfigHandler.LOGGING)LogManager.getLogger().log(Level.INFO, "We're ticking in this dimension: " + tickTracker.worldToTick); if(tickTracker.trackedWorldHasPlayers() && tickTracker.playerToTick < event.world.playerEntities.size()){ SpawnHandler.attemptSpawnNearPlayer(event.world.playerEntities.get(tickTracker.playerToTick), event.world); tickTracker.setNextPlayerToTick(event.world); } } tickTracker.hasTicked = true; findNextWorldToTick(); lastTickProcessed = event.world.getTotalWorldTime(); return; } // if we get to this point, a world has probably unloaded and eaten our tick tracker, so find a new world to tick on if(DimensionManager.getWorld(nextWorldToTick) == null){ if(ConfigHandler.LOGGING)LogManager.getLogger().log(Level.WARN, "Tracker lost, generating new tracker."); findNextWorldToTick(); } }
public Object call() throws Exception { // Setup for capturing logger messages Appender mockAppender = mock(Appender.class); when(mockAppender.getName()).thenReturn("MockAppender"); when(mockAppender.isStarted()).thenReturn(true); when(mockAppender.isStopped()).thenReturn(false); Logger logger = (Logger) LogManager.getLogger(ColocationLogger.class); logger.addAppender(mockAppender); logger.setLevel(Level.WARN); loggingEventCaptor = ArgumentCaptor.forClass(LogEvent.class); // Logger interval may have been hooked by the test, so adjust test delays here int logInterval = ColocationLogger.getLogInterval(); List<LogEvent> logEvents = Collections.emptyList(); try { createPR(PR_REGION_NAME, true); createPR("region2", PR_REGION_NAME, true); // This child region is never created // Let this thread continue running long enough for the missing region to be logged a // couple times. // Grandchild region does not get created by this thread. (1.5*logInterval < delay < // 2*logInterval) await().atMost((int) (1.75 * logInterval), TimeUnit.MILLISECONDS).until(() -> { verify(mockAppender, times(numExpectedLogMessages)) .append(loggingEventCaptor.capture()); }); // createPR("region3", PR_REGION_NAME, true); // This child region is never created } finally { logEvents = loggingEventCaptor.getAllValues(); assertEquals(String.format("Expected %d messages to be logged, got %d.", numExpectedLogMessages, logEvents.size()), numExpectedLogMessages, logEvents.size()); String logMsg = logEvents.get(0).getMessage().getFormattedMessage(); logger.removeAppender(mockAppender); numExpectedLogMessages = 1; return logMsg; } }