Java Code Examples for org.apache.log4j.Level

The following are top voted examples for showing how to use org.apache.log4j.Level. 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: pai   File: LauncherModule.java   View source code 6 votes vote down vote up
@PUT
@Path(WebStructure.APPLICATION_PROGRESS_PATH)
@Consumes({MediaType.APPLICATION_JSON})
public Response putApplicationProgress(
    @Context HttpServletRequest hsr,
    @PathParam(WebStructure.FRAMEWORK_NAME_PATH_PARAM) String frameworkName,
    OverrideApplicationProgressRequest overrideApplicationProgressRequest) throws Exception {
  LOGGER.logSplittedLines(Level.INFO,
      "[%s]: putApplicationProgress: \n%s",
      frameworkName, WebCommon.toJson(overrideApplicationProgressRequest));

  ModelValidation.validate(frameworkName);
  ModelValidation.validate(overrideApplicationProgressRequest);

  requestManager.updateApplicationProgress(frameworkName, overrideApplicationProgressRequest);
  return Response
      .status(HttpStatus.SC_ACCEPTED)
      .header("Location", hsr.getRequestURL())
      .build();
}
 
Example 2
Project: LightSIP   File: LogWriter.java   View source code 6 votes vote down vote up
public Level getLevel(int traceLevel) {
     if ( traceLevel == TRACE_INFO ) {
        return Level.INFO;
    } else if ( traceLevel == TRACE_ERROR ) {
        return Level.ERROR;
    } else if ( traceLevel == TRACE_DEBUG) {
        return Level.DEBUG;
    } else if (traceLevel == TRACE_TRACE) {
        return Level.ALL;
    } else {
        return Level.OFF;
    }
}
 
Example 3
Project: EatDubbo   File: ClientReconnectTest.java   View source code 6 votes vote down vote up
/**
 * 重连日志的校验
 */
@Test
public void testReconnectWaringLog() throws RemotingException, InterruptedException{
    int port = NetUtils.getAvailablePort();
    DubboAppender.doStart();
    String url = "exchange://127.0.0.4:"+port + "/client.reconnect.test?check=false&"
    +Constants.RECONNECT_KEY+"="+1 //1ms reconnect,保证有足够频率的重连
    +"&"+Constants.SHUTDOWN_TIMEOUT_KEY+ "=1"//shutdown时间足够短,确保error日志输出
    +"&reconnect.waring.period=100";//每隔多少warning记录一次
    try{
        Exchangers.connect(url);
    }catch (Exception e) {
        //do nothing
    }
    int count =  0;
    for (int i=0;i<100;i++){
        count =  LogUtil.findMessage(Level.WARN, "client reconnect to ") ; 
        if (count >=1){
            break;
        }
        Thread.sleep(50);//重连线程的运行
    }
    Assert.assertTrue("warning message count must >= 1, real :"+count, count>= 1);
    DubboAppender.doStop();
}
 
Example 4
Project: phone-simulator   File: TestCapScfMan.java   View source code 6 votes vote down vote up
@Override
public void onDialogRequest(CAPDialog capDialog, CAPGprsReferenceNumber referenceNumber) {
    synchronized (this) {
        if (capDialog instanceof CAPDialogCircuitSwitchedCall) {
            CAPDialogCircuitSwitchedCall dlg = (CAPDialogCircuitSwitchedCall) capDialog;

            CAPDialogCircuitSwitchedCall curDialog = this.currentDialog;
            currentRequestDef = "";
            if (curDialog == null) {
                this.currentDialog = dlg;
                this.testerHost
                        .sendNotif(SOURCE_NAME, "DlgAccepted:", "TrId=" + capDialog.getRemoteDialogId(), Level.DEBUG);
            } else {
                try {
                    capDialog.abort(CAPUserAbortReason.congestion);
                } catch (CAPException e) {
                    this.testerHost.sendNotif(SOURCE_NAME, "Exception when rejecting Dialog", e.toString(), Level.DEBUG);
                }
                this.testerHost.sendNotif(SOURCE_NAME, "Rejected incoming Dialog:",
                        "TrId=" + capDialog.getRemoteDialogId(), Level.DEBUG);
            }
        }
    }
}
 
