org.apache.log4j.FileAppender Java Examples

The following examples show how to use org.apache.log4j.FileAppender. 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 File: Log4jLoggerAdapter.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #2
Source File: CoasterService.java    From swift-k with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected static Appender getFileAppender() {
    Logger root = Logger.getRootLogger();
    Enumeration e = root.getAllAppenders();
    while (e.hasMoreElements()) {
        Appender a = (Appender) e.nextElement();
        if (a instanceof FileAppender) {
            return a;
        }
        if (a instanceof AsyncAppender) {
            // likely this is running in a JVM in which
            // the file appender has been replaced with
            // an async appender, so don't mess with things
            return null;
        }
    }
    logger.warn("Could not find a file appender to configure");
    return null;
}
 
Example #3
Source File: Ase.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
private static void startLogging(File logFile, boolean debugMode) {

		try {
			FileAppender logAppender = new FileAppender(new SimpleLayout(), logFile.getCanonicalPath(), false);
			Logger.getRootLogger().removeAllAppenders();
			Logger.getRootLogger().addAppender(logAppender);
			if (debugMode) {
				LOGGER.setLevel(Level.DEBUG);
			} else {
				LOGGER.setLevel(Level.INFO);
			}
		} catch (IOException e) {
			System.err.println("Failed to create logger: " + e.getMessage());
			System.exit(1);
		}

		LOGGER.info(
				"\n" + HEADER);
		LOGGER.info("Version: " + VERSION);
		LOGGER.info("Current date and time: " + DATE_TIME_FORMAT.format(currentDataTime));
		LOGGER.info("Log level: " + LOGGER.getLevel());

		System.out.println("Started logging");
		System.out.println();
	}
 
Example #4
Source File: Log4jLoggerAdapter.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter(){
    try {
        org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender) appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
}
 
Example #5
Source File: Logging.java    From swift-t with Apache License 2.0 6 votes vote down vote up
private static void setupLoggingToFile(Logger stcLogger, String logfile,
    boolean trace) {
  Layout layout = new PatternLayout("%-5p %m%n");
  boolean append = false;
  try {
    FileAppender appender = new FileAppender(layout, logfile, append);
    Level threshold;
    if (trace) {
      threshold = Level.TRACE;
    } else {
      threshold = Level.DEBUG;
    }
    appender.setThreshold(threshold);
    stcLogger.addAppender(appender);
    stcLogger.setLevel(threshold);
  } catch (IOException e) {
    System.out.println(e.getMessage());
    System.exit(ExitCode.ERROR_IO.code());
  }
}
 
Example #6
Source File: PreLaunchUpdateApplication.java    From bigtable-sql with 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 #7
Source File: RdfSClassGenerator.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void generateCode() throws MojoExecutionException, MojoFailureException {
	try {
	    // make sure that directory for log file exists.
	    rdfReactorLogfile.getParentFile().mkdirs();
		
	    // configure logging infrastructure for RDFReactor
	    FileAppender logFileAppender = new FileAppender(new SimpleLayout(), rdfReactorLogfile.getAbsolutePath());
		BasicConfigurator.configure(logFileAppender);

	} catch (IOException ioe) {
		throw new MojoExecutionException("Cannot open log file for writing RDFReactor log messages", ioe);
	}

	getLog().info("Generating code from RDF schema file " + schemaFile + " into dir " + outputDirectory
			+ ". Classes will be in package " + packageName + " and with method prefix " + methodPrefix +". skipBuiltins is " + skipBuiltins + ".");
	getLog().info("RDFReactor's log messages are written to " + rdfReactorLogfile);


	try {
		CodeGenerator.generate(schemaFile.getAbsolutePath(), outputDirectory.getAbsolutePath(), packageName, Reasoning.rdfs, skipBuiltins, methodPrefix);
	} catch (Exception e) {
		e.printStackTrace();
	    throw new MojoFailureException(e, "RDFS processing error", "Could not generate code from the specified RDF schema file.");
	}
}
 
