Java Code Examples for org.apache.log4j.PatternLayout

The following are top voted examples for showing how to use org.apache.log4j.PatternLayout. 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: vntscraper   File: VntMain.java   Source Code and License 7 votes vote down vote up
private static void initLogger() {
	Logger rootLogger = Logger.getRootLogger();
	PatternLayout layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n");

	try {
		RollingFileAppender fileAppender = new RollingFileAppender(layout, System.getProperty("log.file", "./vnt.log"));
		fileAppender.setImmediateFlush(true);
		fileAppender.setThreshold(Level.DEBUG);
		fileAppender.setAppend(true);
		fileAppender.setMaxFileSize("5MB");
		fileAppender.setMaxBackupIndex(2);

		rootLogger.addAppender(fileAppender);
	} catch (IOException e) {
		log.error("Failed to add appender !!", e);
	}
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: Log4JMetricsFileWriter.java   Source Code and License 6 votes vote down vote up
private RollingFileAppender initLogger(String loggerName, String filePrefix) {
  String fileName = Paths.get(rootPath, filePrefix + "." + loggerName + ".dat").toString();
  RollingFileAppender fileAppender = new RollingFileAppender();
  fileAppender.setName(loggerName);
  fileAppender.setFile(fileName);
  fileAppender.setLayout(new PatternLayout("%m%n"));
  fileAppender.setAppend(true);
  fileAppender.setMaxFileSize(maxFileSize);
  fileAppender.setMaxBackupIndex(maxFileCount);
  fileAppender.activateOptions();
  return fileAppender;
}
 
Example 3
Project: SPLGroundControl   File: SPLGroungControlTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    //Configure log4j
    ConsoleAppender console = new ConsoleAppender(); 
    String PATTERN = "%d [%p|%c|%C{1}] %m%n";
    console.setLayout(new PatternLayout(PATTERN)); 
    console.setThreshold(Level.DEBUG);
    console.activateOptions();

    Logger.getRootLogger().addAppender(console);

    System.out.println("SETUP: Starting SPLGroundControl...");
    config.init(args);

    daemon.init(new SPLGroundControl.SPLDaemonContext(args));
    daemon.start();
}
 
Example 4
Project: endpoint-health   File: EndPointHealthServiceImpl.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 5
Project: ats-framework   File: AgentConfigurationServiceImpl.java   Source Code and License 6 votes vote down vote up
private void attachPassiveDbAppender(
                                      DbAppenderConfiguration appenderConfiguration,
                                      long timestamp ) {

    // create the new appender
    PassiveDbAppender attachedAppender = new PassiveDbAppender(ThreadsPerCaller.getCaller());

    // calculate the time stamp offset, between the test executor and the agent
    attachedAppender.calculateTimeOffset(timestamp);

    attachedAppender.setAppenderConfig(appenderConfiguration);
    // use a default pattern, as we log in the db
    attachedAppender.setLayout(new PatternLayout("%c{2}: %m%n"));
    attachedAppender.activateOptions();

    // attach the appender to the logging system
    Category log = Logger.getRootLogger();

    log.setLevel(Level.toLevel(appenderConfiguration.getLoggingThreshold().toInt()));
    log.addAppender(attachedAppender);

}
 
Example 6
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
public void testAsciiMessageFromEventDefaultLayout() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "test";

    LoggingEvent event = createLoggingEvent(timestamp, text, null);
    LogMessage message = new LogMessage(event, new PatternLayout());

    // the default pattern appends a newline
    String expectedText = text + "\n";

    assertEquals("timestmap",               timestamp,                      message.getTimestamp());
    assertEquals("message",                 expectedText,                   message.getMessage());
    assertArrayEquals("message as bytes",   expectedText.getBytes("UTF-8"), message.getBytes());
    assertEquals("size",                    5,                              message.size());
}
 
Example 7
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
public void testUnicodeMessageFromEventDefaultLayout() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "\u0024\u00a2\u20ac";

    LoggingEvent event = createLoggingEvent(timestamp, text, null);
    LogMessage message = new LogMessage(event, new PatternLayout());

    // the default pattern appends a newline
    String expectedText = text + "\n";

    assertEquals("timestmap",               timestamp,                      message.getTimestamp());
    assertEquals("message",                 expectedText,                   message.getMessage());
    assertArrayEquals("message as bytes",   expectedText.getBytes("UTF-8"), message.getBytes());
    assertEquals("size",                    7,                              message.size());
}
 
