org.apache.log4j.PatternLayout Java Examples

The following examples show how to use org.apache.log4j.PatternLayout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jforgame   Author: kingston-csj   File: LoggerBuilder.java    License: Apache License 2.0 7 votes vote down vote up
private static Logger build(String name) {
    Logger logger = Logger.getLogger(name);
    logger.removeAllAppenders();
    logger.setLevel(Level.INFO);
    logger.setAdditivity(false);

    RollingFileAppender appender = new RollingFileAppender();
    PatternLayout layout = new PatternLayout();
    String conversionPatten = "[%d] %p %t %c - %m%n";
    layout.setConversionPattern(conversionPatten);
    appender.setLayout(layout);
    appender.setEncoding("utf-8");
    appender.setAppend(true);

    TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
    String fp = LoggerBuilder.LOG_PATH + name + "/" + name + ".log.%d{yyyy-MM-dd}";
    policy.setFileNamePattern(fp);
    appender.setRollingPolicy(policy);

    appender.activateOptions();
    logger.addAppender(appender);

    container.put(name,logger);
    return logger;
}
 
Example #2
Source Project: ats-framework   Author: Axway   File: AgentConfigurationServiceImpl.java    License: Apache License 2.0 7 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 #3
Source Project: incubator-sentry   Author: apache   File: TestRollingFileWithoutDeleteAppender.java    License: Apache License 2.0 6 votes vote down vote up
/***
 * Generate log enough to cause a single rollover. Verify the file name format
 * @throws Throwable
 */
@Test
public void testFileNamePattern() throws Throwable {
  if (dataDir == null) {
    fail("Excepted temp folder for audit log is created.");
  }
  RollingFileWithoutDeleteAppender appender = new RollingFileWithoutDeleteAppender(
      new PatternLayout("%m%n"), dataDir.getPath() + "/auditLog.log");
  appender.setMaximumFileSize(10);
  sentryLogger.addAppender(appender);
  sentryLogger.debug("123456789012345");
  File[] files = dataDir.listFiles();
  if (files != null) {
    assertEquals(files.length, 2);
    assertTrue(files[0].getName().contains("auditLog.log."));
    assertTrue(files[1].getName().contains("auditLog.log."));
  } else {
    fail("Excepted 2 log files.");
  }
}
 
Example #4
Source Project: uyuni   Author: uyuni-project   File: RhnJavaJob.java    License: GNU General Public License v2.0 6 votes vote down vote up
void enableLogging(TaskoRun run) {
    PatternLayout pattern = new PatternLayout(DEFAULT_LOGGING_LAYOUT);
    try {
        getLogger().removeAllAppenders();
        FileAppender outLogAppender = new FileAppender(pattern,
                run.buildStdOutputLogPath());
        outLogAppender.setThreshold(Level.INFO);
        getLogger().addAppender(outLogAppender);
        FileAppender errLogAppender = new FileAppender(pattern,
                run.buildStdErrorLogPath());
        errLogAppender.setThreshold(Level.ERROR);
        getLogger().addAppender(errLogAppender);
    }
    catch (IOException e) {
        getLogger().warn("Logging to file disabled");
        e.printStackTrace();
    }
}
 
Example #5
Source Project: celos   Author: collectivemedia   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static void setupLogging(File logDir) {
    System.getProperties().setProperty("log4j.defaultInitOverride", "true");

    RollingFileAppender appender = new RollingFileAppender();
    appender.setFile(new File(logDir, "celos.log").getAbsolutePath());
    appender.setAppend(true);

    TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
    rollingPolicy.setFileNamePattern(new File(logDir, "celos-%d{yyyy-MM-dd}.log").getAbsolutePath());
    appender.setRollingPolicy(rollingPolicy);

    PatternLayout patternLayout = new PatternLayout();
    patternLayout.setConversionPattern("[%d{YYYY-MM-dd HH:mm:ss.SSS}] %-5p: %m%n");
    appender.setLayout(patternLayout);

    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);
    Logger.getRootLogger().setLevel(Level.INFO);
}
 