Example 5
Project: EatDubbo   File: ClientReconnectTest.java   View source code 6 votes vote down vote up
/**
 * 重连日志的校验,不能一直抛出error日志.
 */
@Test
public void testReconnectErrorLog() throws RemotingException, InterruptedException{
    int port = NetUtils.getAvailablePort();
    DubboAppender.doStart();
    String url = "exchange://127.0.0.3:"+port + "/client.reconnect.test?check=false&"
    +Constants.RECONNECT_KEY+"="+1 + //1ms reconnect,保证有足够频率的重连
    "&"+Constants.SHUTDOWN_TIMEOUT_KEY+ "=1";//shutdown时间足够短,确保error日志输出
    try{
        Exchangers.connect(url);
    }catch (Exception e) {
        //do nothing
    }
    Thread.sleep(1500);//重连线程的运行
    Assert.assertEquals("only one error message ", 1 , LogUtil.findMessage(Level.ERROR, "client reconnect to "));
    DubboAppender.doStop();
}
 
Example 6
Project: phone-simulator   File: TesterHost.java   View source code 6 votes vote down vote up
public void sendNotif(String source, String msg, Throwable e, Level logLevel) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement st : e.getStackTrace()) {
        if (sb.length() > 0)
            sb.append("\n");
        sb.append(st.toString());
    }
    this.doSendNotif(source, msg + " - " + e.toString(), sb.toString());

    logger.log(logLevel, msg, e);
    // if (showInConsole) {
    // logger.error(msg, e);
    // } else {
    // logger.debug(msg, e);
    // }
}
 
Example 7
Project: LightSIP   File: LogWriter.java   View source code 6 votes vote down vote up
public void logStackTrace(int traceLevel) {
    if (needsLogging) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        StackTraceElement[] ste = new Exception().getStackTrace();
        // Skip the log writer frame and log all the other stack frames.
        for (int i = 1; i < ste.length; i++) {
            String callFrame = "[" + ste[i].getFileName() + ":"
                    + ste[i].getLineNumber() + "]";
            pw.print(callFrame);
        }
        pw.close();
        String stackTrace = sw.getBuffer().toString();
        Level level = this.getLevel(traceLevel);
        Priority priority = this.getLogPriority();
        if ( level.isGreaterOrEqual(priority)) {
            logger.log(level,stackTrace);
        }

    }
}
 
Example 8
Project: unitimes   File: ApplicationConfig.java   View source code 6 votes vote down vote up
public static boolean configureLogging() {
	if (!_RootDAO.isConfigured()) return false;
	
    org.hibernate.Session hibSession = ApplicationConfigDAO.getInstance().createNewSession();
    try {
    	for (ApplicationConfig config: (List<ApplicationConfig>)hibSession.createQuery("from ApplicationConfig where key like 'log4j.logger.%'").list()) {
    		Level level = Level.toLevel(config.getValue());
    		boolean root = "log4j.logger.root".equals(config.getKey());
    		Logger logger = (root ? Logger.getRootLogger() : Logger.getLogger(config.getKey().substring("log4j.logger.".length())));
    		logger.setLevel(level);
    		Debug.info("Logging level for " + logger.getName() + " set to " + level);
    	}
    } finally {
    	hibSession.close();
    }
    
    return true;
}
 
Example 9
Project: hadoop-oss   File: EventCounter.java   View source code 6 votes vote down vote up
@Override
public void append(LoggingEvent event) {
  Level level = event.getLevel();
  // depends on the api, == might not work
  // see HADOOP-7055 for details
  if (level.equals(Level.INFO)) {
    counts.incr(INFO);
  }
  else if (level.equals(Level.WARN)) {
    counts.incr(WARN);
  }
  else if (level.equals(Level.ERROR)) {
    counts.incr(ERROR);
  }
  else if (level.equals(Level.FATAL)) {
    counts.incr(FATAL);
  }
}
 
