Java Code Examples for org.apache.logging.log4j.LogManager#shutdown()

The following examples show how to use org.apache.logging.log4j.LogManager#shutdown() . 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: Activator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public void stop(final BundleContext context) throws Exception {
    provideRegistration.unregister();
    pluginRegistration.unregister();
    contextDataRegistration.unregister();
    this.contextRef.compareAndSet(context, null);
    LogManager.shutdown(false, true);
}
 
Example 2
Source File: Log4j2RollingExample.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    for(int i = 0; i<2000; i++){
        logger.info("This is the {} time I say 'Hello World'.", i);
        Thread.sleep(100);
    }
    LogManager.shutdown();
}
 
Example 3
Source File: Log4J2Logger.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Cleans up the logger configuration. Should be used in unit tests only for sequential tests run with
 * different configurations
 */
static void cleanup() {
    synchronized (mux) {
        if (inited)
            LogManager.shutdown();

        inited = false;
    }
}
 
Example 4
Source File: ShutdownThread.java    From modernmt with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    long begin = System.currentTimeMillis();

    // Prevent new API requests
    halt(this.node.api);

    // Close internal services
    halt(this.node.translationService); // wait for all translations to be fulfilled
    halt(this.node.database);
    halt(this.node.binaryLog);

    // Stop all engine components
    halt(this.node.getEngine());

    // Stop external services
    for (EmbeddedService service : this.node.services)
        halt(service);

    // Finally set status and halt hazelcast
    this.node.setStatus(ClusterNode.Status.TERMINATED);
    this.node.hazelcast.shutdown();

    long elapsed = System.currentTimeMillis() - begin;
    logger.info("System halted in " + (elapsed / 1000) + "s");

    // Stop log4j2
    LogManager.shutdown();
}
 
Example 5
Source File: BackupDaemonMain.java    From modernmt with Apache License 2.0 5 votes vote down vote up
private void close() {
    try {
        daemon.close();
    } catch (Throwable e) {
        logger.error("Failed to stop engine", e);
    } finally {
        LogManager.shutdown();
    }
}
 
Example 6
Source File: Log4j2Shutdown.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public void shutdown() {
    try {
        // We disabled the log4j shutdown hook to gain more control and keep logs during shutdown.
        // See #disableLog4jShutdownHook()
        // Otoh that means we need to shutdown Log4j manually.
        // So here we go...
        LogManager.shutdown();
    } catch (final Exception e) {
        System.out.println("A problem happened when shutting down Log4j: " + e + "\n" + e.getMessage());
    }
}
 
Example 7
Source File: TestPushRTMsg.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void shutdownProducer() {
    System.out.println("producer shutdown...");
    producer.shutdown();
    LogManager.shutdown();
}
 
Example 8
Source File: AbstractAsyncThreadContextTestBase.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAsyncLogWritesToLog() throws Exception {
    final File[] files = new File[] {
            new File("target", "AsyncLoggerTest.log"), //
            new File("target", "SynchronousContextTest.log"), //
            new File("target", "AsyncLoggerAndAsyncAppenderTest.log"), //
            new File("target", "AsyncAppenderContextTest.log"), //
    };
    for (final File f : files) {
        f.delete();
    }

    ThreadContext.push("stackvalue");
    ThreadContext.put("KEY", "mapvalue");

    final Logger log = LogManager.getLogger("com.foo.Bar");
    final LoggerContext loggerContext = LogManager.getContext(false);
    final String loggerContextName = loggerContext.getClass().getSimpleName();
    RingBufferAdmin ring;
    if (loggerContext instanceof AsyncLoggerContext) {
        ring = ((AsyncLoggerContext) loggerContext).createRingBufferAdmin();
    } else {
        ring = ((AsyncLoggerConfig) ((org.apache.logging.log4j.core.Logger) log).get()).createRingBufferAdmin("");
    }

    for (int i = 0; i < LINE_COUNT; i++) {
        while (i >= 128 && ring.getRemainingCapacity() == 0) { // buffer may be full
            Thread.sleep(1);
        }
        if ((i & 1) == 1) {
            ThreadContext.put("count", String.valueOf(i));
        } else {
            ThreadContext.remove("count");
        }
        log.info("{} {} {} i={}", contextImpl, contextMap(), loggerContextName, Unbox.box(i));
    }
    ThreadContext.pop();
    CoreLoggerContexts.stopLoggerContext(false, files[0]); // stop async thread

    checkResult(files[0], loggerContextName);
    if (asyncMode == Mode.MIXED || asyncMode == Mode.BOTH_ALL_ASYNC_AND_MIXED) {
        for (int i = 1; i < files.length; i++) {
            checkResult(files[i], loggerContextName);
        }
    }
    LogManager.shutdown();
}
 