Example 8
Project: log4j-aws-appenders   File: TestLogMessage.java   Source Code and License 6 votes vote down vote up
@Test
// at this point we'll assume that UTF-8 conversion works as expected
public void testAsciiMessageFromEventDefaultLayoutWithException() throws Exception
{
    final long timestamp = System.currentTimeMillis();
    final String text = "test";
    final Exception ex = new Exception();

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.println(text);
    ex.printStackTrace(pw);
    pw.close();
    String expectedText = sw.toString();

    LoggingEvent event = createLoggingEvent(timestamp, text, ex);
    LogMessage message = new LogMessage(event, new PatternLayout());

    assertEquals("explicit timestamp",  timestamp,      message.getTimestamp());
    assertEquals("message as string",   expectedText,   message.getMessage());
}
 
Example 9
Project: LightSIP   File: DeadSocketTlsTest.java   Source Code and License 6 votes vote down vote up
public void setUp() {

		Logger root = Logger.getRootLogger();
		root.setLevel(Level.DEBUG);
		root.addAppender(new ConsoleAppender(
				new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
		// setup TLS properties
		System.setProperty( "javax.net.ssl.keyStore",  TlsTest.class.getResource("testkeys").getPath() );
		System.setProperty( "javax.net.ssl.trustStore", TlsTest.class.getResource("testkeys").getPath() );
		System.setProperty( "javax.net.ssl.keyStorePassword", "passphrase" );
		System.setProperty( "javax.net.ssl.keyStoreType", "jks" );
		this.shootist = new BadShootist();
		this.shootme = new BadShootme();
		shootist.setSocketDisconnectWorstCase(true);
		shootme.setSocketDisconnectWorstCase(true);
		this.shootme.init();
	}
 
Example 10
Project: marklogic-monitoring-extension   File: MarkLogicMonitor.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws TaskExecutionException {

        ConsoleAppender ca = new ConsoleAppender();
        ca.setWriter(new OutputStreamWriter(System.out));
        ca.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
        ca.setThreshold(Level.TRACE);

        logger.getRootLogger().addAppender(ca);

        final MarkLogicMonitor monitor = new MarkLogicMonitor();

        final Map<String, String> taskArgs = new HashMap<String, String>();
        taskArgs.put("config-file", "src/main/resources/conf/config.yml");
        taskArgs.put("metrics-file", "src/main/resources/conf/metrics.xml");
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                try {
                    monitor.execute(taskArgs, null);
                } catch (Exception e) {
                    logger.error("Error while running the task", e);
                }
            }
        }, 2, 30, TimeUnit.SECONDS);
    }
 
Example 11
Project: ibench   File: iBenchDriver.java   Source Code and License 6 votes vote down vote up
private static void setUpExperimentalLogger(File pathF) throws IOException {
	
	Logger.getRootLogger().removeAllAppenders();
	log.removeAllAppenders();
	
	PropertyConfigurator.configure("resource/log4jproperties.txt");
	
	FileAppender resultAppender = new FileAppender(
			new PatternLayout("%m"),
			new File(pathF, "result.txt").toString(), false);
	
	LevelRangeFilter infoFilter = new LevelRangeFilter();
	infoFilter.setLevelMin(Level.INFO);
	infoFilter.setLevelMax(Level.FATAL);
	infoFilter.setAcceptOnMatch(true);
	resultAppender.addFilter(infoFilter);
	log.addAppender(resultAppender);
	Logger.getLogger(iBench.class).addAppender(resultAppender);
	
}
 
Example 12
Project: ibench   File: iBenchDriver.java   Source Code and License 6 votes vote down vote up
private static void setUpConfigLogger(File pathF, String configName) throws IOException {
	Logger.getRootLogger().removeAllAppenders();
	
	String nameSuffix = configName.replace(".txt", "");
	
	PropertyConfigurator.configure("resource/log4jproperties.txt");	
	
	FileAppender logFileAppender = new FileAppender(
			new PatternLayout("%-4r [%t] %-5p %c %x - %m%n"),
			new File(pathF, "log_" + nameSuffix + ".txt").toString(), false);
	Logger.getRootLogger().addAppender(logFileAppender);
	
	if (opt.logToConsole)
		Logger.getRootLogger().addAppender(new ConsoleAppender(
				new PatternLayout("%-4r [%t] %-5p %c %x - %m%n")));
}
 