Example #6
Source Project: samza   Author: apache   File: TestStreamAppender.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemProducerAppenderInAM() throws InterruptedException {
  System.setProperty("samza.container.name", "samza-job-coordinator");

  MockSystemProducerAppender systemProducerAppender = new MockSystemProducerAppender();
  PatternLayout layout = new PatternLayout();
  layout.setConversionPattern("%m");
  systemProducerAppender.setLayout(layout);
  systemProducerAppender.activateOptions();
  log.addAppender(systemProducerAppender);

  log.info("no-received"); // System isn't initialized yet, so this message should be dropped

  systemProducerAppender.setupSystem();
  MockSystemProducerAppender.systemInitialized = true;

  List<String> messages = Lists.newArrayList("testing3", "testing4");
  logAndVerifyMessages(messages);
}
 
Example #7
Source Project: render   Author: saalfeldlab   File: LogUtilities.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void setupExecutorLog4j(final String context,
                                      final String rootLoggerName) {

    final Logger logger = LogManager.getLogger(rootLoggerName);

    for (final Enumeration e = LogManager.getRootLogger().getAllAppenders(); e.hasMoreElements(); ) {
        final Appender a = (Appender) e.nextElement();
        if (a instanceof ConsoleAppender) {
            final Layout layout = a.getLayout();
            if (layout instanceof PatternLayout) {
                final PatternLayout patternLayout = (PatternLayout) layout;
                final String conversionPattern = "%d{ISO8601} [%t] [%X{context}] %-5p [%c] %m%n";
                if (! conversionPattern.equals(patternLayout.getConversionPattern())) {
                    a.setLayout(new PatternLayout(conversionPattern));
                }
            }
        }
    }

    MDC.put("context", context);

    logger.setLevel(Level.DEBUG);
}
 
Example #8
Source Project: incubator-atlas   Author: apache   File: FailedMessagesLogger.java    License: Apache License 2.0 6 votes vote down vote up
void init() {
    String rootLoggerDirectory = getRootLoggerDirectory();
    if (rootLoggerDirectory == null) {
        return;
    }
    String absolutePath = new File(rootLoggerDirectory, failedMessageFile).getAbsolutePath();
    try {
        DailyRollingFileAppender failedLogFilesAppender = new DailyRollingFileAppender(
                new PatternLayout(PATTERN_SPEC_TIMESTAMP_MESSAGE_NEWLINE), absolutePath, DATE_PATTERN);
        logger.addAppender(failedLogFilesAppender);
        logger.setLevel(Level.ERROR);
        logger.setAdditivity(false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #9
Source Project: tasmo   Author: jivesoftware   File: ModePathPrefixMerging.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
    public void logger() {
        String PATTERN = "%t %m%n";

        Enumeration allAppenders = LogManager.getRootLogger().getAllAppenders();
        while (allAppenders.hasMoreElements()) {
            Appender appender = (Appender) allAppenders.nextElement();
            appender.setLayout(new PatternLayout(PATTERN));
        }
        //if (verbose) {
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib").setLevel(Level.TRACE);
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib.TasmoViewModel").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.lib.concur.ConcurrencyAndExistanceCommitChange").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.reference.lib.ReferenceStore").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.view.reader.service.writer.WriteToViewValueStore").setLevel(Level.TRACE);
//        } else {
//            LogManager.getRootLogger().setLevel(Level.OFF);
//        }
    }
 
Example #10
Source Project: activiti6-boot2   Author: dingziyang   File: MDCLoggingTest.java    License: Apache License 2.0 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);
  
  LogMDC.setMDCEnabled(true);
}
 
Example #11
Source Project: yb-sample-apps   Author: yugabyte   File: LogUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void configureLogLevel(boolean verbose) {
  // First remove all appenders.
  Logger.getLogger("com.yugabyte.sample").removeAppender("YBConsoleLogger");
  Logger.getRootLogger().removeAppender("YBConsoleLogger");;

  // Create the console appender.
  ConsoleAppender console = new ConsoleAppender();
  console.setName("YBConsoleLogger");
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN));
  console.setThreshold(verbose ? Level.DEBUG : Level.INFO);
  console.activateOptions();

  // Set the desired logging level.
  if (verbose) {
    // If verbose, make everything DEBUG log level and output to console.
    Logger.getRootLogger().addAppender(console);
    Logger.getRootLogger().setLevel(Level.DEBUG);
  } else {
    // If not verbose, allow YB sample app and driver INFO logs go to console.
    Logger.getLogger("com.yugabyte.sample").addAppender(console);
    Logger.getLogger("com.yugabyte.driver").addAppender(console);
    Logger.getLogger("com.datastax.driver").addAppender(console);
    Logger.getRootLogger().setLevel(Level.WARN);
  }
}
 