Example 9
Source File: Log4j2LoggingHelper.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public void shutdownLogging()
{
    LogManager.shutdown();
}
 
Example 10
Source File: MeecrowaveRunMojo.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() {
    if (skip) {
        getLog().warn("Mojo skipped");
        return;
    }
    if (watcherBouncing <= 0 && (reloadGoals == null || reloadGoals.isEmpty())) {
        try {
            reloadGoals = singletonList("process-classes");
        } catch (final RuntimeException re) { // mojo in read only mode
            // no-op
        }
    }
    logConfigurationErrors();

    final Map<String, String> originalSystemProps;
    if (systemProperties != null) {
        originalSystemProps = systemProperties.keySet().stream()
                                              .filter(System.getProperties()::containsKey)
                                              .collect(toMap(identity(), System::getProperty));
        systemProperties.forEach(System::setProperty);
    } else {
        originalSystemProps = null;
    }

    final Thread thread = Thread.currentThread();
    final ClassLoader loader = thread.getContextClassLoader();
    final Supplier<ClassLoader> appLoaderSupplier = createClassLoader(loader);
    thread.setContextClassLoader(appLoaderSupplier.get());
    try {
        final Configuration builder = getConfig();
        try (final Meecrowave meecrowave = new Meecrowave(builder) {
            @Override
            protected void beforeStart() {
                scriptCustomization(jsCustomizers, "js", singletonMap("meecrowaveBase", base.getAbsolutePath()));
            }
        }) {
            meecrowave.start();
            final String fixedContext = ofNullable(context).orElse("");
            final Meecrowave.DeploymentMeta deploymentMeta = new Meecrowave.DeploymentMeta(
                    fixedContext,
                    webapp != null && webapp.isDirectory() ? webapp : null,
                    jsContextCustomizer == null ?
                            null : ctx -> scriptCustomization(
                            singletonList(jsContextCustomizer), "js", singletonMap("context", ctx)));
            deploy(meecrowave, deploymentMeta);
            final Scanner scanner = new Scanner(System.in);
            String cmd;
            boolean quit = false;
            while (!quit && (cmd = scanner.next()) != null) {
                cmd = cmd.trim();
                switch (cmd) {
                    case "": // normally impossible with a Scanner but we can move to another "reader"
                    case "q":
                    case "quit":
                    case "e":
                    case "exit":
                        quit = true;
                        break;
                    case "r":
                    case "reload":
                        reload(meecrowave, fixedContext, appLoaderSupplier, loader);
                        break;
                    default:
                        getLog().error("Unknown command: '" + cmd + "', use 'quit' or 'exit' or 'reload'");
                }
            }
        }
    } finally {
        if (forceLog4j2Shutdown) {
            LogManager.shutdown();
        }
        destroyTcclIfNeeded(thread, loader);
        thread.setContextClassLoader(loader);
        if (originalSystemProps != null) {
            systemProperties.keySet().forEach(k -> {
                final Optional<String> originalValue = ofNullable(originalSystemProps.get(k));
                if (originalValue.isPresent()) {
                    System.setProperty(k, originalValue.get());
                } else {
                    System.clearProperty(k);
                }
            });
        }
    }
}
 