Example 10
Project: hadoop   File: TestReservedRawPaths.java   View source code 6 votes vote down vote up
@Before
public void setup() throws Exception {
  conf = new HdfsConfiguration();
  fsHelper = new FileSystemTestHelper();
  // Set up java key store
  String testRoot = fsHelper.getTestRootDir();
  File testRootDir = new File(testRoot).getAbsoluteFile();
  final Path jksPath = new Path(testRootDir.toString(), "test.jks");
  conf.set(DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI,
      JavaKeyStoreProvider.SCHEME_NAME + "://file" + jksPath.toUri()
  );
  cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
  Logger.getLogger(EncryptionZoneManager.class).setLevel(Level.TRACE);
  fs = cluster.getFileSystem();
  fsWrapper = new FileSystemTestWrapper(cluster.getFileSystem());
  fcWrapper = new FileContextTestWrapper(
      FileContext.getFileContext(cluster.getURI(), conf));
  dfsAdmin = new HdfsAdmin(cluster.getURI(), conf);
  // Need to set the client's KeyProvider to the NN's for JKS,
  // else the updates do not get flushed properly
  fs.getClient().setKeyProvider(cluster.getNameNode().getNamesystem()
      .getProvider());
  DFSTestUtil.createKey(TEST_KEY, cluster, conf);
}
 
Example 11
Project: dubbox-hystrix   File: ClientReconnectTest.java   View source code 6 votes vote down vote up
/**
 * 重连日志的校验
 */
@Test
public void testReconnectWaringLog() throws RemotingException, InterruptedException{
    int port = NetUtils.getAvailablePort();
    DubboAppender.doStart();
    String url = "exchange://127.0.0.4:"+port + "/client.reconnect.test?check=false&"
    +Constants.RECONNECT_KEY+"="+1 //1ms reconnect,保证有足够频率的重连
    +"&"+Constants.SHUTDOWN_TIMEOUT_KEY+ "=1"//shutdown时间足够短,确保error日志输出
    +"&reconnect.waring.period=100";//每隔多少warning记录一次
    try{
        Exchangers.connect(url);
    }catch (Exception e) {
        //do nothing
    }
    int count =  0;
    for (int i=0;i<100;i++){
        count =  LogUtil.findMessage(Level.WARN, "client reconnect to ") ; 
        if (count >=1){
            break;
        }
        Thread.sleep(50);//重连线程的运行
    }
    Assert.assertTrue("warning message count must >= 1, real :"+count, count>= 1);
    DubboAppender.doStop();
}
 
Example 12
Project: CloudDB   File: app_KVClient.java   View source code 6 votes vote down vote up
/**
   * Main entry point for the echo server application. 
   * @param args contains the port number at args[0].
   */
  public static void main(String[] args) {
  	try {
	new LogSetup("logs/client.log", Level.OFF);
	app_KVClient app = new app_KVClient();
	app.run();
} catch (IOException e) {
	System.out.println("Error! Unable to initialize logger!");
	e.printStackTrace();
	System.exit(1);
}
  }
 
Example 13
Project: CloudDB   File: LogSetup.java   View source code 6 votes vote down vote up
public static boolean isValidLevel(String levelString) {
	boolean valid = false;
	
	if(levelString.equals(Level.ALL.toString())) {
		valid = true;
	} else if(levelString.equals(Level.DEBUG.toString())) {
		valid = true;
	} else if(levelString.equals(Level.INFO.toString())) {
		valid = true;
	} else if(levelString.equals(Level.WARN.toString())) {
		valid = true;
	} else if(levelString.equals(Level.ERROR.toString())) {
		valid = true;
	} else if(levelString.equals(Level.FATAL.toString())) {
		valid = true;
	} else if(levelString.equals(Level.OFF.toString())) {
		valid = true;
	}
	
	return valid;
}
 
Example 14
Project: phone-simulator   File: TestSmsClientMan.java   View source code 6 votes vote down vote up
public boolean start() {
    this.countSriReq = 0;
    this.countSriResp = 0;
    this.countMtFsmReq = 0;
    this.countMtFsmReqNot = 0;
    this.countMtFsmResp = 0;
    this.countMoFsmReq = 0;
    this.countMoFsmResp = 0;
    this.countIscReq = 0;
    this.countRsmdsReq = 0;
    this.countRsmdsResp = 0;
    this.countAscReq = 0;
    this.countAscResp = 0;
    this.countErrRcvd = 0;
    this.countErrSent = 0;

    MAPProvider mapProvider = this.mapMan.getMAPStack().getMAPProvider();
    mapProvider.getMAPServiceSms().acivate();
    mapProvider.getMAPServiceSms().addMAPServiceListener(this);
    mapProvider.addMAPDialogListener(this);
    this.testerHost.sendNotif(SOURCE_NAME, "SMS Client has been started", "", Level.INFO);
    isStarted = true;

    return true;
}
 
