下面列出了怎么用org.apache.log4j.Logger的API类实例代码及写法,或者点击链接到github查看源代码。
private static boolean unrollLoops(Logger logger, Program prog, Function f,
Block block) {
boolean unrolled = false;
ListIterator<Continuation> it = block.continuationIterator();
while (it.hasNext()) {
Continuation c = it.next();
// Doing from bottom up gives us better estimate of inner loop size after expansion
for (Block b: c.getBlocks()) {
boolean res = unrollLoops(logger, prog, f, b);
unrolled = unrolled || res;
}
Pair<Boolean, List<Continuation>> cRes;
cRes = c.tryUnroll(logger, f.id(), block);
if (cRes.val1) {
unrolled = true;
for (Continuation newC: cRes.val2) {
it.add(newC);
}
}
}
return unrolled;
}
/**
* Saves an entry to file
* @param entry
* @param dbName usually scrapig
* @return true if success
*/
public static boolean saveEntry(DBEntry entry, String dbName){
if(entry == null || !entry.isValid())
return false;
Logger log = Logger.getLogger(DAO.class);
MongoDatabase db = MongoDB.INSTANCE.getDatabase(dbName);
String collectionName = getCollectionName(entry);
MongoCollection collection = db.getCollection(collectionName,BasicDBObject.class);
try {
collection.insertOne(entry);
return true;
}
catch (MongoWriteException ex){
if (ex.getCode() != 11000) // Ignore errors about duplicates
log.error(ex.getError().getMessage());
return false;
}
}
private static void recurseOnContinuation(Logger logger, InitState state,
Continuation cont, boolean validate) {
// Only recurse if we're validating, or if we need info from inner blocks
boolean unifyBranches = InitState.canUnifyBranches(cont);
List<InitState> branchStates = null;
if (unifyBranches) {
branchStates = new ArrayList<InitState>();
}
InitState contState = state.enterContinuation(cont);
for (Block inner: cont.getBlocks()) {
InitState blockState = contState.makeChild();
recurseOnBlock(logger, inner, blockState, validate);
if (unifyBranches) {
branchStates.add(blockState);
}
}
// Unify information from branches into parent
if (unifyBranches) {
state.unifyBranches(cont, branchStates);
}
}
@Test
public void assertThatLog4jMockPolicyWorks() throws Exception {
final Log4jUser tested = createPartialMockAndInvokeDefaultConstructor(Log4jUser.class, "getMessage");
final String otherMessage = "other message";
final String firstMessage = "first message and ";
expect(tested.getMessage()).andReturn(firstMessage);
replayAll();
final String actual = tested.mergeMessageWith(otherMessage);
Class<? extends Logger> class1 = Whitebox.getInternalState(Log4jUserParent.class, Logger.class).getClass();
assertTrue(class1.getName().contains("org.apache.log4j.Logger$$EnhancerByCGLIB$$"));
verifyAll();
assertEquals(firstMessage + otherMessage, actual);
}
@Test
public void testListAppender() {
Logger logger = LogManager.getLogger("test");
logger.debug("This is a test of the root logger");
LoggerContext loggerContext = org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = ((org.apache.logging.log4j.core.LoggerContext) loggerContext).getConfiguration();
Map<String, Appender> appenders = configuration.getAppenders();
ListAppender eventAppender = null;
ListAppender messageAppender = null;
for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
if (entry.getKey().equals("list")) {
messageAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
} else if (entry.getKey().equals("events")) {
eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
}
}
assertNotNull("No Event Appender", eventAppender);
assertNotNull("No Message Appender", messageAppender);
List<LoggingEvent> events = eventAppender.getEvents();
assertTrue("No events", events != null && events.size() > 0);
List<String> messages = messageAppender.getMessages();
assertTrue("No messages", messages != null && messages.size() > 0);
}
@Override
public void generate(Logger logger, CompilerBackend gen, GenInfo info) {
switch(this.op) {
case CALL_FOREIGN:
gen.callForeignFunctionWrapped(id, outputs, inputs, props);
break;
case CALL_SYNC:
case CALL_CONTROL:
case CALL_LOCAL:
case CALL_LOCAL_CONTROL:
List<Boolean> blocking = info.getBlockingInputVector(id);
assert(blocking != null && blocking.size() == inputs.size()) :
this + "; blocking: " + blocking;
List<Boolean> needToBlock = new ArrayList<Boolean>(inputs.size());
for (int i = 0; i < inputs.size(); i++) {
needToBlock.add(blocking.get(i) && (!this.closedInputs.get(i)));
}
gen.functionCall(id, outputs, inputs, needToBlock,
execMode(), props);
break;
default:
throw new STCRuntimeError("Huh?");
}
}
/**
* Optimize the program and return a new one
*
* NOTE: the input might be modified in-place
* @param icOutput where to log IC between optimiation steps. Null for
* no output
* @return
* @throws InvalidWriteException
*/
public static Program optimize(Logger logger, PrintStream icOutput,
Program prog) throws UserException {
boolean logIC = icOutput != null;
if (logIC) {
prog.log(icOutput, "Initial IC before optimization");
}
long nIterations = Settings.getLongUnchecked(Settings.OPT_MAX_ITERATIONS);
boolean debug = Settings.getBooleanUnchecked(Settings.COMPILER_DEBUG);
preprocess(icOutput, logger, debug, prog);
iterate(icOutput, logger, prog, debug, nIterations);
postprocess(icOutput, logger, debug, prog, nIterations);
if (logIC) {
prog.log(icOutput, "Final optimized IC");
}
return prog;
}
/**
* Enable or disable debugging
*
* @param debugging
*/
public void setDebugging(boolean debugging)
{
this.debugging = debugging;
if (debugging)
{
Thread.setDefaultUncaughtExceptionHandler(debugAppender);
BasicConfigurator.configure(debugAppender);
}
else
{
// Turn off everything before disabling the debug tab
postClock.stop();
postMessagesButton.setSelected(false);
drawTextGridBox.setSelected(false);
drawBorderGridBox.setSelected(false);
chat.repaint();
Thread.setDefaultUncaughtExceptionHandler(null);
Logger.getRootLogger().removeAppender(debugAppender);
}
}
@Test
public void tesApplyUserLoggerLevels() {
// set the level
Logger.getLogger("fake.logger").setLevel(Level.INFO);
// read the configuration and remember the level
RemoteLoggingConfigurator remoteLoggingConfig = new RemoteLoggingConfigurator(null, -1);
// change the level in log4j
Logger.getLogger("fake.logger").setLevel(Level.DEBUG);
assertTrue(Logger.getLogger("fake.logger").getLevel().equals(Level.DEBUG));
assertTrue(remoteLoggingConfig.needsApplying());
// apply the remembered level
remoteLoggingConfig.apply();
assertTrue(Logger.getLogger("fake.logger").getLevel().equals(Level.INFO));
}
/**
* Creates new logger with given configuration {@code cfgUrl}.
*
* @param cfgUrl URL for Log4j configuration XML file.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public GridTestLog4jLogger(final URL cfgUrl) throws IgniteCheckedException {
if (cfgUrl == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
cfg = cfgUrl.getPath();
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
DOMConfigurator.configure(cfgUrl);
return Logger.getRootLogger();
}
});
quiet = quiet0;
}
/**
* Adds Logger Appender to a specified logger
* @param logger Logger to add appender to, if null, use root logger
* @param name Appender name
* @param properties Appender properties
* @return True if the appender has been added successfully
*/
public static boolean addAppender(Logger logger, String name, Properties properties)
{
if (logger == null) {
logger = LogManager.getRootLogger();
}
if (getAppendersNames(logger).contains(name)) {
LoggerUtil.logger.warn("A logger appender with the name '{}' exists. Cannot add a new logger appender with the same name", name);
} else {
try {
Method method = PropertyConfigurator.class.getDeclaredMethod("parseAppender", Properties.class, String.class);
method.setAccessible(true);
Appender appender = (Appender)method.invoke(new PropertyConfigurator(), properties, name);
if (appender == null) {
LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties);
} else {
logger.addAppender(appender);
return true;
}
} catch (Exception ex) {
LoggerUtil.logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties, ex);
}
}
return false;
}
/**
* Tests CDATA element within exception. See bug 37560.
*/
public void testExceptionWithCDATA() throws Exception {
Logger logger = Logger.getLogger("com.example.bar");
Level level = Level.INFO;
String exceptionMessage ="<envelope><faultstring><![CDATA[The EffectiveDate]]></faultstring><envelope>";
LoggingEvent event =
new LoggingEvent(
"com.example.bar", logger, level, "Hello, World", new Exception(exceptionMessage));
Layout layout = createLayout();
String result = layout.format(event);
Element parsedResult = parse(result);
NodeList throwables = parsedResult.getElementsByTagName("log4j:throwable");
assertEquals(1, throwables.getLength());
StringBuffer buf = new StringBuffer();
for(Node child = throwables.item(0).getFirstChild();
child != null;
child = child.getNextSibling()) {
buf.append(child.getNodeValue());
}
assertTrue(buf.toString().indexOf(exceptionMessage) != -1);
}
/**
* Sets up log4j logging to fit the demo's needs.
* @param loggingDetail the {@link LoggingDetail} to use.
*/
public static void setupLogging(final LoggingDetail loggingDetail) {
// Turn off all the loggers and customize how they write to the console.
final Logger rootLogger = LogManager.getRootLogger();
rootLogger.setLevel(Level.OFF);
final ConsoleAppender ca = (ConsoleAppender) rootLogger.getAppender("stdout");
ca.setLayout(loggingDetail.getPatternLayout());
// Turn the loggers used by the demo back on.
//log.setLevel(Level.INFO);
rootLogger.setLevel(Level.INFO);
}
/**
* Simple test of NTEventLogAppender.
*/
public void testSimple() {
BasicConfigurator.configure(new NTEventLogAppender());
Logger logger = Logger.getLogger("org.apache.log4j.nt.NTEventLogAppenderTest");
int i = 0;
logger.debug( "Message " + i++);
logger.info( "Message " + i++);
logger.warn( "Message " + i++);
logger.error( "Message " + i++);
logger.log(Level.FATAL, "Message " + i++);
logger.debug("Message " + i++, new Exception("Just testing."));
}
@Before
public void setUp() {
smtp = new SmtpManager();
Logger.getRootLogger()
.info("--------------------------START TESTCASE----------------------------------------");
}
@Before
public void setup() {
Level desiredLevel = Level.ALL;
Logger log = Logger.getLogger(DateIndexTableConfigHelperTest.class);
DateIndexTableConfigHelperTest.testDriverLevel = log.getLevel();
log.setLevel(desiredLevel);
}
@Test(expected = FullTableScansDisallowedException.class)
public void testErrorMissingReverseIndex() throws Exception {
log.info("------ testMissingReverseIndex ------");
Logger.getLogger(DefaultQueryPlanner.class).setLevel(Level.DEBUG);
// should at least match usa, fra, and ita
String regex = "'.*?a'";
for (final TestCities city : TestCities.values()) {
String query = CityField.CODE.name() + RE_OP + regex;
runTest(query, query);
}
}
public JoinTestCaseEvent( String loggerFQCN,
Logger logger,
TestCaseState testCaseState ) {
super(loggerFQCN,
logger,
"Joining test case with id " + testCaseState.getTestcaseId(),
LoggingEventType.JOIN_TEST_CASE);
this.testCaseState = testCaseState;
}
/**
* This method is used to initialize the image map. Images are downloaded
* by the crawler component, and the map we initialize here associates
* the url of the image with the binary image content.
*/
public void initializeImageMap() {
if (imageMap == null) {
imageMap = new HashMap<>();
}
if (imageOnErrorSet == null) {
imageOnErrorSet = new HashSet<>();
}
imageMap.clear();
for (RelatedContent relatedContent : ssp.getRelatedContentSet()) {
if (relatedContent instanceof ImageContent) {
BufferedImage image;
if (((ImageContent) relatedContent).getHttpStatusCode() != 200
|| ((ImageContent) relatedContent).getContent() == null) {
imageOnErrorSet.add((ImageContent) relatedContent);
} else {
try {
image = ImageIO.read(new ByteArrayInputStream(
((ImageContent) relatedContent).getContent()));
imageMap.put(((Content) relatedContent).getURI(), image);
} catch (IOException ex) {
Logger.getLogger(SSPHandlerImpl.class.getName()).error(ex);
}
}
}
}
}
@Test
public void testAllocateContainerOnNodeWithoutOffSwitchSpecified()
throws Exception {
Logger rootLogger = LogManager.getRootLogger();
rootLogger.setLevel(Level.DEBUG);
MockRM rm = new MockRM(conf);
rm.start();
MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB);
RMApp app1 = rm.submitApp(2048);
// kick the scheduling, 2 GB given to AM1, remaining 4GB on nm1
nm1.nodeHeartbeat(true);
RMAppAttempt attempt1 = app1.getCurrentAppAttempt();
MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId());
am1.registerAppAttempt();
// add request for containers
List<ResourceRequest> requests = new ArrayList<ResourceRequest>();
requests.add(am1.createResourceReq("127.0.0.1", 1 * GB, 1, 1));
requests.add(am1.createResourceReq("/default-rack", 1 * GB, 1, 1));
am1.allocate(requests, null); // send the request
try {
// kick the schedule
nm1.nodeHeartbeat(true);
} catch (NullPointerException e) {
Assert.fail("NPE when allocating container on node but "
+ "forget to set off-switch request should be handled");
}
rm.stop();
}
public Log4jSyslogBackLogHandler(Class loggerClass, boolean appendReason) {
if (loggerClass == null) {
throw new SyslogRuntimeException("loggerClass cannot be null");
}
this.logger = Logger.getLogger(loggerClass);
this.appendReason = appendReason;
initialize();
}
/**
* Test Or of Level and Time.
*/
@Test public void test3() {
Stack<Object> stack = new Stack<>();
stack.push(LevelEqualsRule.getRule("INFO"));
stack.push(TimestampInequalityRule.getRule(">=", "2008-05-21 00:44:45"));
Rule rule = OrRule.getRule(stack);
AssertJUnit.assertEquals(0, stack.size());
Calendar cal = new GregorianCalendar(2008, 4, 21, 0, 45, 44);
LoggingEvent event = new LoggingEvent("org.apache.log4j.Logger",
Logger.getRootLogger(), cal.getTimeInMillis(), Level.INFO,
"Hello, World", null);
AssertJUnit.assertTrue(rule.evaluate(Log4jUtil.translateLog4j(event), null));
}
@Override
public Logger makeNewLoggerInstance(String name)
{
Logger logger = new DefaultLogger(name);
Level level = getLevelFor(name);
if (level != null) {
logger.setLevel(level);
}
return logger;
}
/**
* Creates two objects with the same field values and verifies they are equal.
*
* @return true, if successful
* @throws Exception the exception
*/
public boolean testIdentityFieldEquals() throws Exception {
Logger.getLogger(getClass()).debug(
"Test identity field equals - " + clazz.getName());
Object o1 = createObject(1);
Object o2 = createObject(1);
return o1.equals(o2);
}
/**
* Creates new logger with given implementation.
*
* @param impl Log4j implementation to use.
* @param path Configuration file/url path.
*/
private Log4JLogger(final Logger impl, final String path) {
assert impl != null;
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
return impl;
}
});
quiet = quiet0;
cfg = path;
}
@Test
public void testLog4j() throws InterruptedException, MQClientException {
Logger logger = Logger.getLogger("testLogger");
for (int i = 0; i < 50; i++) {
logger.info("log4j " + this.getType() + " simple test message " + i);
}
int received = consumeMessages(30, "log4j",30);
Assert.assertTrue(received>20);
}
@Override
public void trace(Object message) {
Logger.getLogger(getClass()).trace(message);
synchronized (iLog) {
iLog.add(new QueueMessage(QueueMessage.Level.TRACE, message));
}
}
public void logSummary(final Logger log) {
Logger logToUse = log;
if (null != log)
logToUse = this.log;
final StringBuilder sb = new StringBuilder(256);
int count = 1;
long totalDurationMillis = 0l;
logToUse.debug("Elapsed time running query");
final int length = Integer.toString(TIMERS.values().length).length();
for (TIMERS timer : TIMERS.values()) {
final String countStr = Integer.toString(count);
final String paddedCount = new StringBuilder(QueryStopwatch.INDENT).append(StringUtils.leftPad(countStr, length, "0")).append(") ").toString();
long myValue = getValue(timer);
// Stopwatch.toString() will give us appropriate units for the timing
sb.append(paddedCount).append(timer.name()).append(": ").append(formatMillis(myValue));
totalDurationMillis += myValue;
count++;
logToUse.debug(sb.toString());
sb.setLength(0);
}
sb.append(QueryStopwatch.INDENT).append("Total elapsed: ").append(formatMillis(totalDurationMillis));
logToUse.debug(sb.toString());
}
/**
* Logs the sql statement. This is typically used before db executions.
* This method is also included in select and update methods of this class, so they don't have to be called explicitly
* @param logger
* @param statement
* @param parameter
*/
protected void logSqlStatement(Logger logger, String statement, Object... parameter) {
if (logger.isDebugEnabled()) {
if (parameter != null && parameter.length > 0) {
logger.debug("SQL: " + statement + "\nParameter: " + getParameterStringList(parameter));
} else {
logger.debug("SQL: " + statement);
}
}
}
public static void logMappingSguidAndUniqueId(Logger logger, SingleMessageWrapper singleMessageWrapper, String uniqueId) {
List<PharmaceuticalCareEventType> listEvent = singleMessageWrapper.getAllEventsOfType(PharmaceuticalCareEventType.class);
Iterator i$ = listEvent.iterator();
while(i$.hasNext()) {
PharmaceuticalCareEventType event = (PharmaceuticalCareEventType)i$.next();
log(logger, "********** PERFLOG-INTERNAL: ", "MAPPING", (String)null, (Long)null, (Long)null, event.getId(), uniqueId);
}
}