@Test public void testUdpSender() throws JoranException, InterruptedException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog-udp.xml")); Logger logger = context.getLogger("test-udp"); logger.info("test message over udp"); context.stop(); Thread.sleep(100); final String serverData = serverStream.toString(); assertTrue("Server received: " + serverData, serverData.contains("test message over udp")); }
/** * Get a {@link LoggingEventCompositeJsonEncoder}. The returned appender * adds a timestamp field and sets the type to "servicelog" if serviceLog is * true. If set to false, we return a request log appender which sets the * timestamp field internally to guarantee that timestamp of the request log * event and the resultant json structure stay in sync. * @param loggerContext to use for setup * @param serviceLog return appender for service logs if true, else return one for request logs * @return corresponding {@link LoggingEventCompositeJsonEncoder} */ static LoggingEventCompositeJsonEncoder getEncoder( final LoggerContext loggerContext, final boolean serviceLog) { final LoggingEventCompositeJsonEncoder jsonEncoder = new LoggingEventCompositeJsonEncoder(); jsonEncoder.setContext(loggerContext); final LoggingEventJsonProviders jsonProviders = getCommonJsonProviders(loggerContext); final GlobalCustomFieldsJsonProvider<ILoggingEvent> customFieldsJsonProvider = new GlobalCustomFieldsJsonProvider<>(); if (serviceLog) { final LoggingEventFormattedTimestampJsonProvider timeStampProvider = new LoggingEventFormattedTimestampJsonProvider(); timeStampProvider.setTimeZone(DateTimeZone.UTC.getID()); timeStampProvider.setFieldName("timestamp"); jsonProviders.addTimestamp(timeStampProvider); customFieldsJsonProvider.setCustomFields("{\"type\":\"servicelog\"}"); } else { customFieldsJsonProvider.setCustomFields("{\"type\":\"requestlog\"}"); } jsonProviders.addGlobalCustomFields(customFieldsJsonProvider); jsonProviders.addStackTrace(new StackTraceJsonProvider()); jsonProviders.addLogLevel(new LogLevelJsonProvider()); jsonEncoder.setProviders(jsonProviders); jsonEncoder.start(); return jsonEncoder; }
static int execute(JetGatlingOptions options) { String workingDir = System.getProperty("user.dir"); GatlingPropertiesBuilder builder = new GatlingPropertiesBuilder(); builder.simulationClass(SIMULATION); builder.dataDirectory(workingDir); builder.bodiesDirectory(workingDir); builder.mute(); if (options.getTimeout() > -1) { System.setProperty("gatling.http.ahc.readTimeout", String.valueOf(options.getTimeout())); } if (options.isDebug() || options.isTrace()) { Level logLevel = options.isTrace() ? Level.TRACE : Level.DEBUG; LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.getLogger("io.gatling.http.ahc").setLevel(logLevel); loggerContext.getLogger("io.gatling.http.response").setLevel(logLevel); loggerContext.getLogger("io.gatling.app").setLevel(logLevel); loggerContext.getLogger("com.github.scw1109.jetgatling").setLevel(logLevel); } return Gatling.fromMap(builder.build()); }
@Before public void setUp() throws Exception { registry = RegistryService.getMetricRegistry(); TagEncodedMetricName rootName = APPENDS_BASE_NAME; TagEncodedMetricName throwablesBaseName = THROWABLES_BASE_NAME; meters = new HashMap<>(); meters.put("total", getMeter(rootName.submetric("total"))); meters.put("trace", getMeter(rootName.withTags("level", "trace"))); meters.put("debug", getMeter(rootName.withTags("level", "debug"))); meters.put("info", getMeter(rootName.withTags("level", "info"))); meters.put("warn", getMeter(rootName.withTags("level", "warn"))); meters.put("error", getMeter(rootName.withTags("level", "error"))); meters.put("throwCount", getMeter(throwablesBaseName.submetric("total"))); meters.put("throw[RuntimeException]", getMeter(throwablesBaseName.withTags("class", RuntimeException.class.getName()) )); LoggerContext context = new LoggerContext(); logger = context.getLogger(LogbackInstrumentationTest.class); origLevel = logger.getLevel(); logger.setLevel(Level.ALL); }
public WebSocketLogAppender(String sessionId) { // deliberately NOT the com.intuit form else will pick up all those // this is supposed to isolate user-session s this.sessionId = sessionId; logger = (Logger) LoggerFactory.getLogger(sessionId); sb = new StringBuilder(); setName("karate-web"); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); setContext(lc); encoder = new PatternLayoutEncoder(); encoder.setPattern("%d{HH:mm:ss.SSS} %-5level - %msg%n"); encoder.setContext(context); encoder.start(); start(); logger.addAppender(this); logger.setLevel(Level.DEBUG); }
@PostConstruct public void initializeLogback() { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); InputStream is = InitLogback.class.getClassLoader().getResourceAsStream("tasfe-logback.xml"); if (is == null) return; JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(is); } catch (JoranException e) { e.printStackTrace(); } }
@Before public void init() { LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory(); ctx.reset(); this.layoutProducer = new LayoutProducer(); ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>(); appender.setLayout(layoutProducer); appender.setContext(ctx); appender.start(); Logger basicLogger = ctx.getLogger(LogFmtTest.class); basicLogger.addAppender(appender); this.logger = LogFmt.from(basicLogger); ctx.start(); }
public void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashSocketAppender logstashAppender = new LogstashSocketAppender(); logstashAppender.setName("LOGSTASH"); logstashAppender.setContext(context); String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," + "\"instance_id\":\"" + instanceId + "\"}"; // Set the Logstash appender config from JHipster properties logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost()); logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort()); logstashAppender.setCustomFields(customFields); // Limit the maximum length of the forwarded stacktrace so that it won't exceed the 8KB UDP limit of logstash ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setMaxLength(7500); throwableConverter.setRootCauseFirst(true); logstashAppender.setThrowableConverter(throwableConverter); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName("ASYNC_LOGSTASH"); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); }
@GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); }
/** * Set up logback logging for service and request logs. We use only ONE appender here to write * normal log lines to stdout for both types. Logging context is set from the keys and values * parameters. They must be corresponding in length and all elements must be non-null and * non-empty. However, the request logger is set up slightly differently. To guarantee that * everything works as expected this method must be called with the fully qualified class name * of the request logger that will be used in jetty. * @param keys to add to all log lines * @param values to add to all log lines * @param requestLoggerName the request logger class name * @param json true for json output, false for plain test */ public static void setupLoggingStdoutOnly( final String[] keys, final String[] values, final String requestLoggerName, final boolean json) { if(!parametersOk(keys, values)) { throw new IllegalArgumentException( "Context keys and/or values are not properly formatted."); } final LoggerContext loggerContext = getLoggerContext(keys, values); final Appender<ILoggingEvent> consoleAppender = json ? createJsonConsoleAppender(SERVICE_CONSOLE_APPENDER, loggerContext, true) : createPatternLayoutConsoleAppender(SERVICE_CONSOLE_APPENDER, loggerContext, true); // specifically cast to logback version so we set it up final Logger rootLogger = (Logger) LoggerFactory.getLogger( org.slf4j.Logger.ROOT_LOGGER_NAME); rootLogger.addAppender(consoleAppender); rootLogger.setLevel(LOG_LEVEL); if (!Strings.isNullOrEmpty(requestLoggerName)) { final Logger requestLogger = (Logger) LoggerFactory.getLogger(requestLoggerName); requestLogger .addAppender(json ? createJsonConsoleAppender( REQUESTLOG_CONSOLE_APPENDER, loggerContext, false) : createPatternLayoutConsoleAppender( REQUESTLOG_CONSOLE_APPENDER, loggerContext, false)); requestLogger.setAdditive(false); requestLogger.setLevel(LOG_LEVEL); } }
private static LoggingEventJsonProviders getCommonJsonProviders( final LoggerContext loggerContext) { final LoggingEventJsonProviders jsonProviders = new LoggingEventJsonProviders(); jsonProviders.addPattern(new LoggingEventPatternJsonProvider()); jsonProviders.addArguments(new ArgumentsJsonProvider()); jsonProviders.addMessage(new MessageJsonProvider()); jsonProviders.addContext(new ContextJsonProvider<ILoggingEvent>()); jsonProviders.addMdc(new MdcJsonProvider()); jsonProviders.setContext(loggerContext); return jsonProviders; }
@RequestMapping(value = "/logs", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerDTO jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); }
/** * figure out the logback's configuration: for example, appenders' file path, buff io, etc... * * @param context * @param webapploader */ private void figureOutLogBackConfig(HookContext context, ClassLoader webapploader) { Logger logback = (Logger) LoggerFactory.getLogger(LogBackHookProxy.class); InterceptContext interceptContext = (InterceptContext) context.get(HookConstants.INTERCEPTCONTEXT); if (interceptContext == null) { logback.warn("No InterceptContext available, can't figure out LogBack configuration."); return; } @SuppressWarnings("unchecked") LinkedList<LogProfileInfo> list = (LinkedList<LogProfileInfo>) interceptContext .get(HookConstants.LOG_PROFILE_LIST); if (null == list) { list = new LinkedList<LogProfileInfo>(); interceptContext.put(HookConstants.LOG_PROFILE_LIST, list); } String appid = (String) (interceptContext.get(InterceptConstants.CONTEXTPATH)); // figureour all loggers LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); List<ch.qos.logback.classic.Logger> loggers = loggerContext.getLoggerList(); for (Logger logger : loggers) { figureoutLogConfiguration(logger, list, appid); } }
@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())); }
@Override public void configure(LoggerContext loggerContext) { addInfo("Setting up default configuration."); DefaultConsoleAppender consoleAppender = new DefaultConsoleAppender(); consoleAppender.setContext(loggerContext); consoleAppender.setName("CONSOLE"); consoleAppender.start(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.INFO); rootLogger.addAppender(consoleAppender); }
private static void setupLogger() { LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory(); PatternLayoutEncoder logEncoder = new PatternLayoutEncoder(); logEncoder.setContext(logCtx); logEncoder.setPattern("%-12date{YYYY-MM-dd HH:mm:ss.SSS} %-5level - %msg%n"); logEncoder.start(); ConsoleAppender logConsoleAppender = new ConsoleAppender(); logConsoleAppender.setContext(logCtx); logConsoleAppender.setName("console"); logConsoleAppender.setEncoder(logEncoder); logConsoleAppender.start(); }
public void addLogstashAppender(LoggerContext context) { log.info("Initializing Logstash logging"); LogstashSocketAppender logstashAppender = new LogstashSocketAppender(); logstashAppender.setName("LOGSTASH"); logstashAppender.setContext(context); String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}"; // Set the Logstash appender config from JHipster properties logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost()); logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort()); logstashAppender.setCustomFields(customFields); // Limit the maximum length of the forwarded stacktrace so that it won't exceed the 8KB UDP limit of logstash ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setMaxLength(7500); throwableConverter.setRootCauseFirst(true); logstashAppender.setThrowableConverter(throwableConverter); logstashAppender.start(); // Wrap the appender in an Async appender for performance AsyncAppender asyncLogstashAppender = new AsyncAppender(); asyncLogstashAppender.setContext(context); asyncLogstashAppender.setName("ASYNC_LOGSTASH"); asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize()); asyncLogstashAppender.addAppender(logstashAppender); asyncLogstashAppender.start(); context.getLogger("ROOT").addAppender(asyncLogstashAppender); }
public static void adjustDetailedTracing(SystemProperties config, long blockNum) { // here we can turn on the detail tracing in the middle of the chain if (blockNum >= config.traceStartBlock() && config.traceStartBlock() != -1) { final URL configFile = ClassLoader.getSystemResource("logback-detailed.xml"); final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); final ContextInitializer ci = new ContextInitializer(loggerContext); loggerContext.reset(); try { ci.configureByResource(configFile); } catch (Exception e) { System.out.println("Error applying new config " + e.getMessage()); } } }
@GetMapping("/logs") public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); }
@Before public void listenForEvents() throws JoranException, IOException { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); InputStream configStream = ResourceUtils.getURL("classpath:logback-test-receiver.xml").openStream(); configurator.setContext(loggerContext); configurator.doConfigure(configStream); configStream.close(); }
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"); }
@GetMapping("/logs") public List<LoggerVm> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVm::new) .collect(Collectors.toList()); }
/** * Loads the Logback configuration from a resource file. * Only here to avoid polluting other examples with logs. Could be replaced by a simple logback.xml file in the resource folder. */ private static void loadLoggerConfiguration() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { configurator.doConfigure(LOGBACK_CONF_FILE); } catch (JoranException je) { Logger.getLogger(StrategyExecutionLogging.class.getName()).log(Level.SEVERE, "Unable to load Logback configuration", je); } }
/** * Allow only selected logger to print DEBUG events to STDOUT and FILE. * Other loggers are allowed to print ERRORS only. */ private static void addSampleLogger(final String loggerName) { if (CUSTOM_FILTER == null) { CUSTOM_FILTER = new CustomFilter(); final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Appender ca = loggerContext.getLogger("ROOT").getAppender("STDOUT"); ca.clearAllFilters(); ca.addFilter(CUSTOM_FILTER); } CUSTOM_FILTER.addVisibleLogger(loggerName); }
private void setupLayout(LoggerContext lc) { PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern(PATTERN_LAYOUT); ple.setContext(lc); ple.start(); setEncoder(ple); }
private FileAppender<ILoggingEvent> createAppender(String logFilePath) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); PatternLayoutEncoder ple = new PatternLayoutEncoder(); ple.setPattern("[%p] %c{1} [%t] %d{[M-dd HH:mm:ss]} - %m%n"); ple.setContext(lc); ple.start(); FileAppender<ILoggingEvent> fileAppender = new FileAppender<>(); fileAppender.setFile(logFilePath); fileAppender.setEncoder(ple); fileAppender.setContext(lc); fileAppender.start(); return fileAppender; }
@Test public void customFieldsShouldBeLogged() throws IOException { final ArgumentCaptor<LoggingEvent> captorLoggingEvent = ArgumentCaptor.forClass( LoggingEvent.class); final LoggerContext loggerContext = SecondBaseLogger.getLoggerContext( new String[] {"environment", "service", "datacenter"}, new String[] {"environment", "service", "datacenter"} ); final Appender<ILoggingEvent> mockAppender = spy( SecondBaseLogger.createJsonConsoleAppender( SecondBaseLogger.SERVICE_CONSOLE_APPENDER, loggerContext, true)); final Logger rootLogger = (Logger) LoggerFactory.getLogger( org.slf4j.Logger.ROOT_LOGGER_NAME); rootLogger.addAppender(mockAppender); final org.slf4j.Logger logger = LoggerFactory.getLogger(SecondBaseLoggerTest.class); logger.info("log message"); verify(mockAppender).doAppend(captorLoggingEvent.capture()); final LoggingEvent loggingEvent = captorLoggingEvent.getValue(); final LoggingEventCompositeJsonEncoder encoder = SecondBaseLogger.getEncoder( loggerContext, true); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); encoder.start(); outputStream.write(encoder.encode(loggingEvent)); final ObjectMapper mapper = new ObjectMapper(); final JsonNode node = mapper.readTree(outputStream.toByteArray()); assertThat(node.get("message").asText(), is("log message")); assertThat(node.get("environment").asText(), is("environment")); assertThat(node.get("datacenter").asText(), is("datacenter")); assertThat(node.get("service").asText(), is("service")); assertThat(node.get("level").asText(), is("INFO")); assertThat(node.has("timestamp"), is(true)); assertThat(node.get("type").asText(), is("servicelog")); encoder.stop(); outputStream.close(); }
public MongoSender(MongoCollection<Document> collection){ this.collection=collection; lis=new LinkedList<Document>(); semaphore = new Semaphore(1); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); logger= loggerContext.getLogger("framework.MongoSender"); }