Example 15
Project: convertigo-engine   File: LogStep.java   View source code 6 votes vote down vote up
public String[] getTagsForProperty(String propertyName) {
	if (propertyName.equals("level")) {
		return new String[]{
				Level.ERROR.toString(),
				Level.WARN.toString(),
				Level.INFO.toString(),
				Level.DEBUG.toString(),
				Level.TRACE.toString(),
		};
	}
	if (propertyName.equals("logger")) {
		return new String[]{
				Engine.logEngine.getName(),
				Engine.logContext.getName(),
				Engine.logUser.getName(),
				Engine.logAudit.getName(),
		};
	}
	return new String[0];
}
 
Example 16
Project: ats-framework   File: Test_RemoteLoggingConfigurator.java   View source code 6 votes vote down vote up
@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( "127.0.0.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 ) );
}
 
Example 17
Project: phone-simulator   File: TestSmsServerMan.java   View source code 6 votes vote down vote up
@Override
public void onMoForwardShortMessageRequest(MoForwardShortMessageRequest ind) {
    if (!isStarted)
        return;

    MAPDialogSms curDialog = ind.getMAPDialog();
    long invokeId = ind.getInvokeId();
    SM_RP_DA da = ind.getSM_RP_DA();
    SM_RP_OA oa = ind.getSM_RP_OA();
    SmsSignalInfo si = ind.getSM_RP_UI();

    this.onMoRequest(da, oa, si, curDialog);

    try {
        curDialog.addMoForwardShortMessageResponse(invokeId, null, null);
        this.needSendClose = true;

        this.countMoFsmResp++;
        this.testerHost.sendNotif(SOURCE_NAME, "Sent: moResp", "", Level.DEBUG);
    } catch (MAPException e) {
        this.testerHost.sendNotif(SOURCE_NAME, "Exception when invoking addMoForwardShortMessageResponse : " + e.getMessage(), e, Level.ERROR);
    }
}
 
Example 18
Project: ats-framework   File: DbEventRequestProcessor.java   View source code 6 votes vote down vote up
private int convertMsgLevel( org.apache.log4j.Level level ) {

        switch (level.toInt()) {
            case Level.FATAL_INT:
                return 1;
            case Level.ERROR_INT:
                return 2;
            case Level.WARN_INT:
                return 3;
            case Level.INFO_INT:
                return 4;
            case Level.DEBUG_INT:
                return 5;
            case Level.TRACE_INT:
                return 6;
            case SystemLogLevel.SYSTEM_INT:
                return 7;
            default:
                return 4;
        }
    }
 
Example 19
Project: pai   File: ApplicationMaster.java   View source code 6 votes vote down vote up
private void onContainerStartSucceeded(String containerId) throws Exception {
  String logSuffix = String.format("[%s]: onContainerStartSucceeded", containerId);

  if (!statusManager.isContainerIdLiveAssociated(containerId)) {
    LOGGER.logWarning("[NotLiveAssociated]%s", logSuffix);
    return;
  }

  TaskStatus taskStatus = statusManager.getTaskStatusWithLiveAssociatedContainerId(containerId);
  String taskRoleName = taskStatus.getTaskRoleName();
  TaskStatusLocator taskLocator = new TaskStatusLocator(taskRoleName, taskStatus.getTaskIndex());
  String linePrefix = String.format("%s: ", taskLocator);

  LOGGER.logSplittedLines(Level.INFO,
      "%s%s\n%s",
      taskLocator, logSuffix, generateContainerDiagnostics(taskStatus, linePrefix));

  statusManager.transitionTaskState(taskLocator, TaskState.CONTAINER_RUNNING);
}
 
