下面列出了怎么用org.apache.log4j.xml.DOMConfigurator的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(final String... args) {
File log4jConfigurationFile = new File(
"src/test/resources/log4j.xml");
if (log4jConfigurationFile.exists()) {
DOMConfigurator.configureAndWatch(
log4jConfigurationFile.getAbsolutePath(), 15);
}
try {
final int port = 9090;
System.out.println("About to start server on port: " + port);
HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer
.bootstrapFromFile("./littleproxy.properties")
.withPort(port).withAllowLocalOnly(false);
bootstrap.withManInTheMiddle(new CertificateSniffingMitmManager());
System.out.println("About to start...");
bootstrap.start();
} catch (Exception e) {
log.error(e.getMessage(), e);
System.exit(1);
}
}
@Test
public void testLocalProperties() throws NoSuchFieldException, IllegalAccessException {
LoggerRepository repo2 = new Hierarchy(new RootLogger((Level) Level.DEBUG));
URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j/log4j_b.xml");
DOMConfigurator domConfigurator = new DOMConfigurator();
Field field = DOMConfigurator.class.getDeclaredField("props");
field.setAccessible(true);
Properties props = new Properties();
field.set(domConfigurator, props);
props.put("hello", "defaultb");
domConfigurator.doConfigure(url2, repo2);
Logger logger2 = repo2.getLogger("com.foo.Bar3");
Assert.assertTrue(logger2.getAllAppenders().hasMoreElements());
}
@Override
public void loading() throws AlbianServiceException {
try {
Thread.currentThread().setContextClassLoader(AlbianClassLoader.getInstance());
if (KernelSetting.getAlbianConfigFilePath().startsWith("http://")) {
DOMConfigurator.configure(new URL(Path
.getExtendResourcePath(KernelSetting
.getAlbianConfigFilePath() + "log4j.xml")));
} else {
DOMConfigurator.configure(Path
.getExtendResourcePath(KernelSetting
.getAlbianConfigFilePath() + "log4j.xml"));
}
super.loading();
loggers = new ConcurrentHashMap<String, Logger>();
} catch (Exception exc) {
throw new AlbianServiceException(exc.getMessage(), exc.getCause());
}
}
public static void main(final String... args) {
File log4jConfigurationFile = new File(
"src/test/resources/log4j.xml");
if (log4jConfigurationFile.exists()) {
DOMConfigurator.configureAndWatch(
log4jConfigurationFile.getAbsolutePath(), 15);
}
try {
final int port = 9090;
System.out.println("About to start server on port: " + port);
HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer
.bootstrapFromFile("./littleproxy.properties")
.withPort(port).withAllowLocalOnly(false);
bootstrap.withManInTheMiddle(new CertificateSniffingMitmManager());
System.out.println("About to start...");
bootstrap.start();
} catch (Exception e) {
log.error(e.getMessage(), e);
System.exit(1);
}
}
void common(int number) throws Exception {
DOMConfigurator.configure("input/xml/customLogger"+number+".xml");
int i = -1;
Logger root = Logger.getRootLogger();
logger.trace("Message " + ++i);
logger.debug("Message " + ++i);
logger.warn ("Message " + ++i);
logger.error("Message " + ++i);
logger.fatal("Message " + ++i);
Exception e = new Exception("Just testing");
logger.debug("Message " + ++i, e);
Transformer.transform(
"output/temp", FILTERED,
new Filter[] {
new LineNumberFilter(), new SunReflectFilter(),
new JunitTestRunnerFilter()
});
assertTrue(Compare.compare(FILTERED, "witness/customLogger."+number));
}
public void test1() throws Exception {
DOMConfigurator.configure("input/xml/fallback1.xml");
common();
ControlFilter cf1 = new ControlFilter(new String[]{TEST1_1A_PAT, TEST1_1B_PAT,
EXCEPTION1, EXCEPTION2, EXCEPTION3});
ControlFilter cf2 = new ControlFilter(new String[]{TEST1_2_PAT,
EXCEPTION1, EXCEPTION2, EXCEPTION3});
Transformer.transform(TEMP_A1, FILTERED_A1, new Filter[] {cf1,
new LineNumberFilter()});
Transformer.transform(TEMP_A2, FILTERED_A2, new Filter[] {cf2,
new LineNumberFilter(), new ISO8601Filter()});
assertTrue(Compare.compare(FILTERED_A1, "witness/dom.A1.1"));
assertTrue(Compare.compare(FILTERED_A2, "witness/dom.A2.1"));
}
/**
* Creates new logger with given configuration {@code cfgUrl}.
* <p>
* If {@code watchDelay} is not zero, created logger will check the configuration file for changes once every
* {@code watchDelay} milliseconds, and update its configuration if the file was changed.
* See {@link DOMConfigurator#configureAndWatch(String, long)} for details.
*
* @param cfgUrl URL for Log4j configuration XML file.
* @param watchDelay delay in milliseconds used to check configuration file for changes.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public Log4JLogger(final URL cfgUrl, final long watchDelay) throws IgniteCheckedException {
if (cfgUrl == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
if (watchDelay < 0)
throw new IgniteCheckedException("watchDelay can't be negative: " + watchDelay);
cfg = cfgUrl.getPath();
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init) {
if (watchDelay > 0)
DOMConfigurator.configureAndWatch(cfg, watchDelay);
else
DOMConfigurator.configure(cfg);
}
return Logger.getRootLogger();
}
});
quiet = quiet0;
}
/**
* Creates new logger with given configuration {@code path}.
*
* @param path Path to log4j configuration XML file.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public GridTestLog4jLogger(String path) throws IgniteCheckedException {
if (path == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
this.cfg = path;
final URL cfgUrl = U.resolveIgniteUrl(path);
if (cfgUrl == null)
throw new IgniteCheckedException("Log4j configuration path was not found: " + path);
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
DOMConfigurator.configure(cfgUrl);
return Logger.getRootLogger();
}
});
quiet = quiet0;
}
/**
* Creates new logger with given configuration {@code cfgFile}.
*
* @param cfgFile Log4j configuration XML file.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public GridTestLog4jLogger(File cfgFile) throws IgniteCheckedException {
if (cfgFile == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
if (!cfgFile.exists() || cfgFile.isDirectory())
throw new IgniteCheckedException("Log4j configuration path was not found or is a directory: " + cfgFile);
cfg = cfgFile.getAbsolutePath();
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
DOMConfigurator.configure(cfg);
return Logger.getRootLogger();
}
});
quiet = quiet0;
}
/**
* Creates new logger with given configuration {@code cfgUrl}.
*
* @param cfgUrl URL for Log4j configuration XML file.
* @throws IgniteCheckedException Thrown in case logger can't be created.
*/
public GridTestLog4jLogger(final URL cfgUrl) throws IgniteCheckedException {
if (cfgUrl == null)
throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");
cfg = cfgUrl.getPath();
addConsoleAppenderIfNeeded(null, new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
DOMConfigurator.configure(cfgUrl);
return Logger.getRootLogger();
}
});
quiet = quiet0;
}
public static void main(final String[] args) {
final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration");
if (StringUtils.isNotBlank(log4jConfiguration)) {
final String parsedConfiguration = PathUtils.clean(StringUtils.removeStart(log4jConfiguration, "file:"));
final File configFile = new File(parsedConfiguration);
if (configFile.exists()) {
DOMConfigurator.configure(parsedConfiguration);
} else {
BasicConfigurator.configure();
}
}
log.info("Starting Copy Tool");
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> log.error("Uncaught exception in " + thread.getName(), throwable));
final CopyTool copyTool = new CopyTool();
final int returnCode = copyTool.setupAndRun(args);
log.info("Finished running Copy Tool");
System.exit(returnCode);
}
public static void main(final String[] args) {
final String log4jConfiguration = System.getProperties().getProperty("log4j.configuration");
if (StringUtils.isNotBlank(log4jConfiguration)) {
final String parsedConfiguration = PathUtils.clean(StringUtils.removeStart(log4jConfiguration, "file:"));
final File configFile = new File(parsedConfiguration);
if (configFile.exists()) {
DOMConfigurator.configure(parsedConfiguration);
} else {
BasicConfigurator.configure();
}
}
log.info("Starting Merge Tool");
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread thread, final Throwable throwable) {
log.error("Uncaught exception in " + thread.getName(), throwable);
}
});
final int returnCode = setupAndRun(args);
log.info("Finished running Merge Tool");
System.exit(returnCode);
}
public static void main(final String... args) {
File log4jConfigurationFile = new File(
"src/test/resources/log4j.xml");
if (log4jConfigurationFile.exists()) {
DOMConfigurator.configureAndWatch(
log4jConfigurationFile.getAbsolutePath(), 15);
}
try {
final int port = 9090;
System.out.println("About to start server on port: " + port);
HttpProxyServerBootstrap bootstrap = DefaultHttpProxyServer
.bootstrapFromFile("./littleproxy.properties")
.withPort(port).withAllowLocalOnly(false);
bootstrap.withManInTheMiddle(new CertificateSniffingMitmManager());
System.out.println("About to start...");
bootstrap.start();
} catch (Exception e) {
log.error(e.getMessage(), e);
System.exit(1);
}
}
private void reloadConfig() throws MalformedURLException, FactoryConfigurationError, BException {
String blurHome = System.getenv("BLUR_HOME");
if (blurHome != null) {
File blurHomeFile = new File(blurHome);
if (blurHomeFile.exists()) {
File log4jFile = new File(new File(blurHomeFile, "conf"), "log4j.xml");
if (log4jFile.exists()) {
LOG.info("Reseting log4j config from [{0}]", log4jFile);
LogManager.resetConfiguration();
DOMConfigurator.configure(log4jFile.toURI().toURL());
return;
}
}
}
URL url = TableAdmin.class.getResource("/log4j.xml");
if (url != null) {
LOG.info("Reseting log4j config from classpath resource [{0}]", url);
LogManager.resetConfiguration();
DOMConfigurator.configure(url);
return;
}
throw new BException("Could not locate log4j file to reload, doing nothing.");
}
protected static void configureLogging(Properties properties) {
// Init logging: Try standard log4j configuration mechanism before falling back to
// provided logging configuration
String log4jConfig = System.getProperty("log4j.configuration");
if (null == log4jConfig) {
if (properties.containsKey(PropertiesBasedServerSetupBuilder.GREENMAIL_VERBOSE)) {
DOMConfigurator.configure(GreenMailStandaloneRunner.class.getResource("/log4j-verbose.xml"));
} else {
DOMConfigurator.configure(GreenMailStandaloneRunner.class.getResource("/log4j.xml"));
}
} else {
if (log4jConfig.toLowerCase().endsWith(".xml")) {
DOMConfigurator.configure(log4jConfig);
} else {
PropertyConfigurator.configure(log4jConfig);
}
}
}
@Override
protected void setUp() {
URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
if (configUrl != null) {
System.out.println("Configure log4j using log4j-cloud.xml");
try {
File file = new File(configUrl.toURI());
System.out.println("Log4j configuration from : " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
} catch (URISyntaxException e) {
System.out.println("Unable to convert log4j configuration Url to URI");
}
} else {
System.out.println("Configure log4j with default properties");
}
}
private static void setupLog4j() {
URL configUrl = System.class.getResource("/resources/log4j-cloud.xml");
if (configUrl != null) {
System.out.println("Configure log4j using log4j-cloud.xml");
try {
File file = new File(configUrl.toURI());
System.out.println("Log4j configuration from : " + file.getAbsolutePath());
DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
} catch (URISyntaxException e) {
System.out.println("Unable to convert log4j configuration Url to URI");
}
} else {
System.out.println("Configure log4j with default properties");
}
}
@BeforeClass
public static void testSetup() throws IOException, SQLException, DAOConfigurationException {
URL configFileResource = PostgresqlDAOTest.class.getResource("/com/ast/processserver/resources/log4j.xml");
DOMConfigurator.configure(configFileResource);
Config.loadProperties();
String dataSource = "postgresql";
DAOFactory factory = new DAOFactory(dataSource);
connection = ConnectionPoolFactory.getConnectionPool(dataSource).getConnection();
workspaceDAO = factory.getWorkspaceDao(connection);
userDao = factory.getUserDao(connection);
objectDao = factory.getItemDAO(connection);
oversionDao = factory.getItemVersionDAO(connection);
}
private void applyLog4jConfiguration() {
LogLog.setQuietMode( true );
LogManager.resetConfiguration();
LogLog.setQuietMode( false );
/**
* On DOMConfigurator.doConfigure() no exception is ever propagated; it's caught and its stacktrace is written to System.err.
*
* @link https://github.com/apache/log4j/blob/v1_2_17_rc3/src/main/java/org/apache/log4j/xml/DOMConfigurator.java#L877-L878
*
* When the kettle5-log4j-plugin is dropped under ~/.kettle/plugins ( which is also a valid location for classic pdi plugins )
* we get a System.err 'FileNotFoundException' stacktrace, as this is attempting to fetch the log4j.xml under a (default path) of
* data-integration/plugins/kettle5-log4j-plugin; but in this scenario ( again, a valid one ), kettle5-log4j-plugin is under ~/.kettle/plugins
*
* With the inability to catch any exception ( as none is ever propagated ), the option left is to infer the starting path of this plugin's jar;
* - If it starts with Const.getKettleDirectory(): then we know it to have been dropped in ~/.kettle/plugins ( a.k.a. Const.getKettleDirectory() )
* - Otherwise: fallback to default/standard location, which is under <pdi-install-dir>/</>data-integration/plugins
*/
final String log4jPath = getPluginPath().startsWith( getKettleDirPath() )
? ( Const.getKettleDirectory() + File.separator + PLUGIN_PROPERTIES_FILE ) : getConfigurationFileName();
DOMConfigurator.configure( log4jPath );
}
public static void initLog4J(PropertyHandler propertyHandler) {
LOG.info("**************** Init LOG4J");
if (propertyHandler != null) {
Path path = Paths.get(propertyHandler.getProperty("LOG4J", "log4j.xml"));
if (Files.exists(path)) {
LogManager.resetConfiguration();
DOMConfigurator.configure(path.toAbsolutePath().toString());
LOG.info("Loading log4j config from " + path.toAbsolutePath().toString());
}
}
}
public static void initLog4J(PropertyHandler propertyHandler) {
LOG.info("**************** Init LOG4J");
if (propertyHandler != null) {
Path path = Paths.get(propertyHandler.getProperty("LOG4J", "log4j.xml"));
if (Files.exists(path, new LinkOption[0])) {
LogManager.resetConfiguration();
DOMConfigurator.configure(path.toAbsolutePath().toString());
LOG.info("Loading log4j config from " + path.toAbsolutePath().toString());
}
}
}
public static void initLog4J(PropertyHandler propertyHandler) {
LOG.info("**************** Init LOG4J");
if (propertyHandler != null) {
Path path = Paths.get(propertyHandler.getProperty("LOG4J", "log4j.xml"));
if (Files.exists(path)) {
LogManager.resetConfiguration();
DOMConfigurator.configure(path.toAbsolutePath().toString());
LOG.info("Loading log4j config from " + path.toAbsolutePath().toString());
}
}
}
/**
* Initialize log4j from the given file location, with no config file refreshing.
* Assumes an XML file in case of a ".xml" file extension, and a properties file
* otherwise.
* @param location the location of the config file: either a "classpath:" location
* (e.g. "classpath:myLog4j.properties"), an absolute file URL
* (e.g. "file:C:/log4j.properties), or a plain absolute path in the file system
* (e.g. "C:/log4j.properties")
* @throws FileNotFoundException if the location specifies an invalid file path
*/
public static void initLogging(String location) throws FileNotFoundException {
String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
URL url = ResourceUtils.getURL(resolvedLocation);
if (ResourceUtils.URL_PROTOCOL_FILE.equals(url.getProtocol()) && !ResourceUtils.getFile(url).exists()) {
throw new FileNotFoundException("Log4j config file [" + resolvedLocation + "] not found");
}
if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
DOMConfigurator.configure(url);
}
else {
PropertyConfigurator.configure(url);
}
}
@Override
public Response reload() {
ApplicationProperties.reload();
Properties copyToReturn = ApplicationProperties.getProperties();
configurer.setProperties(copyToReturn);
filesConfiguration.reload();
LogManager.resetConfiguration();
DOMConfigurator.configure("../data/conf/log4j.xml");
copyToReturn.put("logging-reload-state", "Property reload complete");
return ResponseBuilder.ok(new TreeMap<>(copyToReturn));
}
/**
* Initialize log4j from the given file location, with no config file refreshing.
* Assumes an XML file in case of a ".xml" file extension, and a properties file
* otherwise.
* @param location the location of the config file: either a "classpath:" location
* (e.g. "classpath:myLog4j.properties"), an absolute file URL
* (e.g. "file:C:/log4j.properties), or a plain absolute path in the file system
* (e.g. "C:/log4j.properties")
* @throws FileNotFoundException if the location specifies an invalid file path
*/
public static void initLogging(String location) throws FileNotFoundException {
String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
URL url = ResourceUtils.getURL(resolvedLocation);
if (ResourceUtils.URL_PROTOCOL_FILE.equals(url.getProtocol()) && !ResourceUtils.getFile(url).exists()) {
throw new FileNotFoundException("Log4j config file [" + resolvedLocation + "] not found");
}
if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
DOMConfigurator.configure(url);
}
else {
PropertyConfigurator.configure(url);
}
}
/**
When called wihtout arguments, this program will just print
<pre>
DEBUG [main] some.cat - Hello world.
</pre>
and exit.
<b>However, it can be called with a configuration file in XML or
properties format.
*/
static public void main(String[] args) {
if(args.length == 0) {
// Note that the appender is added to root but that the log
// request is made to an instance of MyLogger. The output still
// goes to System.out.
Logger root = Logger.getRootLogger();
Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");
root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));
}
else if(args.length == 1) {
if(args[0].endsWith("xml")) {
DOMConfigurator.configure(args[0]);
} else {
PropertyConfigurator.configure(args[0]);
}
} else {
usage("Incorrect number of parameters.");
}
try {
MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");
c.trace("Hello");
c.debug("Hello");
} catch(ClassCastException e) {
LogLog.error("Did you forget to set the factory in the config file?", e);
}
}
static void init(String portStr, String configFile) {
try {
port = Integer.parseInt(portStr);
} catch(java.lang.NumberFormatException e) {
e.printStackTrace();
usage("Could not interpret port number ["+ portStr +"].");
}
if(configFile.endsWith(".xml")) {
DOMConfigurator.configure(configFile);
} else {
PropertyConfigurator.configure(configFile);
}
}
static public void main(String[] args) throws Exception {
if(args.length != 5) {
usage("Wrong number of arguments.");
}
String tcfBindingName = args[0];
String topicBindingName = args[1];
String username = args[2];
String password = args[3];
String configFile = args[4];
if(configFile.endsWith(".xml")) {
DOMConfigurator.configure(configFile);
} else {
PropertyConfigurator.configure(configFile);
}
new JMSSink(tcfBindingName, topicBindingName, username, password);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
// Loop until the word "exit" is typed
System.out.println("Type \"exit\" to quit JMSSink.");
while(true){
String s = stdin.readLine( );
if (s.equalsIgnoreCase("exit")) {
System.out.println("Exiting. Kill the application if it does not exit "
+ "due to daemon threads.");
return;
}
}
}
/**
* Tests that triggeringPolicy element will set evaluator.
*/
public void testTrigger() {
DOMConfigurator.configure("input/xml/smtpAppender1.xml");
SMTPAppender appender = (SMTPAppender) Logger.getRootLogger().getAppender("A1");
TriggeringEventEvaluator evaluator = appender.getEvaluator();
assertTrue(evaluator instanceof MockTriggeringEventEvaluator);
}
protected void setUp() {
DOMConfigurator.configure("input/xml/SocketAppenderTestConfig.xml");
logger = Logger.getLogger(SocketAppenderTest.class);
primary = logger.getAppender("remote");
secondary = (LastOnlyAppender) Logger.getLogger(
"org.apache.log4j.net.SocketAppenderTestDummy").getAppender("lastOnly");
}