下面列出了org.apache.log4j.Logger#getLogger ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void internalInit(URL urlDefaultPropertiesFile, String sDefaultPropertiesFile, String logHost) {
//init logging
initLogging(logHost);
// print out the basic environment information to log4j interface - has to be after log4j initialization - issue #1911
Logger logger = Logger.getLogger(EngineInitializer.class);
LogUtils.printRuntimeHeader(logger);
LogUtils.printJvmInfo(logger);
//init framework constants
if (urlDefaultPropertiesFile != null) {
Defaults.init(urlDefaultPropertiesFile);
} else {
Defaults.init(sDefaultPropertiesFile);
}
//file manager initialisation
FileManager.init();
// create and register CloverJMX mbean for graph tracking
CloverJMX.registerMBean();
// create and register DebugJMX mbean for CTL debugging
DebugJMX.registerMBean();
}
@Test
public void jsonSourceMapperTest16() throws Exception {
log.info("test JsonSourceMapper with test validate event identifier");
log = Logger.getLogger(JsonSourceMapper.class);
UnitTestAppender appender = new UnitTestAppender();
log.addAppender(appender);
String streams = "" +
"@App:name('TestSiddhiApp')" +
"@source(type='inMemory', topic='stock', @map(type='json')) " +
"define stream FooStream (symbol string, price float, volume long); " +
"define stream BarStream (symbol string, price float, volume long); ";
String query = "" +
"from FooStream " +
"select * " +
"insert into BarStream; ";
SiddhiManager siddhiManager = new SiddhiManager();
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);
siddhiAppRuntime.start();
InMemoryBroker.publish("stock",
"{\"event1\":{\"symbol\":\"WSO2\",\"price\":52.6,\"volume\":100}}");
AssertJUnit.assertTrue(appender.getMessages()
.contains("Stream \"FooStream\" does not have an attribute named \"event1\""));
siddhiAppRuntime.shutdown();
}
/**
* base constructor
*
* @param uriPrefix
* the uriPrefix
* @param dc
* the dc
* @param pc
* the pc
* @param baseDirectory
* the base directory of the ontologies
* @param templateLibraryDomain
* the domain of the template library
*/
public WorkflowGenerationKB(Properties props, DataReasoningAPI dc,
ComponentReasoningAPI pc, ResourceAPI rc, String ldid) {
this.props = props;
this.request_id = ldid;
this.logger = Logger.getLogger(this.getClass().getName());
this.dc = dc;
this.pc = pc;
this.rc = rc;
this.tc = new TemplateReasoningKB(this);
this.dataNS = props.getProperty("lib.domain.data.url") + "#";
this.wNS = props.getProperty("ont.workflow.url") + "#";
this.exPrefix = props.getProperty("domain.executions.dir.url");
this.explanations = new ArrayList<String>();
}
@Test
public void samplesAreCreated_2Beans() throws Exception {
File rrdFile = createTempRRDFile();
Fake fakeBean = new Fake();
Fake fakeBean2 = new Fake();
MBeanServer beanServer = MBeanServerFactory.createMBeanServer();
beanServer.registerMBean(fakeBean, new ObjectName("java.lang:type=Memory"));
beanServer.registerMBean(fakeBean2, new ObjectName("sigar:Type=Mem"));
RRDSigarDataStore store = new RRDSigarDataStore(beanServer, rrdFile.getPath(), 4, Logger.getLogger("test"));
RrdDb dataBase = new RrdDb(rrdFile.getPath());
// sample 5 times every 10 seconds
long firstSampleTime = System.currentTimeMillis();
for (int i = 1; i <= 5; i++) {
store.sample(dataBase, firstSampleTime + i * TEN_SECONDS);
}
assertEquals((firstSampleTime + 5 * TEN_SECONDS) / 1000, dataBase.getLastUpdateTime());
assertEquals(42, dataBase.getDatasource("ValueMemory").getLastValue(), 0.001);
assertEquals(42, dataBase.getDatasource("ValueMem").getLastValue(), 0.001);
}
/**
* 始化
*/
public void init( Context context) {
logger = Logger.getLogger(CrashHandler.class);
mContext = context;
// 获取系统默认的 UncaughtException 处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该 CrashHandler 为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Logger log = Logger.getLogger("com.mobilefish.demo.test");
if (log != null) {
log.info("身份证 620503198801272195\n");
log.warn("IdCard=42050319820815801X DepositCard=6225750103374126 Transaction=1999.22\n");
}
} catch (Exception e) {
resp.getWriter().print(e);
}
}
@Override
public void activateOptions() {
try {
queue = new JdbmQueue<>( file );
} catch ( IOException e ) {
throw new IllegalStateException( e );
}
forward = Logger.getLogger( "audit.forward" );
forward.setAdditivity( false );
forwarder = new Forwarder();
forwarder.setDaemon( true );
forwarder.start();
}
/** */
public Worker(Ignite ignite, long startPosition, long endPosition) {
this.ignite = ignite;
this.log = Logger.getLogger(loggerName());
this.startPosition = startPosition;
this.endPosition = endPosition;
}
@Test
public void test() {
String testLog = "testing";
Logger logger = Logger.getLogger(TestLoggingEventStringSerde.class);
LoggingEvent log = new LoggingEvent(logger.getName(), logger, logger.getLevel(), testLog, null);
LoggingEventStringSerde loggingEventStringSerde = new LoggingEventStringSerde();
assertNull(loggingEventStringSerde.fromBytes(null));
assertNull(loggingEventStringSerde.toBytes(null));
assertArrayEquals(testLog.getBytes(), loggingEventStringSerde.toBytes(log));
// only the log messages are guaranteed to be equivalent
assertEquals(log.getMessage().toString(), loggingEventStringSerde.fromBytes(testLog.getBytes()).getMessage().toString());
}
void initLog4j() {
if (mLogger == null) {
mLogger = Logger.getLogger("android-log");
String fileName = LogConfig.sDiskCachePath + File.separator + sLogFile;
mLog4jConfig = new Log4jConfig(fileName);
mLog4jConfig.setMaxFileSize(LogConfig.sMaxLogFileSize);
mLog4jConfig.configure(mLogger);
}
}
public Log4jSyslogBackLogHandler(String loggerName, LoggerFactory loggerFactory, boolean appendReason) {
if (loggerName == null) {
throw new SyslogRuntimeException("loggerName cannot be null");
}
if (loggerFactory == null) {
throw new SyslogRuntimeException("loggerFactory cannot be null");
}
this.logger = Logger.getLogger(loggerName, loggerFactory);
this.appendReason = appendReason;
initialize();
}
public HttpServletSupport()
{
logger_ = Logger.getLogger(getClass());
}
/**
*
* @throws Exception
*/
public CompServer(String configURL) throws Exception {
// initialise dir, config and logging
DirectoryLayout.initialiseServerLayout(
Arrays.asList(new String[] {"comp"}), configURL);
Configuration configuration = DirectoryLayout.getInstance().getConfiguration();
// Initialise instance variables
this.scheduleTimeout = configuration.getInt("comp", "schedule-timeout");
this.offerDelay = configuration.getInt("comp", "offer-delay");
this.timeoutCheckInterval = configuration.getInt("comp", "timeout-check-interval");
this.compAvailableInterval = configuration.getInt("comp", "comp-available-interval");
this.sweepWorkDir= configuration.getBoolean("comp", "sweep-work-dir");
this.maxJobs = configuration.getInt("comp", "max-jobs");
this.localFilebrokerPath = nullIfEmpty(configuration.getString("comp", "local-filebroker-user-data-path"));
this.overridingFilebrokerIp = nullIfEmpty(configuration.getString("comp", "overriding-filebroker-ip"));
this.moduleFilterName = configuration.getString("comp", "module-filter-name");
this.moduleFilterMode = configuration.getString("comp", "module-filter-mode");
this.monitoringInterval = configuration.getInt("comp", "resource-monitoring-interval");
this.jobTimeout = configuration.getInt("comp", "job-timeout");
logger = Logger.getLogger(CompServer.class);
loggerJobs = Logger.getLogger("jobs");
loggerStatus = Logger.getLogger("status");
// initialize working directory
logger.info("starting compute service...");
this.workDir = DirectoryLayout.getInstance().getJobsDataDirBase(id);
// initialize executor service
this.executorService = Executors.newCachedThreadPool();
// initialize runtime and tools
FileInputStream runtimesStream = new FileInputStream(new File(DirectoryLayout.getInstance().getConfDir(), "runtimes.xml"));
this.runtimeRepository = new RuntimeRepository(this.workDir, runtimesStream);
// initialize toolbox client
String toolboxUrl = configuration.getString("messaging", "toolbox-url");
this.toolboxClient = new ToolboxClientComp(toolboxUrl);
logger.info("toolbox client connecting to: " + toolboxUrl);
// initialize timeout checker
timeoutTimer = new Timer(true);
timeoutTimer.schedule(new TimeoutTimerTask(), timeoutCheckInterval, timeoutCheckInterval);
compAvailableTimer = new Timer(true);
compAvailableTimer.schedule(new CompAvailableTask(), compAvailableInterval, compAvailableInterval);
resourceMonitor = new ResourceMonitor(this, monitoringInterval);
// initialize communications
this.endpoint = new JMSMessagingEndpoint(this);
MessagingTopic compTopic = endpoint.createTopic(Topics.Name.AUTHORIZED_MANAGED_REQUEST_TOPIC, AccessMode.READ);
compTopic.setListener(this);
managerTopic = endpoint.createTopic(Topics.Name.JOB_LOG_TOPIC, AccessMode.WRITE);
MessagingTopic filebrokerAdminTopic = endpoint.createTopic(Topics.Name.COMP_ADMIN_TOPIC, AccessMode.READ);
filebrokerAdminTopic.setListener(new CompAdminMessageListener());
fileBroker = new JMSFileBrokerClient(this.endpoint.createTopic(Topics.Name.AUTHORISED_FILEBROKER_TOPIC, AccessMode.WRITE), this.localFilebrokerPath, this.overridingFilebrokerIp);
jobmanagerTopic = endpoint.createTopic(Topics.Name.JOBMANAGER_TOPIC, AccessMode.WRITE);
// create keep-alive thread and register shutdown hook
KeepAliveShutdownHandler.init(this);
sendCompAvailable();
logger.info("comp is up and running [" + ApplicationConstants.VERSION + "]");
logger.info("[mem: " + SystemMonitorUtil.getMemInfo() + "]");
}
private LogUtil(Class<?> clazz){
configLogProperties();
log = Logger.getLogger(clazz);
}
@Override
public AbstractLogHandler registerLogHandler(Map<String, String> logConfig) throws IOException {
String logName = logConfig.get("logName");
String fileName = logConfig.get("fileName");
boolean flush = Boolean.valueOf(logConfig.get("flush"));
boolean append = Boolean.valueOf(logConfig.get("append"));
String rotation = logConfig.get("rotation");
boolean isAbstractLogger = Boolean.valueOf(logConfig.get("abstractLogger"));
String logFormatPattern = logConfig.get("format");
boolean isTraceLogger = false;
String isTraceLoggerString = logConfig.get("isTraceLogger");
if (isTraceLoggerString != null) {
isTraceLogger = Boolean.valueOf(isTraceLoggerString);
}
//If the log is abstract, then the concrete logger creation step registers
//the appender
//If it is a real implementation here, then we'll associate the log4j appender with
//the logger
Log4JLogHandler handler = null;
if (logFormatPattern != null && !logFormatPattern.equals("")) {
handler = new Log4JLogHandler(fileName, flush, append, rotation, logFormatPattern, isAbstractLogger);
} else {
handler = new Log4JLogHandler(fileName, flush, append, rotation, isAbstractLogger);
}
if (!isAbstractLogger) {
if (logName == null) {
throw new IllegalArgumentException("logName mustn't be null for concrete log implementation. " + fileName);
}
handler.associateAppenderWithLogger(logName);
if (isTraceLogger) {
Logger l = Logger.getLogger(logName);
l.setLevel(Level.TRACE);
}
}
return handler;
}
@Test(dependsOnMethods = "faultStreamTest5")
public void faultStreamTest6() throws InterruptedException {
log.info("faultStreamTest6-Tests logging by default when fault handling is not configured "
+ "explicitly at sink level during publishing failures.");
SiddhiManager siddhiManager = new SiddhiManager();
String siddhiApp = "" +
"@OnError(action='stream')" +
"define stream cseEventStream (symbol string, price float, volume long);" +
"\n" +
"@sink(type='inMemory', topic='{{symbol}}', @map(type='passThrough')) " +
"define stream outputStream (symbol string, price float, sym1 string);" +
"\n" +
"@info(name = 'query1') " +
"from cseEventStream " +
"select symbol, price , symbol as sym1 " +
"insert into outputStream ;" +
"";
SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp);
siddhiAppRuntime.addCallback("outputStream", new StreamCallback() {
@Override
public void receive(Event[] events) {
EventPrinter.print(events);
Assert.assertTrue(events[0].getData(0) != null);
}
});
InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream");
siddhiAppRuntime.start();
Logger logger = Logger.getLogger(Sink.class);
UnitTestAppender appender = new UnitTestAppender();
logger.addAppender(appender);
try {
inputHandler.send(new Object[]{"IBM", 0f, 100L});
AssertJUnit.assertTrue(appender.getMessages().contains("Dropping event at Sink 'inMemory' at"));
} catch (Exception e) {
Assert.fail("Unexpected exception occurred when testing.", e);
} finally {
logger.removeAppender(appender);
siddhiAppRuntime.shutdown();
}
}
public static Logger l() {
return Logger.getLogger("sparkboost");
}
/**
* Validate an internal redirect URL to avoid internal open redirect. (Use this function only if the use of internal url redirect keys is not possible. For
* external url redirection control, use the plugin plugin-verifybackurl)
*
* the url should : - not be blank (null or empty string or spaces) - not start with "http://" or "https://" or "//" OR match the base URL or any URL in the
* pattern list
*
* example with a base url "https://lutece.fr/ : - valid : myapp/jsp/site/Portal.jsp , Another.jsp , https://lutece.fr/myapp/jsp/site/Portal.jsp - invalid :
* http://anothersite.com , https://anothersite.com , //anothersite.com , file://my.txt , ...
*
*
* @param strUrl
* the Url to validate
* @param request
* the current request (containing the baseUrl)
* @param strAntPathMatcherPatterns
* a comma separated list of AntPathMatcher patterns, as "http://**.lutece.com,https://**.lutece.com"
* @return true if valid
*/
public static boolean isInternalRedirectUrlSafe( String strUrl, HttpServletRequest request, String strAntPathMatcherPatterns )
{
if ( StringUtils.isBlank( strUrl ) )
{
return true; // this is not a valid redirect Url, but it is not unsafe
}
// filter schemes
boolean [ ] conditions = new boolean [ ] {
!strUrl.startsWith( "//" ), !strUrl.startsWith( "http:" ), !strUrl.startsWith( "https:" ), !strUrl.contains( "://" ),
!strUrl.startsWith( "javascript:" )
};
if ( BooleanUtils.and( conditions ) )
{
return true; // should be a relative path
}
// compare with current baseUrl
if ( strUrl.startsWith( AppPathService.getBaseUrl( request ) ) )
{
return true;
}
// compare with allowed url patterns
if ( !StringUtils.isBlank( strAntPathMatcherPatterns ) )
{
AntPathMatcher pathMatcher = new AntPathMatcher( );
String [ ] strAntPathMatcherPatternsTab = strAntPathMatcherPatterns.split( CONSTANT_COMMA );
for ( String pattern : strAntPathMatcherPatternsTab )
{
if ( pattern != null && pathMatcher.match( pattern, strUrl ) )
{
return true;
}
}
}
// the Url does not match the allowed patterns
Logger logger = Logger.getLogger( LOGGER_NAME );
logger.warn( "SECURITY WARNING : OPEN_REDIRECT DETECTED : " + dumpRequest( request ) );
return false;
}
/**
* @see org.ow2.proactive.authentication.Loggable#getLogger()
*/
public Logger getLogger() {
return Logger.getLogger(SchedulerConnection.class);
}
@ManagedOperation(description = "Sets the level of logger (p1) to level (p2)")
public void setLogLevel(String loggerName, String level) {
Logger l = loggerName == null? Logger.getRootLogger() : Logger.getLogger(loggerName);
logger.info("Logger {}: level customised to {}", l.getName(), level);
l.setLevel(Level.toLevel(level));
}