Java Code Examples for org.slf4j.LoggerFactory

The following are top voted examples for showing how to use org.slf4j.LoggerFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: vars-annotation   File: AppDemo.java   View source code 6 votes vote down vote up
/**
 *
 * @param args
 */
public static void main(String[] args) {
    Logger log = LoggerFactory.getLogger(AppDemo.class);
    Initializer.getToolBox()
            .getEventBus()
            .toObserverable()
            .subscribe(e -> log.debug(e.toString()));
    App.main(args);

    ObservableList<Annotation> annotations = Initializer.getToolBox()
            .getData()
            .getAnnotations();

    annotations.addListener((InvalidationListener) observable ->
            log.debug("Annotation count: " + annotations.size()));
}
 
Example 2
Project: homunculus   File: EEMethodsPreDestroy.java   View source code 6 votes vote down vote up
private void execNextMethod(Scope scope, Object instance, List<MyMethod> methods, ProcessingCompleteCallback callback, List<Throwable> failures) {
    if (methods.isEmpty()) {
        LoggerFactory.getLogger(instance.getClass()).debug("{}[email protected] complete", instance.getClass().getSimpleName());
        callback.onComplete(scope, instance, failures);
    } else {
        MyMethod method = methods.remove(0);
        method.handler.post(() -> {
            LoggerFactory.getLogger(instance.getClass()).debug("{}.{}()", instance.getClass().getSimpleName(), method.method.getName());
            try {
                method.method.invoke(instance);
            } catch (Throwable t) {
                LoggerFactory.getLogger(instance.getClass()).error("{}.{}() -> {}", instance.getClass().getSimpleName(), method.method.getName(), t);
                failures.add(t);
            }
            execNextMethod(scope, instance, methods, callback, failures);
        });
    }
}
 
Example 3
Project: homunculus   File: HomunculusActivity.java   View source code 6 votes vote down vote up
/**
 * Saves the current stack state into the given bundle by using the serializer in {@link #getInstanceStateSerializer()}
 *
 * @param outState the target
 */
protected void saveStackState(Bundle outState) {
    NavigationBuilder nb = getNavigation();
    if (nb instanceof Navigation) {
        //create a defensive copy into a serializable list
        ArrayList<Request> tmp = new ArrayList<>(((Navigation) nb).getStack());
        try {
            //serialize simply into a byte array
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            getInstanceStateSerializer().serialize(tmp, bout);
            outState.putByteArray(HC_NAVIGATION_STACK, bout.toByteArray());
        } catch (IOException e) {
            //clean it out, in case of programming error
            outState.putByteArray(HC_NAVIGATION_STACK, null);
            LoggerFactory.getLogger(getClass()).warn("onSaveInstanceState: the navigation stack contains a value which is not serializable by {}. Reason:", getInstanceStateSerializer(), e);
        }

    } else {
        //clean it out, if no navigation is available
        outState.putByteArray(HC_NAVIGATION_STACK, null);
        LoggerFactory.getLogger(getClass()).warn("onSaveInstanceState: getNavigation() does not provide a Navigation instance");
    }
}
 
Example 4
Project: uroborosql   File: SqlREPL.java   View source code 6 votes vote down vote up
/**
 * メインメソッド
 *
 * @param args 読み込むプロパティファイルのファイルパス
 */
public static void main(final String... args) {
	((Logger) LoggerFactory.getLogger("jp.co.future.uroborosql")).setLevel(Level.DEBUG);

	String propFile = "repl.properties";
	if (args.length != 0) {
		propFile = args[0];
	}

	Path path = Paths.get(propFile);

	if (!Files.exists(path)) {
		throw new IllegalArgumentException("properties could not found.");
	}

	try {
		SqlREPL repl = new SqlREPL(path);
		repl.execute();
	} catch (Exception ex) {
		throw new IllegalStateException("Failed to REPL.", ex);
	}
}
 