Example #12
Source Project: olat   Author: huihoo   File: Log4JInitServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    String file = getInitParameter("log4j-init-file");
    ClassPathResource res = new ClassPathResource(file);
    if (!res.exists()) {
        // creating basic log4j configuration which writes to console out, Only called when not yet configured
        ConsoleAppender appender = new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %5p %c{1}:%L - %m%n"), ConsoleAppender.SYSTEM_OUT);
        appender.setThreshold(Level.INFO);
        BasicConfigurator.configure(appender);

        log.info("*****************************************************************************************");
        log.info("You don't provide a log4j config file for your OLAT instance. OLAT will just log to standard out (e.g. catalina.out)."
                + " Please provide a proper log config file (log4j.xml, see olat/conf for an example or read the installation guide) "
                + "and place it into the root of the classpath e.g. tomcat/lib or WEB-INF/classes");
        log.info("*****************************************************************************************");
    }
}
 
Example #13
Source Project: azure-cosmosdb-java   Author: Azure   File: LogLevelTest.java    License: MIT License 6 votes vote down vote up
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void createDocumentWithTraceLevelAtRoot() throws Exception {
    LogManager.getRootLogger().setLevel(Level.INFO);
    LogManager.getLogger(COSMOS_DB_LOGGING_CATEGORY).setLevel(Level.TRACE);
    StringWriter consoleWriter = new StringWriter();
    WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter);
    Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender);

    AsyncDocumentClient client = this.clientBuilder().build();
    try {
        Document docDefinition = getDocumentDefinition();
        Observable<ResourceResponse<Document>> createObservable = client
                .createDocument(getCollectionLink(), docDefinition, null, false);
        ResourceResponseValidator<Document> validator = new ResourceResponseValidator.Builder<Document>()
                .withId(docDefinition.getId())
                .build();
        validateSuccess(createObservable, validator);

        assertThat(consoleWriter.toString()).contains(LOG_PATTERN_1);
        assertThat(consoleWriter.toString()).contains(LOG_PATTERN_2);
        assertThat(consoleWriter.toString()).contains(LOG_PATTERN_3);
        assertThat(consoleWriter.toString()).contains(LOG_PATTERN_4);
    } finally {
        safeClose(client);
    }
}
 
Example #14
Source Project: cpsolver   Author: UniTime   File: Test.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Setup log4j logging
 * 
 * @param logFile  log file
 */
public static void setupLogging(File logFile) {
    Logger root = Logger.getRootLogger();
    ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%t] %m%n"));
    console.setThreshold(Level.INFO);
    root.addAppender(console);
    if (logFile != null) {
        try {
            FileAppender file = new FileAppender(new PatternLayout("%d{dd-MMM-yy HH:mm:ss.SSS} [%t] %-5p %c{2}> %m%n"), logFile.getPath(), false);
            file.setThreshold(Level.DEBUG);
            root.addAppender(file);
        } catch (IOException e) {
            sLog.fatal("Unable to configure logging, reason: " + e.getMessage(), e);
        }
    }
}
 
Example #15
Source Project: commons-vfs   Author: apache   File: JackrabbitMain.java    License: Apache License 2.0 6 votes vote down vote up
private void prepareServerLog(final File log) throws IOException {
    final Layout layout = new PatternLayout("%d{dd.MM.yyyy HH:mm:ss} *%-5p* %c{1}: %m%n");

    final Logger jackrabbitLog = Logger.getRootLogger();
    jackrabbitAppender = new FileAppender(layout, new File(log, "jackrabbit.log").getPath());
    jackrabbitAppender.setThreshold(Level.ALL);
    jackrabbitLog.addAppender(jackrabbitAppender);

    final Logger jettyLog = Logger.getLogger("org.mortbay.log");
    jettyAppender = new FileAppender(layout, new File(log, "jetty.log").getPath());
    jettyAppender.setThreshold(Level.ALL);
    jettyLog.addAppender(jettyAppender);
    jettyLog.setAdditivity(false);

    System.setProperty("derby.stream.error.file", new File(log, "derby.log").getPath());
}
 