Example #8
Source File: TimelineMetricConfiguration.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
public String getDefaultMetricsSinkDir() {
  String dirPath = metricsConf.get(DEFAULT_EXTERNAL_SINK_DIR);
  if (dirPath == null) {
    // Only one logger at the time of writing
    Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement();
    if (appender instanceof FileAppender) {
      File f = new File(((FileAppender) appender).getFile());
      if (f.exists()) {
        dirPath = f.getParent();
      } else {
        dirPath = "/tmp";
      }
    }
  }

  return dirPath;
}
 
Example #9
Source File: Log4jLoggerAdapter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #10
Source File: MR4CLogging.java    From mr4c with Apache License 2.0 6 votes vote down vote up
private Set<File> extractAppenderFiles(org.apache.log4j.Logger logger) {
	Set<File> result = new HashSet<File>();
	Enumeration<Appender> e = logger.getAllAppenders();
	while ( e.hasMoreElements() ) {
		Appender app = e.nextElement();
		if (app instanceof FileAppender ) {
			FileAppender fileApp = (FileAppender) app;
			String filePath = fileApp.getFile();
			if ( filePath==null ) {
				m_logger.warn("Logger {} has file appender {}  with no file", logger.getName(), app.getName());
			} else {
				result.add(new File(filePath));
			}
		}
	}
	return result;
}
 
Example #11
Source File: Log4jLoggerAdapter.java    From light-task-scheduler with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #12
Source File: LogPageHandler.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public LogPageHandler() {
    try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender)appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
   }
 
Example #13
Source File: TaskLogger.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
public File createFileAppender(File pathToFolder) throws IOException {
    if (taskLogAppender.getAppender(FILE_APPENDER_NAME) != null) {
        throw new IllegalStateException("Only one file appender can be created");
    }

    File logFile = new File(pathToFolder, new TaskLoggerRelativePathGenerator(taskId).getRelativePath());
    boolean append = true;
    if (!logFile.exists()) {
        append = false;
        logFile.getParentFile().mkdirs();

        FileUtils.touch(logFile);
    }

    logFile.setWritable(true, false);

    FileAppender fap = new FileAppender(Log4JTaskLogs.getTaskLogLayout(), logFile.getAbsolutePath(), append);
    fap.setName(FILE_APPENDER_NAME);
    taskLogAppender.addAppender(fap);

    return logFile;
}
 
Example #14
Source File: LogPageHandler.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public LogPageHandler() {
    try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender)appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
   }
 
Example #15
Source File: ActiveActor.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
private void addHostToFilename(FileAppender fileApp) {
    String hostID = Math.abs(UniqueID.getCurrentVMID().hashCode() % 100000) + "-" +
                    ProActiveInet.getInstance().getHostname();
    String fileName = fileApp.getFile();
    File filePath = new File(fileName);
    String hostFileName;
    String name = filePath.getName();
    String pathToFile = filePath.getParent();
    int point = name.indexOf('.');
    if (point == -1) {
        hostFileName = fileName + "-" + hostID;
    } else {
        String extension = name.substring(point + 1);
        String nameNoExtension = name.substring(0, point);
        hostFileName = (pathToFile != null ? pathToFile : "") + File.separator + nameNoExtension + "-" + hostID +
                       "." + extension;
    }
    System.out.println("New output file:" + hostFileName);
    fileApp.setFile(hostFileName);
    fileApp.activateOptions();
}
 
Example #16
Source File: SystemLogPage.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public SystemLogPage() {
	super();
	
	WebMarkupContainer cssContainer = new WebMarkupContainer("cssPath");
       cssContainer.add(new AttributeModifier("href", ThemesManager.getInstance().getThemeRelativePathCss()));
       add(cssContainer);
	
	FileAppender appender = (FileAppender) LogManager.getRootLogger().getAppender("FILE");
	File logFile = new File(appender.getFile());
	
	String content;
	try {
		content = FileUtils.readFileToString(logFile);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		content = e.toString();
	}
	
	add(new Label("size", FileUtils.byteCountToDisplaySize(logFile.length())));
	add(new Label("lastModified", new Date(logFile.lastModified()).toString()));
	add(new MultiLineLabel("log", content));
}
 
