下面列出了怎么用org.apache.log4j.BasicConfigurator的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws InterruptedException {
// Configure console logging
BasicConfigurator.configure();
String topic = "publishing_to_topic";
if (args.length > 0) {
topic = args[0];
}
System.out.println("Publishing to topic " + topic);
while (!Thread.currentThread().isInterrupted()) {
String s = RandomStringUtils.randomAlphanumeric(10);
PubSub.publish(topic, s);
Thread.sleep(1000);
}
}
public static void init(Level level)
{
if (!alreadyInitialized)
{
synchronized(Log4jInit.class)
{
if (!alreadyInitialized)
{
final Layout layout = new VerySimpleLayout(); // new PatternLayout("%p [%t] %m%n");
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(level);
Enumeration<?> enumAppenders = Logger.getRootLogger().getAllAppenders();
while (enumAppenders.hasMoreElements())
{
Appender appender = (Appender) enumAppenders.nextElement();
appender.setLayout(layout);
}
alreadyInitialized = true;
}
}
}
}
public static void main(String[] args) {
BasicConfigurator.configure();
HelloWorldHystrixObservableCommand command = new HelloWorldHystrixObservableCommand("kronchan");
Observable<String> observable = command.observe();
observable.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
log.info("completed");
}
@Override
public void onError(Throwable throwable) {
log.error(throwable.getMessage());
}
@Override
public void onNext(String o) {
log.info("Observe onNext: {}", o);
}
});
}
@BeforeSuite
public void setProps() {
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d{HH:mm:ss,SSS} [%t] %p %c %x - %m%n")));
Logger.getRootLogger().setLevel(Level.INFO);
Logger.getLogger(SimpleEVCacheTest.class).setLevel(Level.DEBUG);
Logger.getLogger(Base.class).setLevel(Level.DEBUG);
Logger.getLogger(EVCacheImpl.class).setLevel(Level.DEBUG);
Logger.getLogger(EVCacheClient.class).setLevel(Level.DEBUG);
Logger.getLogger(EVCacheClientPool.class).setLevel(Level.DEBUG);
final Properties props = getProps();
props.setProperty("EVCACHE_TEST.use.simple.node.list.provider", "true");
props.setProperty("EVCACHE_TEST.EVCacheClientPool.readTimeout", "1000");
props.setProperty("EVCACHE_TEST.EVCacheClientPool.bulkReadTimeout", "1000");
props.setProperty("EVCACHE_TEST.max.read.queue.length", "100");
props.setProperty("EVCACHE_TEST.operation.timeout", "10000");
props.setProperty("EVCACHE_TEST.throw.exception", "false");
int maxThreads = 2;
final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(100000);
pool = new ThreadPoolExecutor(maxThreads * 4, maxThreads * 4, 30, TimeUnit.SECONDS, queue);
pool.prestartAllCoreThreads();
}
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(String[] args) {
BasicConfigurator.configure();
String mainDir = "D:\\Data\\JedAIdata\\datasets\\dirtyErDatasets\\";
final String[] datasets = {"census", "cddb", "cora"};
for (String dataset : datasets) {
System.out.println("\n\n\n\n\nCurrent dataset\t:\t" + dataset);
final EntitySerializationReader inReaderD1 = new EntitySerializationReader(mainDir + dataset + "Profiles");
final List<EntityProfile> profiles = inReaderD1.getEntityProfiles();
System.out.println("Profiles D1\t:\t" + profiles.size());
final AttributeValueClustering avc = new AttributeValueClustering(RepresentationModel.CHARACTER_TRIGRAMS, SimilarityMetric.ENHANCED_JACCARD_SIMILARITY);
final AttributeClusters[] clusters = avc.getClusters(profiles);
for (int j = 0; j < clusters.length; j++) {
System.out.println("\nDataset\t:\t" + (j + 1));
for (int k = 0; k < clusters[j].getNoOfClusters(); k++) {
System.out.println(k + "\t" + clusters[j].getClusterEntropy(k));
}
}
}
}
@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("*****************************************************************************************");
}
}
@Test
public void testLog4JAppendLongs() throws Exception {
BasicConfigurator.configure();
org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("com.db.fxpricing.Logger");
for(long i = 0; i < WARMUP_COUNT; i++)
log.info("value:" + i + " " + i + " " + i + " " + i + " " + i
+ i + " " + i + " " + i + " " + i + " " + i);
Thread.sleep(1000L);
objectCounting.set(true);
for(long i = 0; i < TEST_COUNT; i++)
log.info("value:" + i + " " + i + " " + i + " " + i + " " + i
+ i + " " + i + " " + i + " " + i + " " + i);
Thread.sleep(500L);
printState("log4j-longs");
}
@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("*****************************************************************************************");
}
}
/**
* Enable or disable debugging
*
* @param debugging
*/
public void setDebugging(boolean debugging)
{
this.debugging = debugging;
if (debugging)
{
Thread.setDefaultUncaughtExceptionHandler(debugAppender);
BasicConfigurator.configure(debugAppender);
}
else
{
// Turn off everything before disabling the debug tab
postClock.stop();
postMessagesButton.setSelected(false);
drawTextGridBox.setSelected(false);
drawBorderGridBox.setSelected(false);
chat.repaint();
Thread.setDefaultUncaughtExceptionHandler(null);
Logger.getRootLogger().removeAppender(debugAppender);
}
}
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.");
}
}
@Before
public void setUp() {
BasicConfigurator.configure();
PowerMockito.mockStatic(ComponentManager.class);
// A mock component manager.
when(ComponentManager.get(any(Class.class))).then(new Answer<Object>() {
private Map<Class, Object> mocks = new HashMap<>();
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Class classToMock = (Class) invocation.getArguments()[0];
return mocks.computeIfAbsent(classToMock, k -> mock(classToMock));
}
});
when(ComponentManager.get(SessionManager.class).getCurrentSession()).thenReturn(mock(Session.class));
when(formattedText.getDecimalSeparator()).thenReturn(".");
when(formattedText.getNumberFormat()).thenReturn(NumberFormat.getInstance(Locale.ENGLISH));
assignmentAction = new AssignmentAction();
Mockito.when(ComponentManager.get(AssignmentService.class)).thenReturn(assignmentService);
}
@Test
public void testProcess() {
BasicConfigurator.configure();
// DicomNode calling = new DicomNode("WEA-SCU");
// DicomNode called = new DicomNode("DCM4CHEE", "localhost", 11112);
// AdvancedParams params = new AdvancedParams();
// TlsOptions tls =
// new TlsOptions(true, "/home/dcm4chee/dcm4chee-2.18.0-mysql/server/default/conf/keystore.jks", "JKS",
// "keypwd", "keypwd", "/home/dcm4chee/dcm4chee-2.18.0-mysql/server/default/conf/trust.jks", "JKS",
// "trustpwd");
// params.setTlsOptions(tls);
// DicomState state = Echo.process(params, calling, called);
DicomNode calling = new DicomNode("WEASIS-SCU");
DicomNode called = new DicomNode("DICOMSERVER", "dicomserver.co.uk", 11112);
DicomState state = Echo.process(null, calling, called);
// Should never happen
Assert.assertNotNull(state);
System.out.println("DICOM Status:" + state.getStatus());
System.out.println(state.getMessage());
// see org.dcm4che3.net.Status
// See server log at http://dicomserver.co.uk/logs/
Assert.assertThat(state.getMessage(), state.getStatus(), IsEqual.equalTo(Status.Success));
}
public void init() {
try {
Properties tckProperties = new Properties();
InputStream inStreamLog4j = TestHarness.class.getResourceAsStream("/log4j.properties");
logger.info("Input Stream = " + inStreamLog4j);
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (Exception e) {
e.printStackTrace();
BasicConfigurator.configure();
}
logger.debug("log4j configured");
String lf = System.getProperties().getProperty(LOG_FILE_NAME);
if (lf != null) {
logFileName = lf;
}
// If a print writer is already created, then just use it.
try {
logger.addAppender(new FileAppender(new SimpleLayout(), logFileName));
} catch (FileNotFoundException fnfe) {
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public DBDatasource () {
cache = new HashMap<>();
seen = new HashSet<>();
log = new Log ("jdbc", Log.INFO);
Appender app = new DBaseAppender (log);
app.addFilter (new DBaseFilter ());
BasicConfigurator.configure (app);
}
@Before
public void setUp() throws Exception {
BasicConfigurator.configure();
Injector injector = Guice.createInjector(new SwaggerApiImporterTestModule());
client = injector.getInstance(ApiGatewaySdkApiImporter.class);
}
public static void main(String[] args) {
BasicConfigurator.configure();
ElkLayoutEngine.initialize(new LayeredMetaDataProvider());
GLSPServerLauncher launcher;
if (args.length == 1 && args[0].equals("websocket")) {
launcher = new WebsocketServerLauncher(new WorkflowGLSPModule(), "/workflow");
launcher.start("localhost", 8081);
} else {
launcher = new DefaultGLSPServerLauncher(new WorkflowGLSPModule());
launcher.start("localhost", 5007);
}
}
public Log(String name, boolean isDebug) {
logger = Logger.getLogger(name);
File file = new File("log4j.properties");
if (!file.exists()) {
this.debug = false;
BasicConfigurator.configure();
logger.warn("The configuration file of log4j does not exist, please refer to tencentcloud-sdk-java/log4j.properties for configuration.");
} else {
this.debug = isDebug;
PropertyConfigurator.configure("log4j.properties");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("*********************");
Logger.getRootLogger().removeAllAppenders();
BasicConfigurator.configure();
registerShutdownHook();
/* Load config */
try {
File configFile = new File(getServletContext().getRealPath(CONFIG_PATH));
Properties props = new Properties();
props.load(new FileReader(configFile));
props.load(new FileReader(configFile));
ProcessingQueue.getInstance().configure(props);
/* Start all processing threads */
for (Runnable runnable : ProcessingQueue.getInstance().getRunnables()) {
Thread thread = ThreadManager.createBackgroundThread(runnable);
thread.start();
}
} catch (Exception e) {
throw new IOException("Could not create processing threads", e);
}
logger.info("App started");
}
public static void main(String[] args) {
BasicConfigurator.configure();
// 每个 command 实例只能使用一次
// 以同步堵塞方式执行run()
HelloWorldHystrixCommand excuteCommand = new HelloWorldHystrixCommand("Excute");
String excuteResult = excuteCommand.execute();
System.out.println("使用 excute 执行的结果 " + excuteResult);
// 以异步非堵塞方式执行run()
HelloWorldHystrixCommand queueCommand = new HelloWorldHystrixCommand("Queue");
Future<String> queueFuture = queueCommand.queue();
// 不会阻塞直接返回一个 Future
String queueResult = null;
for (;;) {
if (queueFuture.isDone()) {
try {
queueResult = queueFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
break;
}
}
}
System.out.println("使用 queue 的异步方式获取的结果:" + queueResult);
}
public void init() {
try {
Properties tckProperties = new Properties();
InputStream inStreamLog4j = AbstractSctpBase.class.getResourceAsStream("/log4j.properties");
System.out.println("Input Stream = " + inStreamLog4j);
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (IOException e) {
e.printStackTrace();
BasicConfigurator.configure();
}
logger.debug("log4j configured");
String lf = System.getProperties().getProperty(LOG_FILE_NAME);
if (lf != null) {
logFileName = lf;
}
// If already created a print writer then just use it.
try {
logger.addAppender(new FileAppender(new SimpleLayout(), logFileName));
} catch (FileNotFoundException fnfe) {
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
@Test
public void roundTrip() throws Exception {
BasicConfigurator.configure();
final String originalFileData;
{
InputStream in = new FileInputStream("src/test/resources/com/moss/ach/file/rck.ach");
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 10]; //10k buffer
for(int numRead = in.read(buffer); numRead!=-1; numRead = in.read(buffer)){
out.write(buffer, 0, numRead);
}
in.close();
out.close();
originalFileData = new String(out.toByteArray());
}
AchFileFormat file = new AchFileFormatReader(new StringReader(originalFileData)).read();
StringWriter writer = new StringWriter();
new AchFileFormatWriter(file, writer).write();
Assert.assertEquals(originalFileData, writer.getBuffer().toString());
}
public static void main(String[] args) {
BasicConfigurator.configure();
String mainDirectory = "data" + File.separator + "dirtyErDatasets" + File.separator;
String[] datasets = {"abtBuy", "amazonGp", "cddb", "census", "cora", "dblpAcm", "dblpScholar", "movies", "restaurant"};
for (String dataset : datasets) {
System.out.println("\n\n\n\nCurrent dataset\t:\t" + dataset);
IEntityReader eReader = new EntitySerializationReader(mainDirectory + dataset + "Profiles");
List<EntityProfile> profiles = eReader.getEntityProfiles();
System.out.println("Input Entity Profiles\t:\t" + profiles.size());
IGroundTruthReader gtReader = new GtSerializationReader(mainDirectory + dataset + "IdDuplicates");
final AbstractDuplicatePropagation duplicatePropagation = new UnilateralDuplicatePropagation(gtReader.getDuplicatePairs(eReader.getEntityProfiles()));
System.out.println("Existing Duplicates\t:\t" + duplicatePropagation.getDuplicates().size());
for (BlockBuildingMethod blbuMethod : BlockBuildingMethod.values()) {
float time1 = System.currentTimeMillis();
System.out.println("\n\nCurrent blocking metohd\t:\t" + blbuMethod);
IBlockBuilding blockBuildingMethod = BlockBuildingMethod.getDefaultConfiguration(blbuMethod);
System.out.println("Block Building...");
List<AbstractBlock> blocks = blockBuildingMethod.getBlocks(profiles, null);
float time2 = System.currentTimeMillis();
BlocksPerformance blStats = new BlocksPerformance(blocks, duplicatePropagation);
blStats.setStatistics();
blStats.printStatistics(time2 - time1, blockBuildingMethod.getMethodConfiguration(), blockBuildingMethod.getMethodName());
}
}
}
/**
Send a "RollOver" message to
<code>ExternallyRolledFileAppender</code> on <code>host</code>
and <code>port</code>.
*/
public
static
void main(String argv[]) {
BasicConfigurator.configure();
if(argv.length == 2)
init(argv[0], argv[1]);
else
usage("Wrong number of arguments.");
roll();
}
@BeforeClass
public void setUp() throws IOException {
BasicConfigurator.configure();
this.fs = FileSystem.getLocal(new Configuration());
this.path = new Path("MRJobLockTest");
if (!this.fs.exists(this.path)) {
this.fs.mkdirs(this.path);
}
}
@BeforeClass
public static void setJobDescriptorcUri() throws Exception {
jobDescriptorUri = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_update_variables.xml")
.toURI();
jobDescriptorNoVariablesUri = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_no_variables.xml")
.toURI();
jobDescriptorSysPropsUri = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_update_variables_using_system_properties.xml")
.toURI();
jobDescriptorWithMetadata = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_with_metadata.xml")
.toURI();
jobDescriptorWithEmptyMetadata = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_with_empty_metadata.xml")
.toURI();
jobDescriptorWithUnresolvedGenericInfoAndVariables = TestStaxJobFactory.class.getResource("job_with_unresolved_generic_info_and_variables.xml")
.toURI();
jobDescriptorWithGlobalVariablesAndGenericInfo = TestStaxJobFactory.class.getResource("/org/ow2/proactive/scheduler/common/job/factories/job_with_global_variables_and_gi.xml")
.toURI();
jobDescriptorAttrDefGenericInformationXmlElement = TestStaxJobFactory.class.getResource("job_attr_def_generic_information_xml_element.xml")
.toURI();
jobDescriptorAttrDefParameterXmlElement = TestStaxJobFactory.class.getResource("job_attr_def_parameter_xml_element.xml")
.toURI();
jobDescriptorAttrDefVariableXmlElement = TestStaxJobFactory.class.getResource("job_attr_def_variable_xml_element.xml")
.toURI();
jobDescriptorTaskVariable = TestStaxJobFactory.class.getResource("task_variables.xml").toURI();
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure();
}
public void init() {
try {
Properties tckProperties = new Properties();
InputStream inStreamLog4j = UlLowLevel.class.getResourceAsStream("log4j.properties");
System.out.println("Input Stream = " + inStreamLog4j);
Properties propertiesLog4j = new Properties();
try {
propertiesLog4j.load(inStreamLog4j);
PropertyConfigurator.configure(propertiesLog4j);
} catch (IOException e) {
e.printStackTrace();
BasicConfigurator.configure();
}
logger.debug("log4j configured");
String lf = System.getProperties().getProperty(LOG_FILE_NAME);
if (lf != null) {
logFileName = lf;
}
// If already created a print writer then just use it.
try {
logger.addAppender(new FileAppender(new SimpleLayout(), logFileName));
} catch (FileNotFoundException fnfe) {
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
BasicConfigurator.configure();
Logger.getLogger(CompositeMetadataProviderImpl.class).setLevel(Level.DEBUG);
Logger.getLogger(SpringMetadataProviderImpl.class).setLevel(Level.DEBUG);
metadataProvider = new EclipseLinkJpaMetadataProviderImpl();
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("krad-data-unit-test");
metadataProvider.setEntityManager(entityManagerFactory.createEntityManager());
}
@BeforeClass
public static void initClass() {
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.WARN);
Logger.getLogger("com.indeed").setLevel(Level.DEBUG);
}
public static Logger getLogger(final Class<?> cls) {
boolean rootIsConfigured = Logger.getRootLogger().getAllAppenders().hasMoreElements();
if (!rootIsConfigured) {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.INFO);
Appender appender = (Appender) Logger.getRootLogger().getAllAppenders().nextElement();
appender.setLayout(new PatternLayout(" %-5p %d [%t] %C{1}: %m%n"));
}
return Logger.getLogger(cls);
}