Example #16
Source Project: coming   Author: SpoonLabs   File: PatternMatchingTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {

	ConsoleAppender console = new ConsoleAppender();
	String PATTERN = "%m%n";
	console.setLayout(new PatternLayout(PATTERN));
	console.setThreshold(Level.INFO);
	console.activateOptions();
	Logger.getRootLogger().getLoggerRepository().resetConfiguration();
	Logger.getRootLogger().addAppender(console);

	File s = getFile("patterns_examples/case1/1205753_EmbedPooledConnection_0_s.java");
	File t = getFile("patterns_examples/case1/1205753_EmbedPooledConnection_0_t.java");
	FineGrainDifftAnalyzer r = new FineGrainDifftAnalyzer();
	diffUpdate = r.getDiff(s, t);
	System.out.println("Output: " + diffUpdate);
	Assert.assertEquals(1, diffUpdate.getRootOperations().size());

	s = getFile("patterns_examples/case2/1205753_EmbedPooledConnection_0_s.java");
	t = getFile("patterns_examples/case2/1205753_EmbedPooledConnection_0_t.java");
	diffInsert = r.getDiff(s, t);
	System.out.println("Output: " + diffInsert);
	Assert.assertEquals(1, diffInsert.getRootOperations().size());

}
 
Example #17
Source Project: openmrs-module-initializer   Author: mekomsolutions   File: InitializerLogFactory.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static Log getLog(Class className) {
	
	Log log = LogFactory.getLog(className);
	
	final Logger logger = Logger.getLogger(className);
	try {
		logger.addAppender(
		    new FileAppender(new PatternLayout("%p - %C{1}.%M(%L) |%d{ISO8601}| %m%n"), inizLogFilePath, true));
		logger.setLevel((Level) Level.ALL);
	}
	catch (IOException e) {
		log.error("The custom logger could not be setup, defaulting on the usual logging mechanism.", e);
	}
	
	return log;
}
 
Example #18
Source Project: bigtable-sql   Author: realXuJiang   File: PreLaunchUpdateApplication.java    License: Apache License 2.0 6 votes vote down vote up
private static void initializeLogger() throws IOException
{
	String logConfigFileName = ApplicationArguments.getInstance().getLoggingConfigFileName();
	if (logConfigFileName != null) {
		PropertyConfigurator.configure(logConfigFileName);
	} else {
		ApplicationFiles appFiles = new ApplicationFiles();
		
		String logMessagePattern = "%-4r [%t] %-5p %c %x - %m%n";
		Layout layout = new PatternLayout(logMessagePattern);
		
		File logsDir = new File(appFiles.getUserSettingsDirectory(), "logs");
		File updateLogFile = new File(logsDir, "updater.log");
		
		FileAppender appender = new FileAppender(layout, updateLogFile.getAbsolutePath());
		
		LoggerController.registerLoggerFactory(new SquirrelLoggerFactory(appender, false));
	}
}
 
Example #19
Source Project: cpsolver   Author: UniTime   File: Test.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Setup log4j logging
 * 
 * @param logFile
 *            log file
 * @param debug
 *            true if debug messages should be logged (use -Ddebug=true to
 *            enable debug message)
 */
public static void setupLogging(File logFile, boolean debug) {
    Logger root = Logger.getRootLogger();
    ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%t] %m%n"));
    console.setThreshold(Level.INFO);
    root.addAppender(console);
    if (logFile != null) {
        try {
            FileAppender file = new FileAppender(new PatternLayout(
                    "%d{dd-MMM-yy HH:mm:ss.SSS} [%t] %-5p %c{2}> %m%n"), logFile.getPath(), false);
            file.setThreshold(Level.DEBUG);
            root.addAppender(file);
        } catch (IOException e) {
            sLog.fatal("Unable to configure logging, reason: " + e.getMessage(), e);
        }
    }
    if (!debug)
        root.setLevel(Level.INFO);
}
 
Example #20
Source Project: cacheonix-core   Author: cacheonix   File: SyslogAppenderTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Tests that append method drops messages below threshold.
 */