Example 13
Project: traccar-service   File: Log.java   Source Code and License 6 votes vote down vote up
public static void setupLogger(Config config) throws IOException {

        Layout layout = new PatternLayout("%d{" + DATE_FORMAT + "} %5p: %m%n");

        Appender appender = new DailyRollingFileAppender(
                layout, config.getString("logger.file"), "'.'yyyyMMdd");

        LogManager.resetConfiguration();
        LogManager.getRootLogger().addAppender(new NullAppender());

        logger = Logger.getLogger(LOGGER_NAME);
        logger.addAppender(appender);
        logger.setLevel(Level.toLevel(config.getString("logger.level"), Level.ALL));

        // Workaround for "Bug 745866 - (EDG-45) Possible netty logging config problem"
        InternalLoggerFactory.setDefaultFactory(new InternalLoggerFactory() {
            @Override
            public InternalLogger newInstance(String string) {
                return new NettyInternalLogger();
            }
        });

        Log.logSystemInfo();
        Log.info("Version: " + getAppVersion());
    }
 
Example 14
Project: Log4Reports   File: LogUtil.java   Source Code and License 6 votes vote down vote up
public LogUtil(LogConfig config, Object obj){
	this.logConfig = config;
	if(LogConfig.logType == 0){
		report = new ExtentReports(config.getExtentLogPath(),false);
		File configFile = new File(System.getProperty("user.dir") + "\\configs\\extent-config.xml");
		if(configFile.exists()) {
			report.loadConfig(configFile);		
		}		
		testLog = report.startTest(String.valueOf(obj));
	}else{
		logger = Logger.getLogger(String.valueOf(obj));
		Layout layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} [%p] %c:%L �� %m%n");  
		try {
			Appender appender = new FileAppender(layout, config.getLog4jPath());
			logger.addAppender(appender);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
 
Example 15
Project: hadoop   File: TestContainerLogAppender.java   Source Code and License 6 votes vote down vote up
@Test
public void testAppendInClose() throws Exception {
  final ContainerLogAppender claAppender = new ContainerLogAppender();
  claAppender.setName("testCLA");
  claAppender.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
  claAppender.setContainerLogDir("target/testAppendInClose/logDir");
  claAppender.setContainerLogFile("syslog");
  claAppender.setTotalLogFileSize(1000);
  claAppender.activateOptions();
  final Logger claLog = Logger.getLogger("testAppendInClose-catergory");
  claLog.setAdditivity(false);
  claLog.addAppender(claAppender);
  claLog.info(new Object() {
    public String toString() {
      claLog.info("message1");
      return "return message1";
    }
  });
  claAppender.close();
}
 
Example 16
Project: hadoop   File: TestAuditLogs.java   Source Code and License 6 votes vote down vote up
private void configureAuditLogs() throws IOException {
  // Shutdown the LogManager to release all logger open file handles.
  // Unfortunately, Apache commons logging library does not provide
  // means to release underlying loggers. For additional info look up
  // commons library FAQ.
  LogManager.shutdown();

  File file = new File(auditLogFile);
  if (file.exists()) {
    assertTrue(file.delete());
  }
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  // disable logging while the cluster startup preps files
  logger.setLevel(Level.OFF);
  PatternLayout layout = new PatternLayout("%m%n");
  RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile);
  logger.addAppender(appender);
}
 
Example 17
Project: Jerkoff   File: LogUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @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;
}
 
Example 18
Project: MLE5109-Course-samples   File: StressTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout("%d{MM-dd HH:mm:ss,SSS} [%t] %5p: %m%n")));
    Logger.getRootLogger().setLevel(Level.DEBUG);

    final RecoveryMessage recoveryMessage = new RecoveryMessage("GROUP1~1~ADD~data1");
    final RecoveryMessage recoveryMessage2 = new RecoveryMessage("GROUP1~1~ADD~data1");

    Service service = new Service(Arrays.asList("GROUP1", "GROUP2"), 10);
    service.process(recoveryMessage);

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(() -> {
        IntStream.rangeClosed(0, 5000)
                .mapToObj(count -> new RecoveryMessage("GROUP1~" + count + "~ADD~data2"))
                .forEach(service::process);
        Logger.getRootLogger().info("Recovery done");
    });

    service.process(recoveryMessage2);
    service.start();

    executorService.shutdown();
    Utils.simulateWork(TimeUnit.SECONDS.toMillis(2));
}
 