Example 5
Project: TOSCAna   File: ExportingImageBuilderIT.java   View source code 6 votes vote down vote up
@Test
public void testBuildShaImage() throws Exception {
    assumeTrue(DockerTestUtils.isDockerAvailable());
    //Create Dockerfile and the corresponding Binary file
    shaDigest = buildSHADockerfile();

    init();
    
    TransformationContext ctx = mock(TransformationContext.class);
    when(ctx.getPluginFileAccess()).thenReturn(access);
    when(ctx.getLogger((Class<?>) any(Class.class))).thenReturn(LoggerFactory.getLogger("Mock Logger"));
    
    imageBuilder = instantiateImageBuilder(ctx);
    logger.info("Building Image");
    imageBuilder.buildImage();
    logger.info("Storing Image");
    imageBuilder.storeImage();
    
    validate(imageBuilder.getTag());
}
 
Example 6
Project: flux-capacitor-client   File: AbstractFluxCapacitorConfiguration.java   View source code 6 votes vote down vote up
protected Configurer configureSagaManagers(Configurer configurer) {
    Configuration configuration = ReflectionUtils.getField("config", configurer);
    configuration.getModules().forEach(m -> {
        if (m instanceof SagaConfiguration) {
            SagaConfiguration sagaConfig = (SagaConfiguration) m;
            Component<EventProcessor> processorComponent = ReflectionUtils.getField("processor", sagaConfig);
            String name = ReflectionUtils.getField("name", processorComponent);
            processorComponent.update(c -> {
                String processorName = format("%s/%s", applicationProperties.getApplicationName(), name);
                Logger logger = LoggerFactory.getLogger(processorName);
                return new FluxCapacitorEventProcessor(
                        processorName, sagaConfig.getSagaManager(),
                        RollbackConfigurationType.ANY_THROWABLE,
                        errorContext -> logger.error("Failed to handle events on saga", errorContext.error()),
                        c.messageMonitor(FluxCapacitorEventProcessor.class, processorName), getEventConsumerService(),
                        c.getComponent(AxonMessageSerializer.class), 1);
            });
        }
    });
    return configurer;
}
 
Example 7
Project: klask-io   File: MetricsConfiguration.java   View source code 6 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }

    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example 8
Project: OftenPorter   File: MainMixinLoop1.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    /**
     * 1.测试{@linkplain cn.xishan.oftenporter.porter.core.annotation.Mixin},自己混入自己
     */
    final Logger logger = LoggerFactory.getLogger(MainMixinLoop1.class);

    LocalMain localMain = new LocalMain(true, new PName("P1"), "utf-8");

    // 进行配置
    PorterConf conf = localMain.newPorterConf();
    conf.setContextName("MainMixinLoop1");
    conf.getSeekPackages().addClassPorter(RootPorter.class);
    localMain.startOne(conf);
    logger.debug("****************************************************");


    logger.debug("****************************************************");
    localMain.destroyAll();

}
 
Example 9
Project: Endless   File: GuildEvents.java   View source code 6 votes vote down vote up
@Override
public void onGuildLeave(GuildLeaveEvent event)
{
    Guild guild = event.getGuild();
    User owner = guild.getOwner().getUser();
    LoggerFactory.getLogger("Logging").info("[GUILD LEFT]: "+guild.getName()+" (ID: "+guild.getId()+")\n");
    long botCount = guild.getMembers().stream().map(m -> m.getUser()).filter(u -> u.isBot()).count();
    long userCount = guild.getMembers().stream().map(m -> m.getUser()).filter(u -> !(u.isBot())).count();
    long totalCount = guild.getMembers().size();
    TextChannel tc = event.getJDA().getTextChannelById(config.getBotlogChannelId());
    String reason = getReason(guild);

    if(config.isBotlogEnabled() && !(tc==null) && tc.canTalk())
    {
        StringBuilder builder = new StringBuilder().append(":outbox_tray: `[Left Guild]:` "+guild.getName()+" (ID: "+guild.getId()+")\n" +
                "`[Owner]:` **"+owner.getName()+"**#**"+owner.getDiscriminator()+"** (ID: "+owner.getId()+"\n" +
                "`[Members]:` Humans: **"+userCount+"** Bots: **"+botCount+"** Total Count: **"+totalCount+"**\n");

        if(!(reason==null))
            builder.append("`[Reason]:` "+reason);

        tc.sendMessage(builder.toString()).queue();
    }
}
 