public void testAppendNoHost() {
  SyslogAppender appender = new SyslogAppender();
  appender.setName("foo");
  appender.setThreshold(Level.INFO);

  VectorErrorHandler errorHandler = new VectorErrorHandler();
  appender.setErrorHandler(errorHandler);
  appender.setLayout(new PatternLayout("%m%n"));
  appender.activateOptions();

  Logger logger = Logger.getRootLogger();
  logger.addAppender(appender);
  logger.info(
    "Should not be logged by SyslogAppenderTest.testAppendNoHost.");
  assertEquals(1, errorHandler.size());

  //
  //  Appender is misspelled in implementation
  //
  assertEquals(
    "No syslog host is set for SyslogAppedender named \"foo\".",
    errorHandler.getMessage(0));
}
 
Example #21
Source Project: lumongo   Author: lumongo   File: LogUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void loadLogConfig() throws Exception {
	synchronized (lock) {
		
		if (!loaded) {
			ConsoleAppender console = new ConsoleAppender(); //create appender
			//configure the appender
			String PATTERN = "%d [%t] <%p> %c{2}: %m%n";
			console.setLayout(new PatternLayout(PATTERN));
			console.setThreshold(Level.INFO);
			console.activateOptions();
			//add appender to any Logger (here is root)
			Logger.getRootLogger().addAppender(console);
			
			//String propPath = "/etc/loglevel.properties";
			//URL url = LogUtil.class.getResource(propPath);
			//if (url == null) {
			//	throw new Exception("Cannot find log properties file: " + propPath);
			//}
			//PropertyConfigurator.configure(url);
			loaded = true;
		}
	}
	
}
 
Example #22
Source Project: samza   Author: apache   File: TestStreamAppender.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNonDefaultSerde() {
  System.setProperty("samza.container.name", "samza-container-1");
  String streamName = StreamAppender.getStreamName("log4jTest", "1");
  Map<String, String> map = new HashMap<String, String>();
  map.put("job.name", "log4jTest");
  map.put("job.id", "1");
  map.put("serializers.registry.log4j-string.class", LoggingEventStringSerdeFactory.class.getCanonicalName());
  map.put("systems.mock.samza.factory", MockSystemFactory.class.getCanonicalName());
  map.put("systems.mock.streams." + streamName + ".samza.msg.serde", "log4j-string");
  map.put("task.log4j.system", "mock");
  MockSystemProducerAppender systemProducerAppender = new MockSystemProducerAppender(new MapConfig(map));
  PatternLayout layout = new PatternLayout();
  layout.setConversionPattern("%m");
  systemProducerAppender.setLayout(layout);
  systemProducerAppender.activateOptions();
  assertNotNull(systemProducerAppender.getSerde());
  assertEquals(LoggingEventStringSerde.class, systemProducerAppender.getSerde().getClass());
}
 
Example #23
Source Project: big-c   Author: yncxcw   File: TestContainerLogAppender.java    License: Apache License 2.0 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 #24
Source Project: olat   Author: huihoo   File: Log4JInitServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    String file = getInitParameter("log4j-init-file");
    ClassPathResource res = new ClassPathResource(file);
    if (!res.exists()) {
        // creating basic log4j configuration which writes to console out, Only called when not yet configured
        ConsoleAppender appender = new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %5p %c{1}:%L - %m%n"), ConsoleAppender.SYSTEM_OUT);
        appender.setThreshold(Level.INFO);
        BasicConfigurator.configure(appender);

        log.info("*****************************************************************************************");
        log.info("You don't provide a log4j config file for your OLAT instance. OLAT will just log to standard out (e.g. catalina.out)."
                + " Please provide a proper log config file (log4j.xml, see olat/conf for an example or read the installation guide) "
                + "and place it into the root of the classpath e.g. tomcat/lib or WEB-INF/classes");
        log.info("*****************************************************************************************");
    }
}
 
Example #25
Source Project: tasmo   Author: jivesoftware   File: ModePathPrefixMerging.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
    public void logger() {
        String PATTERN = "%t %m%n";

        Enumeration allAppenders = LogManager.getRootLogger().getAllAppenders();
        while (allAppenders.hasMoreElements()) {
            Appender appender = (Appender) allAppenders.nextElement();
            appender.setLayout(new PatternLayout(PATTERN));
        }
        //if (verbose) {
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib").setLevel(Level.TRACE);
        LogManager.getLogger("com.jivesoftware.os.tasmo.lib.TasmoViewModel").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.lib.concur.ConcurrencyAndExistanceCommitChange").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.reference.lib.ReferenceStore").setLevel(Level.TRACE);