Example 20
Project: ats-framework   File: AutoLevel.java   View source code 6 votes vote down vote up
/**
   Convert the string passed as argument to a level. If the
   conversion fails, then this method returns the value of
   <code>defaultLevel</code>.  
*/
public static Level toLevel(
                             String sArg,
                             Level defaultLevel ) {

    if (sArg == null)
        return defaultLevel;

    String s = sArg.toUpperCase();

    if ("SYSTEM".equals(s)) {
        return AutoLevel.SYSTEM;
    } else {
        return Level.toLevel(sArg, defaultLevel);
    }
}
 
Example 21
Project: alvisnlp   File: TikaReader.java   View source code 6 votes vote down vote up
@Override
public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException {
	Logger.getLogger("org.apache.pdfbox").setLevel(Level.OFF);
	AutoDetectParser parser = new AutoDetectParser();
	ParseContext parseContext = new ParseContext();
	try {
		for (InputStream is : Iterators.loop(source.getInputStreams())) {
			TikaReaderHandler handler = parse(parser, parseContext, is);
			Document doc = createDocument(corpus, handler);
			createTagAnnotations(doc, handler);
		}
	}
	catch (IOException|SAXException|TikaException e) {
		rethrow(e);
	}
}
 
Example 22
Project: hadoop   File: TestRMDelegationTokens.java   View source code 5 votes vote down vote up
@Before
public void setup() {
  Logger rootLogger = LogManager.getRootLogger();
  rootLogger.setLevel(Level.DEBUG);
  ExitUtil.disableSystemExit();
  conf = new YarnConfiguration();
  UserGroupInformation.setConfiguration(conf);
  conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName());
  conf.set(YarnConfiguration.RM_SCHEDULER, FairScheduler.class.getName());
}
 
Example 23
Project: hadoop   File: TestDecommissioningStatus.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  conf = new HdfsConfiguration();
  conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY,
      false);

  // Set up the hosts/exclude files.
  localFileSys = FileSystem.getLocal(conf);
  Path workingDir = localFileSys.getWorkingDirectory();
  dir = new Path(workingDir, "build/test/data/work-dir/decommission");
  assertTrue(localFileSys.mkdirs(dir));
  excludeFile = new Path(dir, "exclude");
  conf.set(DFSConfigKeys.DFS_HOSTS_EXCLUDE, excludeFile.toUri().getPath());
  Path includeFile = new Path(dir, "include");
  conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 
      1000);
  conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_PENDING_TIMEOUT_SEC_KEY,
      4);
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1000);
  conf.setInt(DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY, 1);
  conf.setLong(DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY, 1);

  writeConfigFile(localFileSys, excludeFile, null);
  writeConfigFile(localFileSys, includeFile, null);

  cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).build();
  cluster.waitActive();
  fileSys = cluster.getFileSystem();
  cluster.getNamesystem().getBlockManager().getDatanodeManager()
      .setHeartbeatExpireInterval(3000);
  Logger.getLogger(DecommissionManager.class).setLevel(Level.DEBUG);
}
 
Example 24
Project: hadoop   File: MRAppBenchmark.java   View source code 5 votes vote down vote up
/**
 * Runs memory and time benchmark with Mock MRApp.
 */
public void run(MRApp app) throws Exception {
  Logger rootLogger = LogManager.getRootLogger();
  rootLogger.setLevel(Level.WARN);
  long startTime = System.currentTimeMillis();
  Job job = app.submit(new Configuration());
  while (!job.getReport().getJobState().equals(JobState.SUCCEEDED)) {
    printStat(job, startTime);
    Thread.sleep(2000);
  }
  printStat(job, startTime);
}
 
Example 25
Project: dubbo2   File: LogUtil.java   View source code 5 votes vote down vote up
public static int findMessage(Level expectedLevel, String expectedMessage) {
    int count = 0;
    List<Log> logList = DubboAppender.logList;
    for (int i = 0; i < logList.size(); i++) {
        Level logLevel = logList.get(i).getLogLevel();
        if (logLevel.equals(expectedLevel)) {
            String logMessage = logList.get(i).getLogMessage();
            if (logMessage.contains(expectedMessage)) count++;
        }
    }
    return count;
}
 
Example 26
Project: pai   File: Service.java   View source code 5 votes vote down vote up
private void completeFramework(FrameworkStatus frameworkStatus) throws Exception {
  String frameworkName = frameworkStatus.getFrameworkName();

  LOGGER.logSplittedLines(Level.INFO,
      "%s: completeFramework: FrameworkStatus:\n%s",
      frameworkName, WebCommon.toJson(frameworkStatus));

  statusManager.transitionFrameworkState(frameworkName, FrameworkState.FRAMEWORK_COMPLETED);
}
 