Example 10
Project: avrocount   File: AvroCountTool.java   View source code 6 votes vote down vote up
private static boolean redirectLogger(Logger logger, boolean isVerbose) {
    if (logger instanceof ch.qos.logback.classic.Logger) {
        try {
            // rewrite console logger to stderr and set log level based on verbosity
            // keep logger implementation details out of AvroCountTool
            ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
            root.setLevel(isVerbose ? ch.qos.logback.classic.Level.DEBUG : ch.qos.logback.classic.Level.ERROR);

            ch.qos.logback.core.Appender<ch.qos.logback.classic.spi.ILoggingEvent> appender = root.getAppender("console");
            ((ch.qos.logback.core.ConsoleAppender) appender).setTarget(ch.qos.logback.core.joran.spi.ConsoleTarget.SystemErr.getName());
            appender.start();

            return true;
        } catch (Exception e) {
            LOGGER.warn("An unexpected error occurred while trying to redirect logger", e);
        }
    }
    return false;
}
 
Example 11
Project: lams   File: SchemaBuilder.java   View source code 6 votes vote down vote up
/**
 * Builds a schema from the given schema sources.
 * 
 * @param lang schema language, must not be null
 * @param schemaSources schema sources, must not be null
 * 
 * @return the constructed schema
 * 
 * @throws SAXException thrown if there is a problem converting the schema sources in to a schema
 */
protected static Schema buildSchema(SchemaLanguage lang, Source[] schemaSources) throws SAXException {
    if(lang == null){
        throw new IllegalArgumentException("Schema language may not be null");
    }
    
    if(schemaSources == null){
        throw new IllegalArgumentException("Schema sources may not be null");
    }
    
    SchemaFactory schemaFactory;

    if (lang == SchemaLanguage.XML) {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    } else {
        schemaFactory = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI);
    }

    schemaFactory.setErrorHandler(new LoggingErrorHandler(LoggerFactory.getLogger(SchemaBuilder.class)));
    return schemaFactory.newSchema(schemaSources);
}
 
Example 12
Project: vt-support   File: MvtReader.java   View source code 6 votes vote down vote up
private static Geometry readGeometry(List<Integer> geomCmds,
                                     VectorTile.Tile.GeomType geomType,
                                     GeometryFactory geomFactory,
                                     Vec2d cursor,
                                     RingClassifier ringClassifier) {
  Geometry result = null;

  switch (geomType) {
    case POINT:
      result = readPoints(geomFactory, geomCmds, cursor);
      break;
    case LINESTRING:
      result = readLines(geomFactory, geomCmds, cursor);
      break;
    case POLYGON:
      result = readPolys(geomFactory, geomCmds, cursor, ringClassifier);
      break;
    default:
      LoggerFactory.getLogger(MvtReader.class)
          .error("readGeometry(): Unhandled geometry type [{}]", geomType);
  }

  return result;
}
 
Example 13
Project: powsybl-core   File: TimeSeries.java   View source code 6 votes vote down vote up
static Map<Integer, List<TimeSeries>> parseCsv(BufferedReader reader, char separator) {
    Objects.requireNonNull(reader);

    Stopwatch stopwatch = Stopwatch.createStarted();

    Map<Integer, List<TimeSeries>> timeSeriesPerVersion = new HashMap<>();
    String separatorStr = Character.toString(separator);
    try {
        CsvParsingContext context = readCsvHeader(reader, separatorStr);
        readCsvValues(reader, separatorStr, context, timeSeriesPerVersion);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    LoggerFactory.getLogger(TimeSeries.class)
            .info("{} time series loaded from CSV in {} ms",
            timeSeriesPerVersion.entrySet().stream().mapToInt(e -> e.getValue().size()).sum(),
            stopwatch.elapsed(TimeUnit.MILLISECONDS));

    return timeSeriesPerVersion;
}
 
Example 14
Project: grain   File: TCPServerTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	GrainLog grainLog = new GrainLog(LoggerFactory.getLogger("minaLog"));
	GrainLog grainLog1 = new GrainLog(LoggerFactory.getLogger("msgLog"));

	// 初始化消息
	MsgManager.init(true, grainLog1);
	// 映射操作码解析类
	TcpManager.addMapping(TestTCode.TESTC, TestC.class);
	TcpManager.addMapping(TestTCode.TESTS, TestS.class);
	// 注册tcp回调函数
	TestTcpServiceS testTcpServiceS = new TestTcpServiceS();
	TcpManager.addTcpListener(testTcpServiceS);
	// 创建TCP服务器
	MinaServer.init("0.0.0.0", 7005, MinaServerHandler.class, true, grainLog);

}
 
