本文整理汇总了Java中org.apache.log4j.Logger.addAppender方法的典型用法代码示例。如果您正苦于以下问题:Java Logger.addAppender方法的具体用法?Java Logger.addAppender怎么用?Java Logger.addAppender使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.log4j.Logger
的用法示例。
在下文中一共展示了Logger.addAppender方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testNeedsApplyWithAppenderExpectTrue
import org.apache.log4j.Logger; //导入方法依赖的package包/类
@Test
public void testNeedsApplyWithAppenderExpectTrue() {
ActiveDbAppender appender = new ActiveDbAppender();
appender.setHost( "test" );
appender.setDatabase( "test" );
appender.setUser( "test" );
appender.setPassword( "test" );
Logger log = Logger.getRootLogger();
log.addAppender( appender );
//construct the configurator - an appender is present
RemoteLoggingConfigurator remoteLoggingConfig = new RemoteLoggingConfigurator( "127.0.0.1" );
//remove the appender, so the configurator will need to apply it
log.removeAppender( appender );
assertTrue( remoteLoggingConfig.needsApplying() );
}
示例2: run
import org.apache.log4j.Logger; //导入方法依赖的package包/类
void run() {
Logger rootLogger = Logger.getRootLogger();
List<LoggingEvent> events = new ArrayList<>();
Appender appender = new MockUp<Appender>() {
@Mock
public void doAppend(LoggingEvent event) {
events.add(event);
}
}.getMockInstance();
rootLogger.addAppender(appender);
doRun(events);
rootLogger.removeAppender(appender);
}
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:17,代码来源:TestServiceRegistryClientImpl.java
示例3: enableAsyncAuditLog
import org.apache.log4j.Logger; //导入方法依赖的package包/类
private static void enableAsyncAuditLog() {
if (!(auditLog instanceof Log4JLogger)) {
LOG.warn("Log4j is required to enable async auditlog");
return;
}
Logger logger = ((Log4JLogger)auditLog).getLogger();
@SuppressWarnings("unchecked")
List<Appender> appenders = Collections.list(logger.getAllAppenders());
// failsafe against trying to async it more than once
if (!appenders.isEmpty() && !(appenders.get(0) instanceof AsyncAppender)) {
AsyncAppender asyncAppender = new AsyncAppender();
// change logger to have an async appender containing all the
// previously configured appenders
for (Appender appender : appenders) {
logger.removeAppender(appender);
asyncAppender.addAppender(appender);
}
logger.addAppender(asyncAppender);
}
}
示例4: setupLogging
import org.apache.log4j.Logger; //导入方法依赖的package包/类
private void setupLogging() {
LogManager.getLogManager().reset();
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
final Logger rootLogger = Logger.getRootLogger();
final PatternLayout layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");
final Level level = endPointHealthConfiguration.logLevel();
final ConsoleAppender consoleAppender = new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR);
consoleAppender.setThreshold(level);
consoleAppender.activateOptions();
final FileAppender fileAppender = new FileAppender();
fileAppender.setFile(endPointHealthConfiguration.logFile().getAbsolutePath());
fileAppender.setLayout(layout);
fileAppender.setThreshold(level);
fileAppender.setAppend(true);
fileAppender.setErrorHandler(new FallbackAppenderErrorHandler(rootLogger, fileAppender, consoleAppender));
rootLogger.addAppender(fileAppender);
fileAppender.activateOptions();
}
示例5: Property
import org.apache.log4j.Logger; //导入方法依赖的package包/类
public Property() {
PropertyConfigurator.configure(this.getClass().getResourceAsStream("log4j_custom.properties"));
Logger l1 = Logger.getLogger("P2P");
Appender a = new CustomAppender();
l1.addAppender(a);
l1 = Logger.getLogger("BlockchainManager");
l1.addAppender(a);
l1 = Logger.getLogger("DbManager");
l1.addAppender(a);
l1 = Logger.getLogger("CrypDist");
l1.addAppender(a);
try {
Config.PRIVATE_KEY = new String((IOUtils.toByteArray(getClass().getResourceAsStream("private.pem"))) );
} catch (Exception e) {
}
}
示例6: getLogger
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/**
*
* @param prop
* @param clazz
* @return
*/
public static Logger getLogger(Properties prop, Class<?> clazz) {
Logger LOG = Logger.getLogger(clazz);
String appName = PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.APP_NAME);
String fileDir = PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.LOG_DIR);
String patternLayout = PropertiesUtils.getRequiredProperty(prop,
PropertiesUtils.LOG_PATTERN);
String level = PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.LOG_LEVEL);
LOG.setLevel(Level.toLevel(level, Level.INFO));
DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
rollingAppender.setFile(fileDir + "/" + appName + ".log");
rollingAppender.setLayout(new PatternLayout(patternLayout));
rollingAppender.setDatePattern("'.'yyyy-MM-dd");
rollingAppender.activateOptions();
LOG.addAppender(rollingAppender);
LOG.setAdditivity(false);
return LOG;
}
示例7: testRevertPositive
import org.apache.log4j.Logger; //导入方法依赖的package包/类
@Test
public void testRevertPositive() {
ActiveDbAppender appender = new ActiveDbAppender();
appender.setHost( "test" );
appender.setDatabase( "test" );
appender.setUser( "test" );
appender.setPassword( "test" );
Logger log = Logger.getLogger( loggerName );
log.addAppender( appender );
//construct the configurator - an appender is present
RemoteLoggingConfigurator remoteLoggingConfig = new RemoteLoggingConfigurator( "127.0.0.1" );
//remove the appender, so the configurator will need to apply it
log.removeAppender( appender );
//apply the appender
remoteLoggingConfig.apply();
remoteLoggingConfig.revert();
assertFalse( log.getAllAppenders().hasMoreElements() );
}
示例8: changeFileAppenderIfNew
import org.apache.log4j.Logger; //导入方法依赖的package包/类
private static void changeFileAppenderIfNew(Logger logger,
String fileAppenderName, RollingFileAppender newFileAppender) {
Appender existingFileAppender = logger.getAppender(fileAppenderName);
if (existingFileAppender == null) {
logger.removeAppender(consoleAppender);
logger.addAppender(newFileAppender);
} else if (existingFileAppender != newFileAppender) {
logger.removeAppender(existingFileAppender);
logger.addAppender(newFileAppender);
}
return;
}
示例9: testChooseTargetWithMoreThanAvailableNodes
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/**
* In this testcase, it tries to choose more targets than available nodes and
* check the result.
* @throws Exception
*/
@Test
public void testChooseTargetWithMoreThanAvailableNodes() throws Exception {
// make data node 0 & 1 to be not qualified to choose: not enough disk space
for(int i=0; i<2; i++) {
updateHeartbeatWithUsage(dataNodes[i],
2*HdfsConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
(HdfsConstants.MIN_BLOCKS_FOR_WRITE-1)*BLOCK_SIZE, 0L, 0L, 0L, 0, 0);
}
final LogVerificationAppender appender = new LogVerificationAppender();
final Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
// try to choose NUM_OF_DATANODES which is more than actually available
// nodes.
DatanodeStorageInfo[] targets = chooseTarget(NUM_OF_DATANODES);
assertEquals(targets.length, NUM_OF_DATANODES - 2);
final List<LoggingEvent> log = appender.getLog();
assertNotNull(log);
assertFalse(log.size() == 0);
final LoggingEvent lastLogEntry = log.get(log.size() - 1);
assertTrue(Level.WARN.isGreaterOrEqual(lastLogEntry.getLevel()));
// Suppose to place replicas on each node but two data nodes are not
// available for placing replica, so here we expect a short of 2
assertTrue(((String) lastLogEntry.getMessage()).contains("in need of 2"));
resetHeartbeatForStorages();
}
示例10: setupAuditLogs
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/** Sets up log4j logger for auditlogs */
private void setupAuditLogs() throws IOException {
File file = new File(auditLogFile);
if (file.exists()) {
file.delete();
}
Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
logger.setLevel(Level.INFO);
PatternLayout layout = new PatternLayout("%m%n");
RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile);
logger.addAppender(appender);
}
示例11: post
import org.apache.log4j.Logger; //导入方法依赖的package包/类
@Override
protected void post() {
super.post();
Logger root = Logger.getRootLogger();
final SystemLogAppender appender = new SystemLogAppender();
appender.setLayout(new PatternLayout("[%t] %-5p %c - %m%n"));
root.addAppender(appender);
}
示例12: testSeekForRwServer
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/**
* Ensures that client seeks for r/w servers while it's connected to r/o
* server.
*/
@SuppressWarnings("deprecation")
@Test(timeout = 90000)
public void testSeekForRwServer() throws Exception {
// setup the logger to capture all logs
Layout layout = Logger.getRootLogger().getAppender("CONSOLE")
.getLayout();
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = new WriterAppender(layout, os);
appender.setImmediateFlush(true);
appender.setThreshold(Level.INFO);
Logger zlogger = Logger.getLogger("org.apache.zookeeper");
zlogger.addAppender(appender);
try {
qu.shutdown(2);
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(qu.getConnString(),
CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// if we don't suspend a peer it will rejoin a quorum
qu.getPeer(1).peer.suspend();
// start two servers to form a quorum; client should detect this and
// connect to one of them
watcher.reset();
qu.start(2);
qu.start(3);
ClientBase.waitForServerUp(qu.getConnString(), 2000);
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
// resume poor fellow
qu.getPeer(1).peer.resume();
} finally {
zlogger.removeAppender(appender);
}
os.close();
LineNumberReader r = new LineNumberReader(new StringReader(os
.toString()));
String line;
Pattern p = Pattern.compile(".*Majority server found.*");
boolean found = false;
while ((line = r.readLine()) != null) {
if (p.matcher(line).matches()) {
found = true;
break;
}
}
Assert.assertTrue(
"Majority server wasn't found while connected to r/o server",
found);
}
示例13: testJobMonitorAndPrint
import org.apache.log4j.Logger; //导入方法依赖的package包/类
@Test
public void testJobMonitorAndPrint() throws Exception {
JobStatus jobStatus_1 = new JobStatus(new JobID("job_000", 1), 1f, 0.1f,
0.1f, 0f, State.RUNNING, JobPriority.HIGH, "tmp-user", "tmp-jobname",
"tmp-queue", "tmp-jobfile", "tmp-url", true);
JobStatus jobStatus_2 = new JobStatus(new JobID("job_000", 1), 1f, 1f,
1f, 1f, State.SUCCEEDED, JobPriority.HIGH, "tmp-user", "tmp-jobname",
"tmp-queue", "tmp-jobfile", "tmp-url", true);
doAnswer(
new Answer<TaskCompletionEvent[]>() {
@Override
public TaskCompletionEvent[] answer(InvocationOnMock invocation)
throws Throwable {
return new TaskCompletionEvent[0];
}
}
).when(job).getTaskCompletionEvents(anyInt(), anyInt());
doReturn(new TaskReport[5]).when(job).getTaskReports(isA(TaskType.class));
when(clientProtocol.getJobStatus(any(JobID.class))).thenReturn(jobStatus_1, jobStatus_2);
// setup the logger to capture all logs
Layout layout =
Logger.getRootLogger().getAppender("stdout").getLayout();
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = new WriterAppender(layout, os);
appender.setThreshold(Level.ALL);
Logger qlogger = Logger.getLogger(Job.class);
qlogger.addAppender(appender);
job.monitorAndPrintJob();
qlogger.removeAppender(appender);
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean foundHundred = false;
boolean foundComplete = false;
boolean foundUber = false;
String uberModeMatch = "uber mode : true";
String progressMatch = "map 100% reduce 100%";
String completionMatch = "completed successfully";
while ((line = r.readLine()) != null) {
if (line.contains(uberModeMatch)) {
foundUber = true;
}
foundHundred = line.contains(progressMatch);
if (foundHundred)
break;
}
line = r.readLine();
foundComplete = line.contains(completionMatch);
assertTrue(foundUber);
assertTrue(foundHundred);
assertTrue(foundComplete);
System.out.println("The output of job.toString() is : \n" + job.toString());
assertTrue(job.toString().contains("Number of maps: 5\n"));
assertTrue(job.toString().contains("Number of reduces: 5\n"));
}
示例14: testHTTPSInputTransportInvalidCertPassword
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/**
* Creating test for publishing events with https protocol with invalid cert pass.
*
* @throws Exception Interrupted exception
*/
@Test
public void testHTTPSInputTransportInvalidCertPassword() throws Exception {
final TestAppender appender = new TestAppender();
final Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
logger.info(" Creating test for publishing events with https protocol with invalid cert pass.");
HttpTestUtil.setCarbonHome();
Map<String, String> masterConfigs = new HashMap<>();
masterConfigs.put("source.http.keyStoreLocation", "${carbon.home}/resources/security/wso2carbon.jks");
masterConfigs.put("source.http.https.keystore,password", "wso2carbon");
masterConfigs.put("source.http.certPassword", "wso2carbon123");
List<String> receivedEventNameList = new ArrayList<>(2);
SiddhiManager siddhiManager = new SiddhiManager();
InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(masterConfigs , null);
inMemoryConfigManager.generateConfigReader("source", "http");
siddhiManager.setConfigManager(inMemoryConfigManager);
siddhiManager.setExtension("xml-input-mapper", XmlSourceMapper.class);
String inStreamDefinition = "" + "@source(type='http', @map(type='xml'), receiver.url='https://localhost:" +
"8005/endpoints/RecPro' )"
+ "define stream inputStream (name string, age int, country string);";
String query = ("@info(name = 'query') "
+ "from inputStream "
+ "select * "
+ "insert into outputStream;"
);
SiddhiAppRuntime siddhiAppRuntime = siddhiManager
.createSiddhiAppRuntime(inStreamDefinition + query);
siddhiAppRuntime.addCallback("query", new QueryCallback() {
@Override
public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
EventPrinter.print(timeStamp, inEvents, removeEvents);
for (Event event : inEvents) {
eventCount.incrementAndGet();
receivedEventNameList.add(event.getData(0).toString());
}
}
});
siddhiAppRuntime.start();
// publishing events
List<String> expected = new ArrayList<>(2);
String event1 = "<events>"
+ "<event>"
+ "<name>John</name>"
+ "<age>100</age>"
+ "<country>AUS</country>"
+ "</event>"
+ "</events>";
String event2 = "<events>"
+ "<event>"
+ "<name>Mike</name>"
+ "<age>20</age>"
+ "<country>USA</country>"
+ "</event>"
+ "</events>";
HttpTestUtil.httpsPublishEvent(event1);
HttpTestUtil.httpsPublishEvent(event2);
final List<LoggingEvent> log = appender.getLog();
List<Object> logMessages = new ArrayList<>();
for (LoggingEvent logEvent : log) {
logMessages.add(logEvent.getLevel());
}
Assert.assertEquals(logMessages.contains(Level.ERROR), true);
Assert.assertEquals(Collections.frequency(logMessages, Level.ERROR), 2);
SiddhiTestHelper.waitForEvents(waitTime, 0, eventCount, timeout);
Assert.assertEquals(receivedEventNameList.toString(), expected.toString());
siddhiAppRuntime.shutdown();
}
示例15: testBadPeerAddressInQuorum
import org.apache.log4j.Logger; //导入方法依赖的package包/类
/**
* Verify handling of bad quorum address
*/
@Test
public void testBadPeerAddressInQuorum() throws Exception {
ClientBase.setupTestEnv();
// setup the logger to capture all logs
Layout layout =
Logger.getRootLogger().getAppender("CONSOLE").getLayout();
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = new WriterAppender(layout, os);
appender.setThreshold(Level.WARN);
Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
qlogger.addAppender(appender);
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique()
+ "\nserver.2=fee.fii.foo.fum:" + PortAssignment.unique()
+ ":" + PortAssignment.unique();
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
boolean isup =
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
30000);
Assert.assertFalse("Server never came up", isup);
q1.shutdown();
Assert.assertTrue("waiting for server 1 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
Pattern p =
Pattern.compile(".*Cannot open channel to .* at election address .*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
Assert.assertTrue("complains about host", found);
}