//            LogManager.getLogger("com.jivesoftware.os.tasmo.view.reader.service.writer.WriteToViewValueStore").setLevel(Level.TRACE);
//        } else {
//            LogManager.getRootLogger().setLevel(Level.OFF);
//        }
    }
 
Example #26
Source Project: CloverETL-Engine   Author: CloverETL   File: SafeLogLayoutTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testNonStringMessage() {
	Integer message = new Integer(17);
	Exception e = new Exception("testExceptionMessage");
	StackTraceElement[] stacktrace = new StackTraceElement[2];
	stacktrace[0]= new StackTraceElement("org.thisTest.SafeLogLayoutTest", "methodName1", "fileName1", 1);
	stacktrace[1]= new StackTraceElement("org.thisTest.SafeLogLayoutTest", "methodName2", "fileName2", 2);
	e.setStackTrace(stacktrace);
	LoggingEvent event = new LoggingEvent("org.jetel.logger.SafeLogLayoutTest", logger, Level.ERROR, message, e);
	
	String safeValue = layout.format(event);
	PatternLayout ptlay = new PatternLayout();
	String expectedValue = ptlay.format(event);
	expectedValue += "java.lang.Exception: testExceptionMessage\n"+
			"	at org.thisTest.SafeLogLayoutTest.methodName1(fileName1:1)\n"+
			"	at org.thisTest.SafeLogLayoutTest.methodName2(fileName2:2)\n";

	assertEquals(safeValue, expectedValue);
}
 
Example #27
Source Project: flowable-engine   Author: flowable   File: MDCLoggingTest.java    License: Apache License 2.0 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 #28
Source Project: cpsolver   Author: UniTime   File: Test.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Setup log4j logging
 * 
 * @param logFile  log file
 * @param debug true if debug messages should be logged (use -Ddebug=true to enable debug message)
 */
public static void setupLogging(File logFile, boolean debug) {
    Logger root = Logger.getRootLogger();
    ConsoleAppender console = new ConsoleAppender(new PatternLayout("[%t] %m%n"));
    console.setThreshold(Level.INFO);
    root.addAppender(console);
    if (logFile != null) {
        try {
            FileAppender file = new FileAppender(new PatternLayout("%d{dd-MMM-yy HH:mm:ss.SSS} [%t] %-5p %c{2}> %m%n"), logFile.getPath(), false);
            file.setThreshold(Level.DEBUG);
            root.addAppender(file);
        } catch (IOException e) {
            sLogger.fatal("Unable to configure logging, reason: " + e.getMessage(), e);
        }
    }
    if (!debug)
        root.setLevel(Level.INFO);
}
 
Example #29
Source Project: zeppelin   Author: apache   File: HeliumBundleFactory.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void configureLogger() {
  org.apache.log4j.Logger npmLogger = org.apache.log4j.Logger.getLogger(
      "com.github.eirslett.maven.plugins.frontend.lib.DefaultYarnRunner");
  Enumeration appenders = org.apache.log4j.Logger.getRootLogger().getAllAppenders();

  if (appenders != null) {
    while (appenders.hasMoreElements()) {
      Appender appender = (Appender) appenders.nextElement();
      appender.addFilter(new Filter() {

        @Override
        public int decide(LoggingEvent loggingEvent) {
          if (loggingEvent.getLoggerName().contains("DefaultYarnRunner")) {
            return DENY;
          } else {
            return NEUTRAL;
          }
        }
      });
    }
  }
  npmLogger.addAppender(new WriterAppender(
      new PatternLayout("%m%n"),
      out
  ));
}
 
Example #30
Source Project: hadoop-ozone   Author: apache   File: GenericTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
private LogCapturer(Logger logger) {
  this.logger = logger;
  Appender defaultAppender = Logger.getRootLogger().getAppender("stdout");
  if (defaultAppender == null) {
    defaultAppender = Logger.getRootLogger().getAppender("console");
  }
  final Layout layout = (defaultAppender == null) ? new PatternLayout() :
      defaultAppender.getLayout();
  this.appender = new WriterAppender(layout, sw);
  logger.addAppender(this.appender);
}