Example 15
Project: 484_P7_1-Java   File: ObjectExtractorStreamEngine.java   View source code 6 votes vote down vote up
protected ObjectExtractorStreamEngine(PDPage page) {
    super(page);

    this.log = LoggerFactory.getLogger(ObjectExtractorStreamEngine.class);

    this.rulings = new ArrayList<>();
    this.pageTransform = null;

    // calculate page transform
    PDRectangle cb = this.getPage().getCropBox();
    int rotation = this.getPage().getRotation();

    this.pageTransform = new AffineTransform();

    if (Math.abs(rotation) == 90 || Math.abs(rotation) == 270) {
        this.pageTransform = AffineTransform.getRotateInstance(rotation * (Math.PI / 180.0), 0, 0);
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    } else {
        this.pageTransform.concatenate(AffineTransform.getTranslateInstance(0, cb.getHeight()));
        this.pageTransform.concatenate(AffineTransform.getScaleInstance(1, -1));
    }

    this.pageTransform.translate(-cb.getLowerLeftX(), -cb.getLowerLeftY());
}
 
Example 16
Project: open-kilda   File: PathVerificationFlowTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    logger = LoggerFactory.getLogger(PathVerificationFlowTest.class);
    cntx = new FloodlightContext();
    FloodlightModuleContext fmc = new FloodlightModuleContext();
    fmc.addService(IFloodlightProviderService.class, mockFloodlightProvider);

    swDescription = factory.buildDescStatsReply().build();
    swFeatures = factory.buildFeaturesReply().setNBuffers(1000).build();

    sw = EasyMock.createMock(IOFSwitch.class);
    expect(sw.getId()).andReturn(swDpid).anyTimes();
    expect(sw.getOFFactory()).andReturn(factory).anyTimes();
    expect(sw.getBuffers()).andReturn(swFeatures.getNBuffers()).anyTimes();
    expect(sw.hasAttribute(IOFSwitch.PROP_SUPPORTS_OFPP_TABLE)).andReturn(true).anyTimes();
    expect(sw.getSwitchDescription()).andReturn(new SwitchDescription(swDescription)).anyTimes();
    expect(sw.isActive()).andReturn(true).anyTimes();
    expect(sw.getLatency()).andReturn(U64.of(10L)).anyTimes();
    replay(sw);

    pvs = new PathVerificationService();
}
 
Example 17
Project: spring-io   File: MetricsConfiguration.java   View source code 6 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example 18
Project: mechaniker   File: Main.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  System.setProperty("environment", "dev");

  System.out.println("JVM: " + System.getProperty("java.version"));
  System.out.println("Classpath: " + System.getProperty("java.class.path"));
  System.out.println("System properties: " + System.getProperties());
  System.out.println("System environment: " + System.getenv());

  configureLog4j();
  // must be done after log4j is configured
  final Logger logger = LoggerFactory.getLogger(Main.class);
  logger.info("Mechaniker starting up...");

  final Beans beans = new Beans();

  final Scheduler scheduler = new Scheduler();
  scheduler.schedule();

  SparkWebapp.start();
}
 