Example 19
Project: aliyun-oss-hadoop-fs   File: TestContainerLogAppender.java   Source Code and License 6 votes vote down vote up
@Test
public void testAppendInClose() throws Exception {
  final ContainerLogAppender claAppender = new ContainerLogAppender();
  claAppender.setName("testCLA");
  claAppender.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
  claAppender.setContainerLogDir("target/testAppendInClose/logDir");
  claAppender.setContainerLogFile("syslog");
  claAppender.setTotalLogFileSize(1000);
  claAppender.activateOptions();
  final Logger claLog = Logger.getLogger("testAppendInClose-catergory");
  claLog.setAdditivity(false);
  claLog.addAppender(claAppender);
  claLog.info(new Object() {
    public String toString() {
      claLog.info("message1");
      return "return message1";
    }
  });
  claAppender.close();
}
 
Example 20
Project: aliyun-oss-hadoop-fs   File: TestAuditLogs.java   Source Code and License 6 votes vote down vote up
private void configureAuditLogs() throws IOException {
  // Shutdown the LogManager to release all logger open file handles.
  // Unfortunately, Apache commons logging library does not provide
  // means to release underlying loggers. For additional info look up
  // commons library FAQ.
  LogManager.shutdown();

  File file = new File(auditLogFile);
  if (file.exists()) {
    assertTrue(file.delete());
  }
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  // disable logging while the cluster startup preps files
  logger.setLevel(Level.OFF);
  PatternLayout layout = new PatternLayout("%m%n");
  RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile);
  logger.addAppender(appender);
}
 
Example 21
Project: wring   File: Exec.java   Source Code and License 6 votes vote down vote up
/**
 * Push and collect logs.
 * @return Logs
 * @throws IOException If fails
 */
private String log() throws IOException {
    final org.apache.log4j.Logger root =
        org.apache.log4j.Logger.getRootLogger();
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Appender appender = new ThreadAppender(
        new PatternLayout("%t %p %m\n"),
        baos
    );
    root.addAppender(appender);
    try {
        this.pipe.status(this.agent.push(this.events));
        return baos.toString();
    } finally {
        root.removeAppender(appender);
    }
}
 
Example 22
Project: DBTestCompare   File: Printer.java   Source Code and License 6 votes vote down vote up
public static void init(CmpSqlResultsConfig cmpSqlResultsConfig) {
    log.debug("Initializing logger / printer ...");
    ConsoleAppender consoleAppender = (ConsoleAppender) Logger.getRootLogger().getAppender("stdout");
    if (cmpSqlResultsConfig.getLogger() != null && cmpSqlResultsConfig.getLogger().getLogLevel() !=
            null && !cmpSqlResultsConfig.getLogger().getLogLevel().isEmpty()) {
        Logger.getRootLogger().setLevel(Level.toLevel(cmpSqlResultsConfig.getLogger().getLogLevel()));
    }
    if (cmpSqlResultsConfig.getLogger().isTeamcityLogsEnabled()) {
        consoleAppender.setLayout(new PatternLayout("%m%n"));
    }
    consoleAppender.addFilter(new Filter() {
        @Override
        public int decide(LoggingEvent loggingEvent) {
            if(loggingEvent.getMessage() instanceof String == false) return ACCEPT;
            boolean isTCMsg = ((String) loggingEvent.getMessage()).contains(TCMessages.TC);
            // before threads (and buffering messages for TC) we allowed "common" logs
            // boolean isNotTCMsg = ((String) loggingEvent.getMessage()).contains(TCMessages.NOT_TC);
            if (cmpSqlResultsConfig.getLogger().isTeamcityLogsEnabled()) {
                return isTCMsg ? ACCEPT : DENY;
                // return isNotTCMsg ? DENY : ACCEPT;
            } else {
                return isTCMsg ? DENY : ACCEPT;
            }
        }
    });
}
 
Example 23
Project: SeedboxSync   File: SeedboxSync.java   Source Code and License 6 votes vote down vote up
/**
 * Configures the logger.
 */
