下面列出了javax.ws.rs.NotSupportedException#org.apache.logging.log4j.LogManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public FocusUpgradeType(int id, ResourceLocation icon, String name, String text, AspectList aspects) {
this.id = (short) id;
this.icon = icon;
this.name = name;
this.text = text;
this.aspects = aspects;
if (id<types.length && types[id]!=null) {
LogManager.getLogger("THAUMCRAFT").fatal("Focus Upgrade id "+id+" already occupied. Ignoring.");
return;
}
// allocate space
if (id>=types.length) {
FocusUpgradeType[] temp = new FocusUpgradeType[id+1];
System.arraycopy(types, 0, temp, 0, types.length);
types = temp;
}
types[id] = this;
}
@Override
public void startUp(ServletContext servletContext) {
try {
initializeJPA();
} catch (PersistenceException e) {
//fix for MCR-1236
if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)) {
LogManager.getLogger()
.error(() -> "Could not initialize JPA. Database access is disabled in this session.", e);
MCRConfiguration2.set("MCR.Persistence.Database.Enable", String.valueOf(false));
}
MCREntityManagerProvider.init(e);
return;
}
Metamodel metamodel = MCREntityManagerProvider.getEntityManagerFactory().getMetamodel();
checkHibernateMappingConfig(metamodel);
LogManager.getLogger()
.info("Mapping these entities: {}", metamodel.getEntities()
.stream()
.map(EntityType::getJavaType)
.map(Class::getName)
.collect(Collectors.toList()));
MCRShutdownHandler.getInstance().addCloseable(new MCRJPAShutdownProcessor());
}
@Test
public void testGetLoggerWithTaglibLogger() throws Exception {
this.setUp(null);
final AbstractLogger wrapped = (AbstractLogger)LogManager.getLogger("testGetLoggerWithTaglibLogger");
final Log4jTaglibLogger logger = new Log4jTaglibLogger(wrapped, wrapped.getName(), wrapped.getMessageFactory());
this.tag.setLogger(logger);
Log4jTaglibLogger returned = this.tag.getLogger();
assertNotNull("The first returned logger should not be null.", returned);
assertSame("The first returned logger should be the same as the set.", logger, returned);
assertEquals("The name is not correct.", "testGetLoggerWithTaglibLogger", returned.getName());
returned = this.tag.getLogger();
assertNotNull("The second returned logger should not be null.", returned);
assertSame("The second returned logger should be the same as the set.", logger, returned);
}
/**
* @param name
* the name of the java class or java package to set the log
* level for
* @param logLevelToSet
* the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and
* FATAL, providing any other value will lead to DEBUG as new log
* level
*/
@MCRCommand(syntax = "change log level of {0} to {1}",
help = "{0} the package or class name for which to change the log level, {1} the log level to set.",
order = 10)
public static synchronized void changeLogLevel(String name, String logLevelToSet) {
LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet);
Level newLevel = Level.getLevel(logLevelToSet);
if (newLevel == null) {
LOGGER.error("Unknown log level \"{}\"", logLevelToSet);
return;
}
Logger log = "ROOT".equals(name) ? LogManager.getRootLogger() : LogManager.getLogger(name);
if (log == null) {
LOGGER.error("Could not get logger for \"{}\"", name);
return;
}
LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel);
Configurator.setLevel(log.getName(), newLevel);
}
/**
* @since 3.0
*/
@PluginFactory
public static LoggerConfig createLogger(
@PluginAttribute final String additivity,
@PluginAttribute final Level level,
@PluginAttribute final String includeLocation,
@PluginElement final AppenderRef[] refs,
@PluginElement final Property[] properties,
@PluginConfiguration final Configuration config,
@PluginElement final Filter filter) {
final List<AppenderRef> appenderRefs = Arrays.asList(refs);
final Level actualLevel = level == null ? Level.ERROR : level;
final boolean additive = Booleans.parseBoolean(additivity, true);
return new AsyncLoggerConfig(LogManager.ROOT_LOGGER_NAME, appenderRefs, filter, actualLevel, additive,
properties, config, AsyncLoggerConfig.includeLocation(includeLocation));
}
@Test
public void messageFactoryTest() {
System.setProperty("log4j2.enable.threadlocals", "true");
System.setProperty("log4j2.enable.direct.encoders", "true");
System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
createLoggerProgrammatically(
() -> createElasticsearchAppenderBuilder(true, false, secure),
configuration -> configuration.getAsyncLoggerConfigDelegate()
);
ObjectMapper objectMapper = configuredMapper();
Logger logger = LogManager.getLogger(DEFAULT_LOGGER_NAME,
new SerializedMessageFactory(objectMapper));
logger.info(new LogObject("Hello, World!"));
}
@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 void aroundWriteTo(WriterInterceptorContext writerInterceptorContext)
throws IOException, WebApplicationException {
writerInterceptorContext
.setOutputStream(new ClientAbortExceptionOutputStream(writerInterceptorContext.getOutputStream()));
try {
writerInterceptorContext.proceed();
} catch (Exception e) {
for (Throwable cause = e; cause != null; cause = cause.getCause()) {
if (cause instanceof ClientAbortException) {
LogManager.getLogger().info("Client closed response too early.");
return;
}
}
throw e;
}
}
@After
@Override
public void tearDown() throws Exception {
try {
startNewTransaction();
MCRCategoryImpl rootNode = getRootCategoryFromSession();
MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1);
if (rootNode != null) {
try {
checkLeftRightLevelValue(rootNode, 0, 0);
checkLeftRightLevelValue(rootNode2, 0, 0);
} catch (AssertionError e) {
LogManager.getLogger().error("Error while checking left, right an level values in database.");
new XMLOutputter(Format.getPrettyFormat())
.output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out);
printCategoryTable();
throw e;
}
}
} finally {
super.tearDown();
}
}
/**
* This is primarily for tests to insure that log messages don't bleed from one test case to another, see:
* SOLR-13268.
*
* However, if there are situations where we want to insure that all log messages for all loggers are flushed,
* this method can be called by anyone. It should _not_ affect Solr in any way except, perhaps, a slight delay
* while messages are being flushed.
*
* 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 flushAllLoggers() {
if (!isLog4jActive()) {
logNotSupported("Not running log4j2, could not call shutdown for async logging.");
return;
}
final LoggerContext logCtx = ((LoggerContext) LogManager.getContext(false));
for (final org.apache.logging.log4j.core.Logger logger : logCtx.getLoggers()) {
for (final Appender appender : logger.getAppenders().values()) {
if (appender instanceof AbstractOutputStreamAppender) {
((AbstractOutputStreamAppender) appender).getManager().flush();
}
}
}
}
public void test(final String[] args) {
System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
// System.out.println(System.getProperty("java.class.path"));
final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
: args[0];
try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
logger.fatal("Fatal message.");
logger.error("Error message.");
logger.warn("Warning message.");
logger.info("Information message.");
logger.debug("Debug message.");
logger.trace("Trace message.");
logger.error("Error message.", new IOException("test"));
}
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
if (produces == null || Stream.of(produces.value()).noneMatch(MediaType.SERVER_SENT_EVENTS::equals)) {
return;
}
LogManager.getLogger().info("Has Session? {}", MCRSessionMgr.hasCurrentSession());
if (MCRSessionMgr.hasCurrentSession()) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
if (currentSession.isTransactionActive()) {
currentSession.commitTransaction();
}
MCRSessionMgr.releaseCurrentSession();
currentSession.close();
}
}
/** {@inheritDoc} */
@Override public void setNodeId(UUID nodeId) {
A.notNull(nodeId, "nodeId");
this.nodeId = nodeId;
// Set nodeId as system variable to be used at configuration.
System.setProperty(NODE_ID, U.id8(nodeId));
if (inited) {
final LoggerContext ctx = impl.getContext();
synchronized (mux) {
inited = false;
}
addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
ctx.reconfigure();
return (Logger)LogManager.getRootLogger();
}
});
}
}
/**
* Allocates a discovery thread.
*/
protected DiscoveryThread() {
this.logger = LogManager.getLogger(DiscoveryThread.class);
this.bootstrap = new Bootstrap();
this.group = new NioEventLoopGroup();
this.handler = new DiscoveryHandler();
bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
try {
this.channel = bootstrap.bind(0).sync().channel();
} catch (InterruptedException e) {
this.interrupt(); // Cause thread to immediately break out of loop
Discovery.setDiscoveryMode(DiscoveryMode.DISABLED);
logger.error("Failed to bind channel necessary for broadcasting pings, disabled discovery system");
}
this.setName(logger.getName());
}
@Test
public void testLogJsonArgument() throws InterruptedException {
final ListAppender appender = (ListAppender) init.getAppender("List");
appender.countDownLatch = new CountDownLatch(4);
appender.clear();
final Logger logger = (Logger) LogManager.getRootLogger();
final String json = "{\"id\":10,\"name\":\"Alice\"}";
logger.error("log:{}", json);
// wait until background thread finished processing
final int msgCount = 1;
if (appender.getMessages().size() < msgCount) {
appender.countDownLatch.await(5, TimeUnit.SECONDS);
}
assertEquals("Background thread did not finish processing: msg count", msgCount, appender.getMessages().size());
// don't stop appender until background thread is done
appender.stop();
final List<String> list = appender.getMessages();
final String eventStr = list.get(0).toString();
Assert.assertTrue(eventStr, eventStr.contains(json));
}
@Test
public void doNotProcessPlaceholdersTwice() throws Exception {
final File file = new File("target", "AsyncAppenderConfigTest-LOG4J2-2032.log");
assertTrue("Deleted old file before test", !file.exists() || file.delete());
final Logger log = LogManager.getLogger("com.foo.Bar");
log.info("Text containing curly braces: {}", "Curly{}");
CoreLoggerContexts.stopLoggerContext(file); // stop async thread
final BufferedReader reader = new BufferedReader(new FileReader(file));
try {
final String line1 = reader.readLine();
System.out.println(line1);
assertTrue("line1 correct", line1.contains(" Text containing curly braces: Curly{} "));
} finally {
reader.close();
file.delete();
}
}
@Test
public void messageFactoryTest() {
System.setProperty("log4j2.enable.threadlocals", "true");
System.setProperty("log4j2.enable.direct.encoders", "true");
System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
createLoggerProgrammatically(
() -> createElasticsearchAppenderBuilder(true, false, secure),
config -> config.getAsyncLoggerConfigDelegate());
ObjectMapper objectMapper = configuredMapper();
Logger logger = LogManager.getLogger(DEFAULT_LOGGER_NAME,
new SerializedMessageFactory(objectMapper));
logger.info(new LogObject("Hello, World!"));
}
private Config() {
this.c = ConfigFactory.load();
final String logLevel = c.getString("log-level");
Level level = Level.toLevel(logLevel);
final String lowerLevel = logLevel.toLowerCase();
if (lowerLevel.equals("debug") || lowerLevel.equals("telemetry")) {
this.debug = true;
}
// force change
Object ctx = LogManager.getContext(false);
if (ctx instanceof LoggerContext) {
LoggerContext context = (LoggerContext) ctx;
Configuration configuration = context.getConfiguration();
LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
loggerConfig.setLevel(level);
context.updateLoggers();
}
}
@BeforeClass
public static void beforeClass() throws IOException, InterruptedException {
server1 = new TestSocketServer(0);
server2 = new TestSocketServer(0);
server1.start();
server2.start();
Thread.sleep(100);
ports = new int[] { server1.getPort(), server2.getPort()};
resolver.ports = ports;
TcpSocketManager.setHostResolver(resolver);
loggerContext = Configurator.initialize("SocketReconnectTest", SocketReconnectTest.class.getClassLoader(),
CONFIG);
logger = LogManager.getLogger(SocketReconnectTest.class);
server1.shutdown();
server1.join();
server2.shutdown();
server2.join();
server1 = null;
server2 = null;
Thread.sleep(100);
list.clear();
}
@Test
public void testRefreshMinimalCodeStopStart() {
Logger log = LogManager.getLogger(this.getClass());
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.stop();
ctx.start();
log.error("Info message");
}
@Test
public void testFromClassPathWithClassPathPrefix() throws Exception {
ctx = Configurator.initialize("Test1", "classpath:log4j2-config.xml");
LogManager.getLogger("org.apache.test.TestConfigurator");
Configuration config = ctx.getConfiguration();
assertNotNull("No configuration", config);
assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName());
final Map<String, Appender> map = config.getAppenders();
assertNotNull("Appenders map should not be null.", map);
assertThat(map, hasSize(greaterThan(0)));
assertThat("Wrong configuration", map, hasKey("List"));
Configurator.shutdown(ctx);
config = ctx.getConfiguration();
assertEquals("Incorrect Configuration.", NullConfiguration.NULL_NAME, config.getName());
}
@BeforeClass public static void beforeClass() {
// Our choice.
System.setProperty("log4j.configuration", "set");
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File("src/test/resources/log4j2-test.xml");
// this will force a reconfiguration
context.setConfigLocation(file.toURI());
}
public void test() {
System.out.println("hello world");
System.setOut(new PrintStream(System.out) {
@Override
public void println(String x) {
StackTraceElement[] ste=Thread.currentThread().getStackTrace();
String line=ste[2].toString();
LogManager.getFormatterLogger("console to log").info(line+" - "+x);
LogManager.getFormatterLogger(Thread.currentThread()).info(line + " - " + x);
}
});
System.out.println("hello world");
}
@BeforeClass
public static void setupClass() throws Exception {
catalogReader = new StringCatalogReader();
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
for (Map.Entry<String, Appender> entry : config.getAppenders().entrySet()) {
if (entry.getKey().equals("List")) {
app = (ListAppender) entry.getValue();
break;
}
}
assertNotNull("No Appender", app);
}
private void initializeJndi(final String location) {
final URI configLocation = getConfigURI(location);
if (this.name == null) {
throw new IllegalStateException("A log4jContextName context parameter is required");
}
LoggerContext context;
final LoggerContextFactory factory = LogManager.getFactory();
if (factory instanceof Log4jContextFactory) {
final ContextSelector selector = ((Log4jContextFactory) factory).getSelector();
if (selector instanceof NamedContextSelector) {
this.namedContextSelector = (NamedContextSelector) selector;
context = this.namedContextSelector.locateContext(this.name, this.servletContext, configLocation);
ContextAnchor.THREAD_CONTEXT.set(context);
if (context.isInitialized()) {
context.start();
}
ContextAnchor.THREAD_CONTEXT.remove();
} else {
LOGGER.warn("Potential problem: Selector is not an instance of NamedContextSelector.");
return;
}
} else {
LOGGER.warn("Potential problem: LoggerContextFactory is not an instance of Log4jContextFactory.");
return;
}
this.loggerContext = context;
LOGGER.debug("Created logger context for [{}] using [{}].", this.name, context.getClass().getClassLoader());
}
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);
}
/**
* .
*/
@Test
public void testCircularCauseExceptions() {
final Exception e1 = new Exception();
final Exception e2 = new Exception(e1);
e1.initCause(e2);
LogManager.getLogger().error("Error", e1);
}
@Override
public boolean evaluate(MCRWorkflowData workflowData) {
MCRCategLinkReference reference = workflowData.getCategoryReference();
if (reference == null) {
LogManager.getLogger(getClass())
.error("Cannot evaluate '{}', if MCRWorkflowData does not contain an object reference",
toString());
return false;
}
return LINK_SERVICE.isInCategory(reference, mcrCategoryID) ^ not;
}
@Test(timeout = 5000)
public void testNormalQueueFullKeepsMessagesInOrder() throws InterruptedException {
final Logger logger = LogManager.getLogger(this.getClass());
blockingAppender.countDownLatch = new CountDownLatch(1);
unlocker = new Unlocker(new CountDownLatch(129));
unlocker.start();
asyncAppenderTest(logger, unlocker, blockingAppender);
}
public void setLevel(Level level) {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
loggerConfig.setLevel(toLog4jLevel(level));
ctx.updateLoggers();
}