Example 19
Project: qualitoast   File: MetricsConfiguration.java   View source code 5 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JCACHE_STATISTICS, new JCacheGaugeSet());
    if (hikariDataSource != null) {
        log.debug("Monitoring the datasource");
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example 20
Project: smartlog   File: Slf4JOutputTest.java   View source code 5 votes vote down vote up
@Test
public void testOutputLoggerForClass() {
    final Slf4JOutput output = Slf4JOutput.create()
            .withLoggerFor(Object.class)
            .build();

    assertThat(output.getLogger())
            .isEqualTo(LoggerFactory.getLogger("java.lang.Object"));
}
 
Example 21
Project: logcapture   File: LogbackInterceptor.java   View source code 5 votes vote down vote up
public static <T> LogCapture<T> captureLogEvents(Supplier<T> codeBlock, String loggerName) {
  StubAppender logAppender = new StubAppender();
  Logger root = (Logger) LoggerFactory.getLogger(loggerName);

  root.addAppender(logAppender);
  try {
    T result = codeBlock.get();
    return new LogCapture<>(logAppender.events(), result);
  } finally {
    root.detachAppender(logAppender);
  }
}
 
Example 22
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: LogbackTest.java   View source code 5 votes vote down vote up
@Before
public void init() throws JoranException {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
 
Example 23
Project: Reer   File: Slf4jLoggingConfigurer.java   View source code 5 votes vote down vote up
public void configure(LogLevel logLevel) {
    if (logLevel == currentLevel) {
        return;
    }

    OutputEventListenerBackedLoggerContext context = (OutputEventListenerBackedLoggerContext) LoggerFactory.getILoggerFactory();

    if (currentLevel == null) {
        context.setOutputEventListener(outputEventListener);
    }

    currentLevel = logLevel;
    context.setLevel(logLevel);
}
 
Example 24
Project: homunculus   File: HomunculusActivity.java   View source code 5 votes vote down vote up
@Override
public void uncaughtException(Thread t, Throwable e) {
    NavigationBuilder nav = getNavigation();
    if (nav != null) {
        nav.redirect(UncaughtException.class).put(UncaughtException.PARAM_THROWABLE, e).start();
    } else {
        LoggerFactory.getLogger(getClass()).error("failed to handle uncaught exception, no navigation present. Uncaught Exception: ", e);
    }
}
 
Example 25
Project: xm-ms-dashboard   File: MetricsConfiguration.java   View source code 5 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    if (hikariDataSource != null) {
        log.debug("Monitoring the datasource");
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example 26
Project: sentry   File: BotCheck.java   View source code 5 votes vote down vote up
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    if (clientRegistry.getClients().isEmpty()) {
        log.warn("No bots to track data for");
    }
    for (Map.Entry<Bot, IDiscordClient> entry : clientRegistry.getClients().entrySet()) {
        IDiscordClient client = entry.getValue();
        if (client.isReady()) {
            String botTag = "bot:" + entry.getKey().getName();
            for (IShard shard : client.getShards()) {
                String shardTag = "shard:" + shard.getInfo()[0];
                long millis = shard.getResponseTime();
                metricRegistry.timer("discord.ws.response[" + botTag + "," + shardTag + "]")
                    .update(millis, TimeUnit.MILLISECONDS);
            }
            for (IGuild guild : client.getGuilds()) {
                String guildTag = "guild:" + guild.getStringID();
                long online = guild.getUsers().stream()
                    .filter(user -> user.getPresence().getStatus() == StatusType.ONLINE)
                    .count();
                long connected = guild.getUsers().stream()
                    .filter(user -> user.getPresence().getStatus() != StatusType.OFFLINE)
                    .count();
                long joined = guild.getUsers().size();
                String onlineMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:online]";
                String connectedMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:connected]";
                String joinedMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:joined]";
                metricRegistry.histogram(onlineMetric).update(online);
                metricRegistry.histogram(connectedMetric).update(connected);
                metricRegistry.histogram(joinedMetric).update(joined);
            }

         LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
         loggerContext.getLogger("org.eclipse.jetty.websocket").setLevel(Level.WARN);
         loggerContext.getLogger(Discord4J.class).setLevel(Level.DEBUG);
        } else {
            log.warn("Bot {} is not ready!", entry.getKey().getName());
        }
    }
}
 