Example 11
Source File: MCRShutdownHandler.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
void shutDown() {
    Logger logger = LogManager.getLogger(MCRShutdownHandler.class);
    String cfgSystemName = "MyCoRe:";
    try {
        cfgSystemName = MCRConfiguration2.getStringOrThrow(PROPERTY_SYSTEM_NAME) + ":";
    } catch (MCRConfigurationException e) {
        //may occur early if there is an error starting mycore up or in JUnit tests
        logger.warn("Error getting '" + PROPERTY_SYSTEM_NAME + "': {}", e.getMessage());
    }
    final String system = cfgSystemName;
    System.out.println(system + " Shutting down system, please wait...\n");
    logger.debug(() -> "requests: " + requests);
    Closeable[] closeables = requests.stream().toArray(Closeable[]::new);
    Stream.of(closeables)
        .peek(c -> logger.debug("Prepare Closing (1): {}", c))
        .forEach(Closeable::prepareClose);
    shutdownLock.writeLock().lock();
    try {
        shuttingDown = true;
        //during shut down more request may come in MCR-1726
        requests.stream()
            .filter(c -> !Arrays.asList(closeables).contains(c))
            .peek(c -> logger.debug("Prepare Closing (2): {}", c))
            .forEach(Closeable::prepareClose);

        requests.stream()
            .peek(c -> logger.debug("Closing: {}", c))
            .forEach(Closeable::close);

        System.out.println(system + " closing any remaining MCRSession instances, please wait...\n");
        MCRSessionMgr.close();
        System.out.println(system + " Goodbye, and remember: \"Alles wird gut.\"\n");
        LogManager.shutdown();
        SINGLETON = null;
    } finally {
        shutdownLock.writeLock().unlock();
    }
    // may be needed in webapp to release file handles correctly.
    if (leakPreventor != null) {
        ClassLoaderLeakPreventor myLeakPreventor = leakPreventor;
        leakPreventor = null;
        myLeakPreventor.runCleanUps();
    }
}
 
Example 12
Source File: SmokeTestBase.java    From log4j2-elasticsearch with Apache License 2.0 4 votes vote down vote up
<T> void indexLogs(Logger logger, Marker marker, int numberOfProducers, Supplier<T> logSupplier) throws InterruptedException {

        final AtomicInteger sleepTime = new AtomicInteger(INITIAL_SLEEP_PER_THREAD);
        CountDownLatch latch = new CountDownLatch(numberOfProducers);

        int numberOfLogsToDeliver = numberOfLogs.get();
        AtomicInteger totalCounter = new AtomicInteger();
        for (int thIndex = 0; thIndex < numberOfProducers; thIndex++) {
            new Thread(() -> {

                for (;numberOfLogs.decrementAndGet() >= 0; totalCounter.incrementAndGet()) {
                    logger.info(marker, logSupplier.get());
                    localCounter.incrementAndGet();
                    try {
                        sleep(sleepTime.get());
                    } catch (InterruptedException e) {
                        interrupted();
                    }

                }
                latch.countDown();
            }).start();
        }

        final int limitPerSec = getInt("smokeTest.limitPerSec", 10000);
        while (latch.getCount() != 0) {
            sleep(1000);
            int count = localCounter.getAndSet(0);
            if (count > limitPerSec && sleepTime.get() != 1) {
                sleepTime.incrementAndGet();
            } else if (sleepTime.get() > 1) {
                sleepTime.decrementAndGet();
            }

            String stats = String.format(
                    "Sleep millis per thread: %d, Current throughput: %d; Progress: %d/%d",
                    sleepTime.get(),
                    count,
                    totalCounter.get(),
                    numberOfLogsToDeliver);

            System.out.println(stats);
        }

        sleep(MILLIS_BEFORE_SHUTDOWN);

        System.out.println("Shutting down");
        LogManager.shutdown();

        sleep(MILLIS_AFTER_SHUTDOWN);

    }
 
Example 13
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 4 votes vote down vote up
@AfterEach
void cleanUp() {
    LogManager.shutdown();
}
 
Example 14
Source File: VelocityServer.java    From Velocity with MIT License 4 votes vote down vote up
@EnsuresNonNull({"serverKeyPair", "servers", "pluginManager", "eventManager", "scheduler",
    "console", "cm", "configuration"})