Example 27
Project: phone-simulator   File: CapMan.java   View source code 5 votes vote down vote up
public boolean start() {
    try {
        this.initCap(this.sccpStack, this.testerHost.getSccpMan().getLocalSsn());
        this.testerHost.sendNotif(SOURCE_NAME, "TCAP+CAP has been started", "", Level.INFO);
        return true;
    } catch (Throwable e) {
        this.testerHost.sendNotif(SOURCE_NAME, "Exception when starting CapMan", e, Level.ERROR);
        return false;
    }
}
 
Example 28
Project: dubbocloud   File: LogPageHandler.java   View source code 5 votes vote down vote up
public Page handle(URL url) {
      long size = 0;
String content = "";
String modified = "Not exist";
if (file != null && file.exists()) {
	try {
		FileInputStream fis = new FileInputStream(file);
		FileChannel channel = fis.getChannel();
		size = channel.size();
		ByteBuffer bb;
		if (size <= SHOW_LOG_LENGTH) {
			bb = ByteBuffer.allocate((int) size);
			channel.read(bb, 0);
		} else {
			int pos = (int) (size - SHOW_LOG_LENGTH);
			bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
			channel.read(bb, pos);
		}
		bb.flip();
		content = new String(bb.array()).replace("<", "&lt;")
				.replace(">", "&gt;").replace("\n", "<br/><br/>");
		modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date(file.lastModified()));
	} catch (IOException e) {
	}
}
Level level = LogManager.getRootLogger().getLevel();
      List<List<String>> rows = new ArrayList<List<String>>();
      List<String> row = new ArrayList<String>();
      row.add(content);
      rows.add(row);
      return new Page("Log", "Log",  new String[] {(file == null ? "" : file.getName()) + ", " + size + " bytes, " + modified + ", " + level}, rows);
  }
 
Example 29
Project: hadoop   File: TestDelegationToken.java   View source code 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testDelegationTokenWebHdfsApi() throws Exception {
  ((Log4JLogger)NamenodeWebHdfsMethods.LOG).getLogger().setLevel(Level.ALL);
  final String uri = WebHdfsFileSystem.SCHEME  + "://"
      + config.get(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY);
  //get file system as JobTracker
  final UserGroupInformation ugi = UserGroupInformation.createUserForTesting(
      "JobTracker", new String[]{"user"});
  final WebHdfsFileSystem webhdfs = ugi.doAs(
      new PrivilegedExceptionAction<WebHdfsFileSystem>() {
    @Override
    public WebHdfsFileSystem run() throws Exception {
      return (WebHdfsFileSystem)FileSystem.get(new URI(uri), config);
    }
  });

  { //test addDelegationTokens(..)
    Credentials creds = new Credentials();
    final Token<?> tokens[] = webhdfs.addDelegationTokens("JobTracker", creds);
    Assert.assertEquals(1, tokens.length);
    Assert.assertEquals(1, creds.numberOfTokens());
    Assert.assertSame(tokens[0], creds.getAllTokens().iterator().next());
    checkTokenIdentifier(ugi, tokens[0]);
    final Token<?> tokens2[] = webhdfs.addDelegationTokens("JobTracker", creds);
    Assert.assertEquals(0, tokens2.length);
  }
}
 
Example 30
Project: hrrs   File: Log4jLoggerLevelAccessor.java   View source code 5 votes vote down vote up
@Override
public void setRootLevel(String levelName) {
    checkNotNull(levelName, "levelName");
    LOGGER.debug("updating root logger level (name={})", levelName);
    Level level = Level.toLevel(levelName);
    Logger logger = LogManager.getRootLogger();
    logger.setLevel(level);
}
 
Example 31
Project: sstore-soft   File: CatalogUtil.java   View source code 5 votes vote down vote up
public static String loadCatalogFromJar(String pathToCatalog, Logger log) {
    assert(pathToCatalog != null);

    String serializedCatalog = null;
    try {
        serializedCatalog = JarReader.readFileFromJarfile(pathToCatalog, CATALOG_FILENAME);
    } catch (Exception e) {
        if (log != null)
            log.l7dlog( Level.FATAL, LogKeys.host_VoltDB_CatalogReadFailure.name(), e);
        return null;
    }

    return serializedCatalog;
}
 