Example 27
Project: reading-and-annotate-rocketmq-3.4.6   File: MQAdminStartup.java   View source code 5 votes vote down vote up
private static void initLogback() throws JoranException {
    String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);
    lc.reset();
    configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
 
Example 28
Project: openNaEF   File: AtmVcCommandBuilder.java   View source code 5 votes vote down vote up
@Override
public BuildResult buildPortCommands() {
    try {
        if (this.pvc != null && !hasChange()) {
            return BuildResult.NO_CHANGES;
        }
        String ifName = getIfName();
        if (pvc == null) {
            LoggerFactory.getLogger(AtmVcCommandBuilder.class).debug("this.ownerName=" + this.ownerName);
            String registerDate = InventoryBuilder.getInventoryDateString(new Date());
            setValue(MPLSNMS_ATTR.REGISTERED_DATE, registerDate);
            InventoryBuilder.changeContext(cmd, this.ownerName);
            SimpleNodeBuilder.buildPortCreationCommands(cmd, ATTR.TYPE_ATM_PVC_IF, String.valueOf(vci));
        } else {
            InventoryBuilder.changeContext(cmd, pvc);
        }
        InventoryBuilder.buildAttributeSetOnCurrentContextCommands(cmd, attributes);
        InventoryBuilder.buildSetAttributeUpdateCommand(cmd, listAttributes);
        this.cmd.addLastEditCommands();
        assignTargetPortToShellContextVariable();

        if (pvc != null) {
            String currentIfName = DtoUtil.getStringOrNull(pvc, MPLSNMS_ATTR.IFNAME);
            if (!currentIfName.equals(ifName)) {
                InventoryBuilder.buildRenameCommands(cmd, ifName);
            }
        }
        return BuildResult.SUCCESS;
    } catch (Exception e) {
        throw ExceptionUtils.throwAsRuntime(e);
    }
}
 
Example 29
Project: iTAP-controller   File: Firewall.java   View source code 5 votes vote down vote up
@Override
public void init(FloodlightModuleContext context) throws FloodlightModuleException {
	floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
	storageSource = context.getServiceImpl(IStorageSourceService.class);
	restApi = context.getServiceImpl(IRestApiService.class);
	rules = new ArrayList<FirewallRule>();
	logger = LoggerFactory.getLogger(Firewall.class);

	// start disabled
	enabled = false;
}
 
Example 30
Project: openNaEF   File: FlashWaveTelnetClient.java   View source code 5 votes vote down vote up
public String changeMode(String changingMode) throws IOException, ConsoleException {
    Logger log = LoggerFactory.getLogger(getClass());
    log.debug("mode-change: " + this.currentMode + " to " + changingMode);
    if (MODE_ENABLE.equals(currentMode) && changingMode.startsWith(MODE_CONFIG)) {
        sendln("config");
        currentMode = changingMode;
        return translate(receiveToPrompt());
    } else if (currentMode.startsWith(MODE_CONFIG) && changingMode.startsWith(MODE_ENABLE)) {
        sendln("exit");
        currentMode = changingMode;
        return translate(receiveToPrompt());
    } else {
        return "";
    }
}
 
Example 31
Project: momo-2   File: State.java   View source code 5 votes vote down vote up
public static void changeBotAvatar(File image) {
	try {
		Bot.getInstance().getBots().get(0).getSelfUser().getManager().setAvatar(Icon.from(image)).queue();
	} catch (Exception e) {
		LoggerFactory.getLogger(State.class).error("Error changing avatar");
	}

}
 
Example 32
Project: jhipster-microservices-example   File: LoggerVMTest.java   View source code 5 votes vote down vote up
@Test
public void getNameTest() throws Exception {
    LoggerVM vm = new LoggerVM();
    assertNull(vm.getName());

    Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    vm = new LoggerVM(logger);
    assertEquals(Logger.ROOT_LOGGER_NAME, vm.getName());
}
 