void start() {
  logger.info("Booting up {} {}...", getVersion().getName(), getVersion().getVersion());
  console.setupStreams();

  serverKeyPair = EncryptionUtils.createRsaKeyPair(1024);

  cm.logChannelInformation();

  // Initialize commands first
  commandManager.register(new VelocityCommand(this), "velocity");
  commandManager.register(new ServerCommand(this), "server");
  commandManager.register(new ShutdownCommand(this), "shutdown", "end");
  commandManager.register(new GlistCommand(this), "glist");

  try {
    Path configPath = Paths.get("velocity.toml");
    configuration = VelocityConfiguration.read(configPath);

    // Resave config to add new values
    AnnotatedConfig.saveConfig(configuration.dumpConfig(), configPath);

    if (!configuration.validate()) {
      logger.error("Your configuration is invalid. Velocity will not start up until the errors "
          + "are resolved.");
      LogManager.shutdown();
      System.exit(1);
    }
  } catch (Exception e) {
    logger.error("Unable to read/load/save your velocity.toml. The server will shut down.", e);
    LogManager.shutdown();
    System.exit(1);
  }

  for (Map.Entry<String, String> entry : configuration.getServers().entrySet()) {
    servers.register(new ServerInfo(entry.getKey(), AddressUtil.parseAddress(entry.getValue())));
  }

  ipAttemptLimiter = Ratelimiters.createWithMilliseconds(configuration.getLoginRatelimit());
  httpClient = new NettyHttpClient(this);
  loadPlugins();

  // Go ahead and fire the proxy initialization event. We block since plugins should have a chance
  // to fully initialize before we accept any connections to the server.
  eventManager.fire(new ProxyInitializeEvent()).join();

  // init console permissions after plugins are loaded
  console.setupPermissions();

  final Integer port = this.options.getPort();
  if (port != null) {
    logger.debug("Overriding bind port to {} from command line option", port);
    this.cm.bind(new InetSocketAddress(configuration.getBind().getHostString(), port));
  } else {
    this.cm.bind(configuration.getBind());
  }

  if (configuration.isQueryEnabled()) {
    this.cm.queryBind(configuration.getBind().getHostString(), configuration.getQueryPort());
  }

  Metrics.VelocityMetrics.startMetrics(this, configuration.getMetrics());
}
 
Example 15
Source File: TestPushRTMsg.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void shutdownProducer() {
    System.out.println("producer shutdown...");
    producer.shutdown();
    LogManager.shutdown();
}
 
Example 16
Source File: TestPushDelayMsg.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void shutdownProducer() {
    System.out.println("producer shutdown...");
    producer.shutdown();
    LogManager.shutdown();
}
 
Example 17
Source File: TestPushDelayMsg.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void shutdownProducer() {
    System.out.println("producer shutdown...");
    producer.shutdown();
    LogManager.shutdown();
}
 
Example 18
Source File: StartupLoggingUtils.java    From lucene-solr with Apache License 2.0 3 votes vote down vote up
/**
 * Perhaps odd to put in startup utils, but this is where the logging-init code is so it seems logical to put the
 * shutdown here too.
 *
 * Tests are particularly sensitive to this call or the object release tracker will report "lmax.disruptor" not
 * terminating when asynch logging (new default as of 8.1) is enabled.
 *
 * Expert, there are rarely good reasons for this to be called outside of the test framework. If you are tempted to
 * call this for running Solr, you should probably be using synchronous logging.
 */
@SuppressForbidden(reason = "Legitimate log4j2 access")
public static void shutdown() {
  if (!isLog4jActive()) {
    logNotSupported("Not running log4j2, could not call shutdown for async logging.");
    return;
  }
  flushAllLoggers();
  LogManager.shutdown(true);
}
 
Example 19
Source File: App.java    From robozonky with Apache License 2.0 2 votes vote down vote up
/**
 * Will terminate the application. Call this on every exit of the app to ensure proper termination. Failure to do
 * so may result in unpredictable behavior of this instance of RoboZonky or future ones.
 * 
 * @param result Will be passed to {@link System#exit(int)}.
 */
void exit(final ReturnCode result) {
    LOGGER.trace("Exit requested with return code {}.", result);
    LogManager.shutdown(); // Wait for async logging to finish before shutting down.
    actuallyExit(result.getCode());
}