Example 32
Project: tap17-muggl-javaee   File: GeneralInstruction.java   View source code 5 votes vote down vote up
/**
 * Process any exception thrown during the execution which has not been handled by the exception
 * handler. It will be logged on the execution Logger with the level WARN and an ExecutionException
 * will be thrown, which can be processed by the virtual machine (most likely resulting in halting
 * the virtual machine). This Exception will contain the root exceptions' type and message.
 * @param e The Exception to process.
 * @throws ExecutionException Thrown in any case where no NoExceptionHandlerFoundException is thrown, containing information about the root exception.
 * @throws NoExceptionHandlerFoundException If no handler could be found.
 */
protected final void executionFailed(Exception e) throws ExecutionException,
		NoExceptionHandlerFoundException {
	// NoExceptionHandlerFoundException just have to be re-thrown.
if (e instanceof NoExceptionHandlerFoundException) {
		throw (NoExceptionHandlerFoundException) e;
	}

	// Proceed normally.
	if (Globals.getInst().execLogger.isEnabledFor(Level.WARN)) Globals.getInst().execLogger.warn("Execution of " + getName() + " failed. Reason: " + e.getMessage());
	if (e.getMessage().contains("Root Reason is:"))
		throw new ExecutionException(e.getMessage());
	throw new ExecutionException("Execution of " + getName() + " failed. Root Reason is a " + e.getClass().getName() + " with message: " + e.getMessage());
}
 
Example 33
Project: dubbo2   File: LogPageHandler.java   View source code 5 votes vote down vote up
public Page handle(URL url) {
      long size = 0;
String content = "";
String modified = "Not exist";
if (file != null && file.exists()) {
	try {
		FileInputStream fis = new FileInputStream(file);
		FileChannel channel = fis.getChannel();
		size = channel.size();
		ByteBuffer bb;
		if (size <= SHOW_LOG_LENGTH) {
			bb = ByteBuffer.allocate((int) size);
			channel.read(bb, 0);
		} else {
			int pos = (int) (size - SHOW_LOG_LENGTH);
			bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
			channel.read(bb, pos);
		}
		bb.flip();
		content = new String(bb.array()).replace("<", "&lt;")
				.replace(">", "&gt;").replace("\n", "<br/><br/>");
		modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date(file.lastModified()));
	} catch (IOException e) {
	}
}
Level level = LogManager.getRootLogger().getLevel();
      List<List<String>> rows = new ArrayList<List<String>>();
      List<String> row = new ArrayList<String>();
      row.add(content);
      rows.add(row);
      return new Page("Log", "Log",  new String[] {(file == null ? "" : file.getName()) + ", " + size + " bytes, " + modified + ", " + level}, rows);
  }
 
Example 34
Project: convertigo-engine   File: LogStatement.java   View source code 5 votes vote down vote up
public String[] getTagsForProperty(String propertyName) {
	if(propertyName.equals("level")){
		return new String[]{
				Level.ERROR.toString(),
				Level.WARN.toString(),
				Level.INFO.toString(),
				Level.DEBUG.toString(),
				Level.TRACE.toString(),
		};
	}
	return new String[0];
}
 
Example 35
Project: hadoop   File: NNThroughputBenchmark.java   View source code 5 votes vote down vote up
static void setNameNodeLoggingLevel(Level logLevel) {
  LOG.fatal("Log level = " + logLevel.toString());
  // change log level to NameNode logs
  DFSTestUtil.setNameNodeLogLevel(logLevel);
  GenericTestUtils.setLogLevel(LogManager.getLogger(
          NetworkTopology.class.getName()), logLevel);
  GenericTestUtils.setLogLevel(LogManager.getLogger(
          Groups.class.getName()), logLevel);
}
 