Example 33
Project: haystack-client-java   File: LoggerDispatcher.java   View source code 5 votes vote down vote up
public LoggerDispatcher(Logger logger) {
    if (logger == null) {
        this.logger = LoggerFactory.getLogger(this.getClass());
    } else {
        this.logger = logger;
    }
}
 
Example 34
Project: jhipster-microservices-example   File: LoggerVMTest.java   View source code 5 votes vote down vote up
@Test
public void setLevelTest() throws Exception {
    LoggerVM vm = new LoggerVM();
    vm.setLevel(null);
    assertNull(vm.getLevel());

    vm = new LoggerVM();
    vm.setLevel("fakeLevel");
    assertEquals("fakeLevel", vm.getLevel());

    Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    vm = new LoggerVM(logger);
    vm.setLevel(Level.OFF.toString());
    assertEquals(Level.OFF.toString(), vm.getLevel());
}
 
Example 35
Project: TorgCRM-Server   File: MetricsConfiguration.java   View source code 5 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Registering JVM gauges");
    metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
    metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
    metricRegistry.register(PROP_METRIC_REG_JCACHE_STATISTICS, new JCacheGaugeSet());
    if (hikariDataSource != null) {
        log.debug("Monitoring the datasource");
        hikariDataSource.setMetricRegistry(metricRegistry);
    }
    if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
        log.debug("Initializing Metrics JMX reporting");
        JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
        jmxReporter.start();
    }
    if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
        log.info("Initializing Metrics Log reporting");
        Marker metricsMarker = MarkerFactory.getMarker("metrics");
        final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
            .outputTo(LoggerFactory.getLogger("metrics"))
            .markWith(metricsMarker)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
        reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
    }
}
 
Example 36
Project: openNaEF   File: LogicalPortEditPage.java   View source code 5 votes vote down vote up
public void processUpdate() {
    if (defaultIfName == null) {
        return;
    }
    try {
        PortDto port = getPort();
        LoggerFactory.getLogger(LogicalPortEditPage.class).debug("port=" + port);
        OspfAreaIdValidator.validate(port, ospfAreaID);

        NodeElementDto owner = port.getOwner();
        if (owner instanceof JackDto) {
            owner = owner.getOwner();
        }
        CommandBuilder builder;
        switch (getIfType()) {
            case ATM_APS:
                builder = processAtmAps((AtmApsIfDto) getPort());
                break;
            case POS_APS:
                builder = processPosAps((PosApsIfDto) getPort());
                break;
            case LAG:
                builder = processLag((EthLagIfDto) getPort());
                break;
            default:
                throw new IllegalArgumentException("not supported-type: " + getIfType().getCaption());
        }
        builder.buildCommand();
        ShellConnector.getInstance().execute(builder);
        if (port != null) {
            port.renew();
        }
    } catch (Exception e) {
        throw ExceptionUtils.throwAsRuntime(e);
    }
}
 
Example 37
Project: jhipster-microservices-example   File: LogsResource.java   View source code 5 votes vote down vote up
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
 
Example 38
Project: API_Endpoint_Identifier   File: SpringAPIIdentifierTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    logger = LoggerFactory.getLogger(SpringAPIIdentifierTest.class);
    File testResourceDirectory = new File("src/test/resources");
    testFilePath = testResourceDirectory.getAbsolutePath() + "//com//aspectsecurity//automation//testing//JavaParser//test//";
    packageLessTestFile = testResourceDirectory.getAbsolutePath() + "//packageLessEndpoint.java";
    // Reset endpoints to empty between tests
    SpringAPIIdentifier.setEndpoints(new ArrayList<>());
}
 
Example 39
Project: sponge   File: StandaloneTestUtils.java   View source code 5 votes vote down vote up
public static void reloadLogback(String configFile) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        configurator.doConfigure(configFile);
    } catch (JoranException je) {
        // StatusPrinter will handle this.
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
 
Example 40
Project: MTC_Labrat   File: LogsResource.java   View source code 5 votes vote down vote up
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    return context.getLoggerList()
        .stream()
        .map(LoggerVM::new)
        .collect(Collectors.toList());
}