Example #17
Source File: Log4jHookProxy.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private LinkedList<LogProfileInfo> figureoutLogConfiguration(Logger Logger, String appid) {
    
    LinkedList<LogProfileInfo> logProfiles = new LinkedList<LogProfileInfo>();

    Enumeration<Appender> appenders = Logger.getAllAppenders();
    while (appenders != null && appenders.hasMoreElements()) {

        Appender appender = appenders.nextElement();
        if (appender instanceof FileAppender) {
            logProfiles.add(getAppenderInfo((FileAppender)appender, appid));
        }
        else if(appender instanceof AsyncAppender) {
            Enumeration<Appender> ads = ((AsyncAppender) appender).getAllAppenders();
            while(ads != null && ads.hasMoreElements()) {
                Appender ap = ads.nextElement();
                if(ap instanceof FileAppender) {
                    logProfiles.add(getAppenderInfo((FileAppender)ap, appid));
                }
            }
        }
    }
    
    return logProfiles;
}
 
Example #18
Source File: ActiveActor.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Log4j configuration tweaking
 * This method will modify the file name of every FileAppender
 * 	by adding the hostname of the machine onto which it executes.
 * Because it cannot be done from the log4j-configuration file
 * 	we hard-code this configuration issue
 * @param logger2 
 */
private void rebaseLogFiles() {
    Enumeration<Logger> curLoggers = LogManager.getCurrentLoggers();
    while (curLoggers.hasMoreElements()) {
        Logger someLogger = curLoggers.nextElement();
        Enumeration<Appender> appenders = someLogger.getAllAppenders();
        while (appenders.hasMoreElements()) {
            Appender app = appenders.nextElement();
            if (app instanceof FileAppender) {
                FileAppender fileApp = (FileAppender) app;
                System.out.println("File appender, output file " + fileApp.getFile());
                addHostToFilename(fileApp);
            }
        }
    }
}
 
Example #19
Source File: Test.java    From cpsolver with 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 #20
Source File: TestAutoLocalMode.java    From spork with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception{
    pigServer = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
    pigServer.getPigContext().getExecutionEngine().setProperty(PigConfiguration.PIG_OPT_FETCH, "false");
    pigServer.getPigContext().getExecutionEngine().setProperty(PigConfiguration.PIG_AUTO_LOCAL_ENABLED, String.valueOf("true"));
    pigServer.getPigContext().getExecutionEngine().setProperty(PigConfiguration.PIG_AUTO_LOCAL_INPUT_MAXBYTES, "200");

    Logger logger = Logger.getLogger(JobControlCompiler.class);
    logger.removeAllAppenders();
    logger.setLevel(Level.INFO);
    SimpleLayout layout = new SimpleLayout();
    logFile = File.createTempFile("log", "");
    FileAppender appender = new FileAppender(layout, logFile.toString(), false, false, 0);
    logger.addAppender(appender);

    miniFileName = createInputFile("miniFile", 10).getAbsolutePath();
    smallFileName = createInputFile("smallFile", 100).getAbsolutePath();
    bigFileName = createInputFile("bigFile", 1000).getAbsolutePath();
}
 
Example #21
Source File: Test.java    From cpsolver with 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 #22
Source File: LogPageHandler.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public LogPageHandler() {
    try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender)appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
   }
 
Example #23
Source File: Log4jLoggerAdapter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter() {
	try {
		org.apache.log4j.Logger logger = LogManager.getRootLogger();
           if (logger != null) {
               Enumeration<Appender> appenders = logger.getAllAppenders();
               if (appenders != null) {
                   while (appenders.hasMoreElements()) {
                       Appender appender = appenders.nextElement();
                       if (appender instanceof FileAppender) {
                           FileAppender fileAppender = (FileAppender)appender;
                           String filename = fileAppender.getFile();
                           file = new File(filename);
                           break;
                       }
                   }
               }
           }
       } catch (Throwable t) {
       }
}
 