private static void configureLogging() {
    PatternLayout layout = new PatternLayout("%d{yyyy-MM-dd' 'HH:mm:ss.SSS} [%-5p] [%c] - %m%n");

    ConsoleAppender console = new ConsoleAppender();
    console.setLayout(layout);
    console.setThreshold(Level.INFO);
    console.activateOptions();

    DailyRollingFileAppender file = new DailyRollingFileAppender();
    file.setFile("log/app.log");
    file.setDatePattern("'.'yyyy-MM-dd");
    file.setLayout(layout);
    file.activateOptions();

    org.apache.log4j.Logger logger = org.apache.log4j.Logger.getRootLogger();
    logger.addAppender(console);
    logger.addAppender(file);
}
 
Example 24
Project: big-c   File: TestContainerLogAppender.java   Source Code and License 6 votes vote down vote up
@Test
public void testAppendInClose() throws Exception {
  final ContainerLogAppender claAppender = new ContainerLogAppender();
  claAppender.setName("testCLA");
  claAppender.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
  claAppender.setContainerLogDir("target/testAppendInClose/logDir");
  claAppender.setContainerLogFile("syslog");
  claAppender.setTotalLogFileSize(1000);
  claAppender.activateOptions();
  final Logger claLog = Logger.getLogger("testAppendInClose-catergory");
  claLog.setAdditivity(false);
  claLog.addAppender(claAppender);
  claLog.info(new Object() {
    public String toString() {
      claLog.info("message1");
      return "return message1";
    }
  });
  claAppender.close();
}
 
Example 25
Project: big-c   File: TestAuditLogs.java   Source Code and License 6 votes vote down vote up
private void configureAuditLogs() throws IOException {
  // Shutdown the LogManager to release all logger open file handles.
  // Unfortunately, Apache commons logging library does not provide
  // means to release underlying loggers. For additional info look up
  // commons library FAQ.
  LogManager.shutdown();

  File file = new File(auditLogFile);
  if (file.exists()) {
    assertTrue(file.delete());
  }
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  // disable logging while the cluster startup preps files
  logger.setLevel(Level.OFF);
  PatternLayout layout = new PatternLayout("%m%n");
  RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile);
  logger.addAppender(appender);
}
 