Example 36
Project: phone-simulator   File: TestAtiClientMan.java   View source code 5 votes vote down vote up
public boolean start() {
    this.countAtiReq = 0;
    this.countAtiResp = 0;

    MAPProvider mapProvider = this.mapMan.getMAPStack().getMAPProvider();
    mapProvider.getMAPServiceMobility().acivate();
    mapProvider.getMAPServiceMobility().addMAPServiceListener(this);
    mapProvider.addMAPDialogListener(this);
    this.testerHost.sendNotif(SOURCE_NAME, "ATI Client has been started", "", Level.INFO);
    isStarted = true;

    return true;
}
 
Example 37
Project: crow   File: SimpleConsoleUnixIntegrationTest.java   View source code 5 votes vote down vote up
@Test
public void whenEchoConsoleThenHelloOnLogs() {
    jobDefinition.setCommand("echo","hello world");
    jobDefinition.setJobName("echoJob");
    simpleConsole = new JobExecutor(jobDefinition, null, Stream.of(new JobLogLogger("echoJob")).collect(Collectors.toList()));
    simpleConsole.run();
    verify(appender).doAppend(logCaptor.capture());
    assertEquals("Log output must be info level!",logCaptor.getValue().getLevel(), Level.INFO);
    assertEquals("Message must match echo directive message!","hello world",logCaptor.getValue().getMessage());
}
 
Example 38
Project: unitimes   File: AbstractSolverServer.java   View source code 5 votes vote down vote up
@Override
public void setLoggingLevel(String name, Integer level) {
	sLog.info("Set logging level for " + (name == null ? "root" : name) + " to " + (level == null ? "null" : Level.toLevel(level)));
	Logger logger = (name == null ? Logger.getRootLogger() : Logger.getLogger(name));
	if (level == null)
		logger.setLevel(null);
	else
		logger.setLevel(Level.toLevel(level));
}
 
Example 39
Project: CloudDB   File: app_KVEcs.java   View source code 5 votes vote down vote up
private String setLevel(String levelString) {
	
	if(levelString.equals(Level.ALL.toString())) {
		logger.setLevel(Level.ALL);
		return Level.ALL.toString();
	} else if(levelString.equals(Level.DEBUG.toString())) {
		logger.setLevel(Level.DEBUG);
		return Level.DEBUG.toString();
	} else if(levelString.equals(Level.INFO.toString())) {
		logger.setLevel(Level.INFO);
		return Level.INFO.toString();
	} else if(levelString.equals(Level.WARN.toString())) {
		logger.setLevel(Level.WARN);
		return Level.WARN.toString();
	} else if(levelString.equals(Level.ERROR.toString())) {
		logger.setLevel(Level.ERROR);
		return Level.ERROR.toString();
	} else if(levelString.equals(Level.FATAL.toString())) {
		logger.setLevel(Level.FATAL);
		return Level.FATAL.toString();
	} else if(levelString.equals(Level.OFF.toString())) {
		logger.setLevel(Level.OFF);
		return Level.OFF.toString();
	} else {
		return LogSetup.UNKNOWN_LEVEL;
	}
}
 
Example 40
Project: tap17-muggl-javaee   File: SimplexSolverTest.java   View source code 5 votes vote down vote up
public void randomTest() throws IncorrectSolverException, TimeoutException, SolverUnableToDecideException, IncompleteSolutionException{
ExampleProblems example = new ExampleProblems();
int count = 30;
//int length = 12;
int length = 12;

console.setLevel(Level.DEBUG);
//Solver oldSimplex = SimplexSolverCL.newInstance(null);
Solver oldSimplex = SimplexSolver.newInstance(null);

SingleConstraintSet set = new SingleConstraintSet();

for (int i = 0; i < count; ++i){
    set.add( (SingleConstraint) example.toComposedConstraint( example.getRandomDoubleCoeffDoubleVarLinearConstraint(length) ));
}

SingleConstraintSet verifyingSet = new SingleConstraintSet();

for (int i = 0; i < count; ++i){
    oldSimplex.addConstraint( set.getConstraint(i) );
    verifyingSet.add( set.getConstraint(i));
    Solution solution = oldSimplex.getSolution();
    console.info(solution);
    if (solution == Solution.NOSOLUTION) 
	console.info("Constraint " + i + " returned NO_SOLUTION.");
    else 
	console.info( "Constraint " + i + " " + verifyingSet.validateSolution( solution ) );
}
   }