Example #24
Source File: Action.java    From charles-rest with BSD 3-Clause "New" or "Revised" 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 #25
Source File: RhnJavaJob.java    From spacewalk with 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 #26
Source File: Log4jLoggerAdapter.java    From tddl with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Log4jLoggerAdapter(){
    try {
        org.apache.log4j.Logger logger = LogManager.getRootLogger();
        if (logger != null) {
            Enumeration<Appender> appenders = logger.getAllAppenders();
            if (appenders != null) {
                while (appenders.hasMoreElements()) {
                    Appender appender = appenders.nextElement();
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = (FileAppender) appender;
                        String filename = fileAppender.getFile();
                        file = new File(filename);
                        break;
                    }
                }
            }
        }
    } catch (Throwable t) {
    }
}
 
Example #27
Source File: XMLLayoutTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testMDCEscaped() throws Exception {
  XMLLayout xmlLayout = new XMLLayout();
  xmlLayout.setProperties(true);
  root.addAppender(new FileAppender(xmlLayout, TEMP, false));

  Hashtable context = MDC.getContext();
  if (context != null) {
      context.clear();
  }
  MDC.put("blahAttribute", "<blah value='blah'>");
  MDC.put("<blahKey value='blah'/>", "blahValue");

  logger.debug("Hello");
  Transformer.transform(
    TEMP, FILTERED,
    new Filter[] { new LineNumberFilter(),
        new JunitTestRunnerFilter(),
        new XMLTimestampFilter() });
  assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.2"));
}
 
Example #28
Source File: XMLLayoutTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void locationInfo() throws Exception {
  XMLLayout xmlLayout = new XMLLayout();
  xmlLayout.setLocationInfo(true);
  root.addAppender(new FileAppender(xmlLayout, TEMP, false));
  common();
  Transformer.transform(
    TEMP, FILTERED,
    new Filter[] {
      new LineNumberFilter(),
      new XMLTimestampFilter(), 
      new XMLLineAttributeFilter(),
      new JunitTestRunnerFilter(),
      new SunReflectFilter()
    });
  assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.2"));
}
 
Example #29
Source File: Main.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
private static void startLogging(File logFile, boolean debugMode) {

        try {
            FileAppender logAppender = new FileAppender(new SimpleLayout(), logFile.getCanonicalPath(), false);
            Logger.getRootLogger().removeAllAppenders();
            Logger.getRootLogger().addAppender(logAppender);
            if (debugMode) {
                LOGGER.setLevel(Level.DEBUG);
            } else {
                LOGGER.setLevel(Level.INFO);
            }
        } catch (IOException e) {
            System.err.println("Failed to create logger: " + e.getMessage());
            System.exit(1);
        }

        LOGGER.info(
                "\n" + HEADER);
        LOGGER.info("Version: " + VERSION);
        LOGGER.info("Current date and time: " + DATE_TIME_FORMAT.format(currentDataTime));
        LOGGER.info("Log level: " + LOGGER.getLevel());

        System.out.println("Started logging");
        System.out.println();
    }
 
Example #30
Source File: XMLLayoutTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testNull() throws Exception {
  XMLLayout xmlLayout = new XMLLayout();
  root.addAppender(new FileAppender(xmlLayout, TEMP, false));

  String oldThreadName = Thread.currentThread().getName();
  Thread.currentThread().setName("main");

  logger.debug("hi");
  logger.debug(null);
  Exception e = new Exception((String) null);
  logger.debug("hi", e);

  Thread.currentThread().setName(oldThreadName);

  Transformer.transform(
    TEMP, FILTERED,
    new Filter[] { new LineNumberFilter(),
        new XMLTimestampFilter(),  
        new JunitTestRunnerFilter(),
        new SunReflectFilter()});
  assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.null"));
}