Example 26
Project: erp   File: FreedomLogger.java   Source Code and License 6 votes vote down vote up
public static Logger getLogger(final Class<?> cl, final String initFile, final String property) {

		Properties properties;
		Logger c = null;
		try {
			ManagerIni mi = initFile != null ? ManagerIni.createManagerIniFile(initFile) : ManagerIni.createManagerIniParameter();
			properties = mi.getSession("FreedomLogger");
			c = Logger.getLogger(cl.getCanonicalName(), myFactory);
			Layout layout = new PatternLayout(LAYOUT_DEFAULT);
			c.addAppender(new FileAppender(layout, properties.get(property).toString(), true));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
 
Example 27
Project: Vitruv   File: TestUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes console logger for tests. Sets the logger level to
 * {@link Level#ERROR} by default. If the VM property <i>logOutputLevel</i>
 * is specified, it is used to determine the logger level.
 */
public static void initializeLogger() {
	Logger.getRootLogger().setLevel(Level.ERROR);
	Logger.getRootLogger().removeAllAppenders();
	Logger.getRootLogger()
			.addAppender(new ConsoleAppender(new PatternLayout("[%-5p] %d{HH:mm:ss,SSS} %-30C{1} - %m%n")));
	String outputLevelProperty = System.getProperty(VM_ARGUMENT_LOG_OUTPUT_LEVEL);
	if (outputLevelProperty != null) {
		if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
			Logger.getRootLogger().addAppender(new ConsoleAppender());
		}
		Logger.getRootLogger().setLevel(Level.toLevel(outputLevelProperty));
	} else {
		Logger.getRootLogger().setLevel(Level.ERROR);
	}
}
 
Example 28
Project: bktail2   File: LogfileHandlerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	try {
		Files.delete(Paths.get(FILEPATH));
	} catch (Exception e) {
		// TODO: handle exception
	}
	
	FileAppender fa = new FileAppender();
	fa.setName("FileLogger");
	fa.setFile(FILEPATH);
	fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
	fa.setThreshold(Level.DEBUG);
	fa.setAppend(true);
	fa.activateOptions();

	//add appender to any Logger (here is root)
	Logger.getRootLogger().addAppender(fa);
}
 
Example 29
Project: flowable-engine   File: MDCLoggingTest.java   Source Code and License 6 votes vote down vote up
private void setCustomLogger() {
    String PATTERN = "Modified Log *** ProcessDefinitionId=%X{mdcProcessDefinitionID} executionId=%X{mdcExecutionId} mdcProcessInstanceID=%X{mdcProcessInstanceID} mdcBusinessKey=%X{mdcBusinessKey} mdcTaskId=%X{mdcTaskId}  %m%n";
    console.setLayout(new PatternLayout(PATTERN));
    console.setThreshold(Level.DEBUG);
    console.activateOptions();
    console.setName("MemoryAppender");

    appenders = new ArrayList<Appender>();
    Enumeration<?> appendersEnum = Logger.getRootLogger().getAllAppenders();

    while (appendersEnum.hasMoreElements()) {
        Appender object = (Appender) appendersEnum.nextElement();
        appenders.add(object);
    }

    removeAppenders();

    Logger.getRootLogger().addAppender(console);
}
 
Example 30
Project: flowable-engine   File: MDCLoggingTest.java   Source Code and License 6 votes vote down vote up
private void setCustomLogger() {
    String PATTERN = "Modified Log *** ProcessDefinitionId=%X{mdcProcessDefinitionID} executionId=%X{mdcExecutionId} mdcProcessInstanceID=%X{mdcProcessInstanceID} mdcBusinessKey=%X{mdcBusinessKey} mdcTaskId=%X{mdcTaskId}  %m%n";
    console.setLayout(new PatternLayout(PATTERN));
    console.setThreshold(Level.DEBUG);
    console.activateOptions();
    console.setName("MemoryAppender");

    appenders = new ArrayList<>();
    Enumeration<?> appendersEnum = Logger.getRootLogger().getAllAppenders();

    while (appendersEnum.hasMoreElements()) {
        Appender object = (Appender) appendersEnum.nextElement();
        appenders.add(object);
    }

    removeAppenders();

    Logger.getRootLogger().addAppender(console);

    LogMDC.setMDCEnabled(true);
}
 
Example 31
Project: caom2   File: Util.java   Source Code and License 6 votes vote down vote up
/**
* Initializes logging to a file.
* @param loggerNames the names of the loggers (usually names of packages
* or classes or ancestors of packages or classes). Can't be null.
* @param argMap command line arguments.
*/
public static synchronized void initFileLogging(String[] loggerNames, ArgumentMap argMap, String filename)
    throws IOException
{
    Level level = DEFAULT_FILE_LOGGING_LEVEL;
    if (argMap.isSet(Argument.LOG_QUIET_SHORT) || argMap.isSet(Argument.LOG_QUIET)) level = Level.ERROR;
    if (argMap.isSet(Argument.LOG_VERBOSE_SHORT) || argMap.isSet(Argument.LOG_VERBOSE)) level = Level.INFO;
    if (argMap.isSet(Argument.LOG_DEBUG_SHORT) || argMap.isSet(Argument.DEBUG)) level = Level.DEBUG;

    FileAppender fileAppender = new FileAppender(new PatternLayout(), filename);

    boolean append = true;
    Writer fileWriter = new FileWriter(filename, append);
    for (String loggerName : loggerNames)
        Log4jInit.setLevel(loggerName, level, fileWriter);
}
 
Example 32
Project: charles-rest   File: Action.java   Source Code and License 6 votes vote down vote up
/**
 * Setup the Log4J logger for this action thread.
 * @return String path to log file
 * @throws IOException If there's something wrong with the FileAppender.
 */
private void setupLog4jForAction() throws IOException {
    String loggerName = "Action_" + this.id;
    org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger("Action_" + this.id);
    String logRoot = System.getProperty("LOG_ROOT");
    if(logRoot == null) {
        logRoot = ".";
    }
    String logFilePath = logRoot + "/charles-rest/ActionsLogs/" + this.id + ".log";
    
    File logFile = new File(logFilePath);
    logFile.getParentFile().mkdirs();
    logFile.createNewFile();//you have to create the file yourself since FileAppender acts funny under linux if the file doesn't already exist.

    FileAppender fa = new FileAppender(new PatternLayout("%d %p - %m%n"), logFilePath);
    fa.setName(this.id + "_appender");
    fa.setThreshold(Level.DEBUG);
    log4jLogger.addAppender(fa);
    log4jLogger.setLevel(Level.DEBUG);
    
    this.logger = LoggerFactory.getLogger(loggerName);
    
}
 
Example 33
Project: eagle   File: Logging.java   Source Code and License 6 votes vote down vote up
/**
 * Sets up audit logging to log to a file named based on the current time (in
 * ms).
 *
 * The logger is configured to effectively ignore the log level.
 *
 * @throws IOException
 *           if the audit log file could not be opened for writing.
 */
public static void configureAuditLogging() throws IOException {
  PatternLayout layout = new PatternLayout(AUDIT_LOG_FORMAT);
  // This assumes that no other daemon will be started within 1 millisecond.
  String filename = String.format(AUDIT_LOG_FILENAME_FORMAT,
      System.currentTimeMillis(), new Random().nextInt(Integer.MAX_VALUE));
  FileAppender fileAppender = new FileAppender(layout, filename);
  Logger auditLogger = Logger.getLogger(Logging.AUDIT_LOGGER_NAME);
  auditLogger.addAppender(fileAppender);
  auditLogger.setLevel(Level.ALL);
  /*
   * We don't want audit messages to be appended to the main appender, which
   * is intended for potentially user-facing messages.
   */
  auditLogger.setAdditivity(false);
}
 
Example 34
Project: CloudCryptoSearch   File: ClientConnectorBeanWIKIHom.java   Source Code and License 6 votes vote down vote up
public static void main (String[] args) {
		log.addAppender(new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %-5p [%c{1}] %m%n")));
		log.setLevel(Level.INFO);
		ClientConnectorLocal client = new ClientConnectorBeanWIKIHom();
		
		log.info("Setup done. Building index...");
//		client.addFirstDocuments("/home/bernardo/Desktop/enwiki-latest-pages-articles.xml");
//		client.addFirstDocuments("/home/bernardo/Desktop/ptwiki-20121027-pages-articles.xml");
//		client.addFirstDocuments("/home/bernardo/Desktop/eswiki-20121018-pages-articles.xml");
//		log.info("Index Finished!");
		client.rebuildIndex();
		log.info("Starting query...");
		query(client, "IETF payload optimize retransmit threshold RFC protocol  trusted network address");
//		query(client, "IETF payload optimize retransmit threshold");
//		query(client, "IETF payload");
		log.info("Query finished!");
	}
 
Example 35
Project: CloudCryptoSearch   File: PrototypeClientConnector.java   Source Code and License 6 votes vote down vote up
public static void main (String[] args) throws Exception{
		log.addAppender(new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %-5p [%c{1}] %m%n")));
		log.setLevel(Level.INFO);
		PrototypeClientConnector client = new PrototypeClientConnector();
		
		log.info("Setup done. Building index...");
		File f = new File("/Users/bernardo/Dropbox/WorkspacePHD/CryptoSearchCloud/docs");
		client.addFirstDocuments(f.listFiles());
		log.info("Index Finished!");
		client.rebuildIndex();
		log.info("Starting query...");
//		query(client, "IETF payload optimize retransmit threshold RFC protocol  trusted network address");
//		query(client, "IETF payload optimize retransmit threshold");
//		query(client, "IETF payload");
		query(client, "rTp");
		log.info("Query finished!");
	}
 
Example 36
Project: CloudCryptoSearch   File: ClientConnectorBeanWIKI.java   Source Code and License 6 votes vote down vote up
public static void main (String[] args) {
		log.addAppender(new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %-5p [%c{1}] %m%n")));
		log.setLevel(Level.INFO);
		ClientConnectorLocal client = new ClientConnectorBeanWIKI();
		
		log.info("Setup done. Building index...");
//		client.addFirstDocuments("/home/bernardo/Desktop/enwiki-latest-pages-articles.xml");
//		client.addFirstDocuments("/home/bernardo/Desktop/ptwiki-20121027-pages-articles.xml");
//		client.addFirstDocuments("/home/bernardo/Desktop/eswiki-20121018-pages-articles.xml");
//		log.info("Index Finished!");
		client.rebuildIndex();
		log.info("Starting query...");
		query(client, "IETF payload optimize retransmit threshold RFC protocol  trusted network address");
//		query(client, "IETF payload optimize retransmit threshold");
//		query(client, "IETF payload");
		log.info("Query finished!");
	}
 
Example 37
Project: mlo-net   File: OdenOSAdapterServiceImplTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSAdapterServiceImpl#notifyLinkDeleted(java.lang.String)}.
 */
@Test
public void testNotifyFlowDeleted_unmatch() {
    StringWriter writer = new StringWriter();
       WriterAppender appender = new WriterAppender(new PatternLayout("%p, %m%n"),writer);
       getLogger().addAppender(appender);
       getLogger().setAdditivity(false);
       try{
           // Outputs any log
   		try {
   			obj.setDeleteFlowQueue("test");
   			obj.notifyFlowDeleted("test2");
   		} catch (Exception e) {
   			fail();
   		}
           // Checks error log
           String logString = writer.toString();
           assertTrue(logString.contains("notifyFlowDeleted Incorrect response : " + "test2"));

       }finally{
           // Removes log appender
           getLogger().removeAppender(appender);
           getLogger().setAdditivity(true);
       }
}
 
Example 38
Project: hadoop-2.6.0-cdh5.4.3   File: TestAuditLogs.java   Source Code and License 6 votes vote down vote up
private void configureAuditLogs() throws IOException {
  // Shutdown the LogManager to release all logger open file handles.
  // Unfortunately, Apache commons logging library does not provide
  // means to release underlying loggers. For additional info look up
  // commons library FAQ.
  LogManager.shutdown();

  File file = new File(auditLogFile);
  if (file.exists()) {
    assertTrue(file.delete());
  }
  Logger logger = ((Log4JLogger) FSNamesystem.auditLog).getLogger();
  // disable logging while the cluster startup preps files
  logger.setLevel(Level.OFF);
  PatternLayout layout = new PatternLayout("%m%n");
  RollingFileAppender appender = new RollingFileAppender(layout, auditLogFile);
  logger.addAppender(appender);
}
 
Example 39
Project: VirtaMarketAnalyzer   File: ProductRecipeParser.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws IOException {
        BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n")));
//        final Document doc = Downloader.getDoc(Wizard.host + "olga/main/industry/unit_type/info/15751");
//        final Document doc = Downloader.getDoc(Wizard.host + "olga/main/industry/unit_type/info/422209");
//        final Document doc = Downloader.getDoc(Wizard.host + "olga/main/industry/unit_type/info/2425");
//        final Document doc = Downloader.getDoc(Wizard.host + "olga/main/industry/unit_type/info/2417");
        final String host = Wizard.host;
        final String realm = "olga";
        final String url = host + realm + "/main/industry/unit_type/info/";
        final List<Manufacture> manufactures = new ArrayList<>();
//        manufactures.add(new Manufacture("423140", "manufactureCategory", "caption"));
//        manufactures.add(new Manufacture("2425", "manufactureCategory", "caption"));
        manufactures.add(new Manufacture("2438", "manufactureCategory", "caption", new ArrayList<>()));

        final Map<String, List<ProductRecipe>> result = getProductRecipes(host, realm, manufactures);
        logger.info(Utils.getPrettyGson(result));
    }
 
Example 40
Project: VirtaMarketAnalyzer   File: ShopParser.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n")));
//        final String url = Wizard.host + "olga/main/unit/view/5788675";
        final String host = Wizard.host;
//        final String realm = "mary";
//        final String url = host + realm + "/main/unit/view/3943258";
        final String realm = "olga";
        final String url = host + realm + "/main/unit/view/6519771";
//        Downloader.invalidateCache(url);
        final List<City> cities = new ArrayList<>();
        cities.add(new City("422653", "422655", "422682", "Вашингтон", 0.0, 0.0, 0.0, 0,0, null));
        final List<Product> products = new ArrayList<>();
        products.add(ProductInitParser.getTradingProduct(host, realm, "422547"));
        products.add(ProductInitParser.getTradingProduct(host, realm, "3838"));
        final Map<String, List<Product>> productsByImgSrc = products.stream().collect(Collectors.groupingBy(Product::getImgUrl));
        System.out.println(Utils.getPrettyGson(parse(realm, url, cities, productsByImgSrc, "Вашингтон")));
    }