use of java.util.logging.Logger in project pcgen by PCGen.
the class Logging method errorPrintLocalised.
/**
* Print a localized error message including parameter substitution. The
* method will issue a beep if the application is running in Debug mode.
* <p>
* This method accepts a variable number of parameters and will replace
* {@code {argno}} in the string with each passed paracter in turn.
*
* @param aKey
* A key for the localized string in the language bundle
* @param varargs
* Variable number of parameters to substitute into the string
*/
public static void errorPrintLocalised(final String aKey, Object... varargs) {
if (debugMode) {
s_TOOLKIT.beep();
}
final String msg = LanguageBundle.getFormattedString(aKey, varargs);
Logger l = getLogger();
if (l.isLoggable(ERROR)) {
l.log(ERROR, msg);
}
}
use of java.util.logging.Logger in project pratilipi by Pratilipi.
the class UserPratilipiDataUtil method getContentsReadList.
/**
* @param userId
* @return List of pratilipi Ids read (completed) by the user
*/
public static List<Long> getContentsReadList(Long userId) {
Logger logger = Logger.getLogger(UserPratilipiDataUtil.class.getSimpleName());
List<Long> contentsReadList = new ArrayList<>();
DataAccessor dataAccessor = DataAccessorFactory.getDataAccessor();
List<UserPratilipi> userPratilipiList = dataAccessor.getUserPratilipiList(userId, null, null, null).getDataList();
if (userPratilipiList == null || userPratilipiList.size() == 0)
return null;
logger.log(Level.INFO, "LIST OF READ CONTENTS");
for (UserPratilipi userPratilipi : userPratilipiList) {
if (userPratilipi.getLastOpenedDate() != null) {
contentsReadList.add(userPratilipi.getPratilipiId());
logger.log(Level.INFO, "PRATILIPI ID : " + userPratilipi.getPratilipiId());
}
}
return contentsReadList;
}
use of java.util.logging.Logger in project ACS by ACS-Community.
the class AcsLogger method log.
/**
* Logs the given <code>LogRecord</code>.
* The record can be modified or dropped by the optional filters provided in {@link #addLogRecordFilter(alma.acs.logging.AcsLogger.LogRecordFilter)}.
* <p>
* Adding of context information:
* <ul>
* <li> If the LogRecord has a parameter that is a map which contains additional information
* about the line of code, thread, etc., the log record will be taken as provided, and no context
* information will be added. This can be useful if
* <ul>
* <li> the log record was reconstructed from a remote error by the ACS error handling code
* (see <code>AcsJException</code>), or
* <li> if in very exceptional cases application code needs to manipulate such information by hand.
* </ul>
* <li> otherwise, context information is inferred, similar to {@link LogRecord#inferCaller()},
* but additionally including thread name and line of code.
* </ul>
* Note that by overloading this method, we intercept all logging activities of the base class.
*
* @see java.util.logging.Logger#log(java.util.logging.LogRecord)
*/
public void log(LogRecord record) {
// Both Level.OFF and AcsLogLevel.OFF use the same value INTEGER.max, but we anyway check for both.
if (record.getLevel().intValue() == Level.OFF.intValue() || record.getLevel().intValue() == AcsLogLevel.OFF.intValue()) {
throw new IllegalArgumentException("Level OFF must not be used for actual logging, but only for level filtering.");
}
StopWatch sw_all = null;
if (PROFILE) {
sw_all = new StopWatch(null);
}
// Level could be null and must then be inherited from the ancestor loggers,
// e.g. during JDK shutdown when the log level is nulled by the JDK LogManager
Logger loggerWithLevel = this;
while (loggerWithLevel != null && loggerWithLevel.getLevel() == null && loggerWithLevel.getParent() != null) {
loggerWithLevel = loggerWithLevel.getParent();
}
int levelValue = -1;
if (loggerWithLevel.getLevel() == null) {
// Just to be safe I add the necessary checks and warning message that improve over a NPE.
if (!noLevelWarningPrinted) {
System.out.println("Logger configuration error: no log level found for logger " + getLoggerName() + " or its ancestors. Will use Level.ALL instead.");
noLevelWarningPrinted = true;
}
// @TODO: decide if resorting to ALL is desirable, or to use schema defaults, INFO, etc
levelValue = Level.ALL.intValue();
} else {
// level is fine, reset the flag to print the error message again when log level is missing.
noLevelWarningPrinted = false;
levelValue = loggerWithLevel.getLevel().intValue();
}
// The same check will be repeated by the base class implementation of this method that gets called afterwards.
if (record.getLevel().intValue() < levelValue || levelValue == offValue) {
return;
}
// modify the logger name if necessary
if (loggerName != null) {
record.setLoggerName(loggerName);
}
// check if this record already has the context data attached which ACS needs but the JDK logging API does not provide
LogParameterUtil paramUtil = new LogParameterUtil(record);
Map<String, Object> specialProperties = paramUtil.extractSpecialPropertiesMap();
if (specialProperties == null) {
// we prepend the special properties map to the other parameters
specialProperties = LogParameterUtil.createPropertiesMap();
List<Object> paramList = paramUtil.getNonSpecialPropertiesMapParameters();
paramList.add(0, specialProperties);
record.setParameters(paramList.toArray());
String threadName = Thread.currentThread().getName();
specialProperties.put(LogParameterUtil.PARAM_THREAD_NAME, threadName);
specialProperties.put(LogParameterUtil.PARAM_PROCESSNAME, this.processName);
specialProperties.put(LogParameterUtil.PARAM_SOURCEOBJECT, this.sourceObject);
// Get the stack trace
StackTraceElement[] stack = (new Throwable()).getStackTrace();
// search for the first frame before the "Logger" class.
int ix = 0;
boolean foundNonLogFrame = false;
while (ix < stack.length) {
StackTraceElement frame = stack[ix];
String cname = frame.getClassName();
if (!foundNonLogFrame && !loggerClassNames.contains(cname)) {
// We've found the relevant frame.
record.setSourceClassName(frame.getFileName());
record.setSourceMethodName(frame.getMethodName());
int lineNumber = frame.getLineNumber();
specialProperties.put(LogParameterUtil.PARAM_LINE, Long.valueOf(lineNumber));
foundNonLogFrame = true;
if (this.callStacksToBeIgnored.isEmpty()) {
// performance optimization: avoid checking all "higher" stack frames
break;
}
}
if (foundNonLogFrame) {
if (callStacksToBeIgnored.contains(concatenateIgnoreLogData(cname, frame.getMethodName()))) {
//System.out.println("Won't log record with message " + record.getMessage());
return;
}
}
ix++;
}
// We haven't found a suitable frame, so just punt. This is
// OK as we are only committed to making a "best effort" here.
}
StopWatch sw_afterAcsLogger = null;
if (PROFILE) {
sw_afterAcsLogger = sw_all.createStopWatchForSubtask("afterAcsLogger");
LogParameterUtil logParamUtil = new LogParameterUtil(record);
logParamUtil.setStopWatch(sw_afterAcsLogger);
}
try {
// Let the delegate or Logger base class handle the rest.
if (delegate != null) {
delegate.log(record);
} else {
super.log(record);
}
// Calculate statistics
if (stats.getDisableStatistics() == false) {
// Increment number of messages logged (only if log has succeded)
stats.incrementNumberOfMessages();
// Calculate time since last calculation of the logging statistics
float timeElapsedSinceLastStatistics = (float) (System.currentTimeMillis() - stats.getLastStatisticsRepportTime()) / (float) (1000);
// Determine if statistics are to be generated
if (timeElapsedSinceLastStatistics >= (float) (stats.getStatisticsCalculationPeriod())) {
// Calculate statistics
stats.calculateLoggingStatistics();
// Reset statistics
stats.resetStatistics();
// Print statistics logs
AcsLogRecord logItem;
Map<String, String> addedData = new HashMap<String, String>();
addedData.put("StatisticsIdentification", stats.getStatisticsIdentification());
addedData.put("LoggerId", getName());
addedData.put("LastPeriodDuration", String.valueOf(stats.getActualStatisticsPeriod()));
addedData.put("LastPeriodNumberOfMessages", String.valueOf(stats.getLastPeriodNumberOfMessages()));
addedData.put("StatisticsGranularity", String.valueOf(stats.getStatisticsGranularity()));
addedData.put("MessageStatistics", String.valueOf(stats.getMessageStatistics()));
addedData.put("MessageIncrement", String.valueOf(stats.getMessageIncrement()));
addedData.put("LastPeriodNumberOfErrorMessages", String.valueOf(stats.getLastPeriodNumberOfLogErrors()));
addedData.put("ErrorMessageStatistics", String.valueOf(stats.getErrorStatistics()));
addedData.put("ErrorMessageIncrement", String.valueOf(stats.getErrorIncrement()));
logItem = createAcsLogRecord(Level.INFO, "LOGGING STATISTICS FOR: " + stats.getStatisticsIdentification() + "." + getName());
logItem.setParameters(new Object[] { addedData });
log(logItem);
}
}
} catch (Exception e) {
// Calculate statistics
if (stats.getDisableStatistics() == false) {
// Increment number of log errors (only if log has not succeded)
stats.incrementNumberOfLogErrors();
// Calculate time since last calculation of the logging statistics
float timeElapsedSinceLastStatistics = (float) (System.currentTimeMillis() - stats.getLastStatisticsRepportTime()) / (float) (1000);
// Determine if statistics are to be generated
if (timeElapsedSinceLastStatistics >= (float) (stats.getStatisticsCalculationPeriod())) {
// Calculate statistics
stats.calculateLoggingStatistics();
// Reset statistics
stats.resetStatistics();
// Print statistics logs
AcsLogRecord logItem;
Map<String, String> addedData = new HashMap<String, String>();
addedData.put("StatisticsIdentification", stats.getStatisticsIdentification());
addedData.put("LoggerId", getName());
addedData.put("LastPeriodDuration", String.valueOf(stats.getActualStatisticsPeriod()));
addedData.put("LastPeriodNumberOfMessages", String.valueOf(stats.getLastPeriodNumberOfMessages()));
addedData.put("StatisticsGranularity", String.valueOf(stats.getStatisticsGranularity()));
addedData.put("MessageStatistics", String.valueOf(stats.getMessageStatistics()));
addedData.put("MessageIncrement", String.valueOf(stats.getMessageIncrement()));
addedData.put("LastPeriodNumberOfErrorMessages", String.valueOf(stats.getLastPeriodNumberOfLogErrors()));
addedData.put("ErrorMessageStatistics", String.valueOf(stats.getErrorStatistics()));
addedData.put("ErrorMessageIncrement", String.valueOf(stats.getErrorIncrement()));
logItem = createAcsLogRecord(Level.INFO, "LOGGING STATISTICS FOR: " + stats.getStatisticsIdentification() + "." + getName());
logItem.setParameters(new Object[] { addedData });
log(logItem);
}
}
System.out.println("CRITICAL LOGGER FAILURE in " + getLoggerName());
}
if (PROFILE) {
sw_afterAcsLogger.stop();
sw_all.stop();
long elapsedNanos = sw_all.getLapTimeNanos();
if (profileSlowestCallStopWatch == null || profileSlowestCallStopWatch.getLapTimeNanos() < elapsedNanos) {
profileSlowestCallStopWatch = sw_all;
}
profileLogTimeStats.addValue(elapsedNanos);
if (profileLogTimeStats.getN() >= profileStatSize) {
String msg = "Local logging times in ms for the last " + profileStatSize + " logs: ";
msg += "mean=" + profileMillisecFormatter.format(profileLogTimeStats.getMean() * 1E-6);
msg += ", median=" + profileMillisecFormatter.format(profileLogTimeStats.getPercentile(50) * 1E-6);
msg += ", stdev=" + profileMillisecFormatter.format(profileLogTimeStats.getStandardDeviation() * 1E-6);
msg += "; details of slowest log (from ";
msg += IsoDateFormat.formatDate(profileSlowestCallStopWatch.getStartTime()) + "): ";
msg += profileSlowestCallStopWatch.getSubtaskDetails();
System.out.println(msg);
profileSlowestCallStopWatch = null;
profileLogTimeStats.clear();
}
}
}
use of java.util.logging.Logger in project ACS by ACS-Community.
the class MaciSupervisorTest method setUp.
@Override
public void setUp() throws Exception {
System.out.println("\n--- " + getName() + " ----------------");
// make the manager
// -----------------------------------------------------------------
orb = Mockito.mock(ORB.class);
manager = Mockito.mock(Manager.class);
administrator = Mockito.mock(Administrator.class);
final int hhhhh = 0;
final int[] empty = new int[] {};
ComponentInfo comp100 = new ComponentInfo("type", "code", null, "comp100", empty, 10, "cont10", 100, 0, new String[] {});
ComponentInfo comp200 = new ComponentInfo("type", "code", null, "comp200", empty, 20, "cont20", 200, 0, new String[] {});
ComponentInfo comp300 = new ComponentInfo("type", "code", null, "comp300", empty, 30, "cont30", 300, 0, new String[] {});
ComponentInfo[] one_comp = { comp100 };
ComponentInfo[] two_comps = { comp100, comp200 };
ComponentInfo[] three_comps = { comp100, comp200, comp300 };
ContainerInfo cont10 = new ContainerInfo("cont10", 10, null, empty);
ContainerInfo cont20 = new ContainerInfo("cont20", 20, null, empty);
ContainerInfo cont30 = new ContainerInfo("cont30", 30, null, empty);
ContainerInfo[] one_cont = { cont10 };
ContainerInfo[] two_conts = { cont10, cont20 };
ContainerInfo[] three_conts = { cont10, cont20, cont30 };
ClientInfo clientA = new ClientInfo(0, null, empty, "clientA", 0);
ClientInfo client1 = new ClientInfo(1, null, empty, "client1", 0);
ClientInfo client2 = new ClientInfo(2, null, empty, "client2", 0);
ClientInfo client3 = new ClientInfo(3, null, empty, "client3", 0);
ClientInfo[] one_client = { client1 };
ClientInfo[] two_clients = { client1, client2 };
ClientInfo[] three_clients = { client1, client2, client3 };
Mockito.when(orb.string_to_object("dummy")).thenReturn(manager);
Mockito.when(manager.login(administrator)).thenReturn(clientA);
Mockito.when(manager.get_component_info(hhhhh, empty, "*", "*", false)).thenReturn(one_comp, two_comps, three_comps);
Mockito.when(manager.get_container_info(hhhhh, empty, "*")).thenReturn(one_cont, one_cont, two_conts, three_conts);
Mockito.when(manager.get_client_info(hhhhh, empty, "*")).thenReturn(one_client, two_clients, three_clients, two_clients, three_clients);
// make the supervisor
// -----------------------------------------------------------------
log = new Logger("Test", null) {
final long start = System.nanoTime();
@Override
public void log(LogRecord r) {
long sinceStart = (System.nanoTime() - start) / 1000 / 1000 / 1000;
System.out.println(String.format("%2d", sinceStart) + " " + r.getLevel() + " " + r.getMessage());
}
};
log.setLevel(Level.FINE);
testee = new MaciSupervisor("Test", "dummy", orb, log);
testee.acImpl = testee.new AdministratorImplementation() {
@Override
protected Administrator asCorbaObject(ORB orb) {
return administrator;
}
};
testee.start();
// assertions
// ----------------------------------------------------------------
maciListener = new MaciInfoListener();
MaciInfo maciInformation = testee.getMaciInformation();
maciInformation.addTreeModelListener(maciListener);
}
use of java.util.logging.Logger in project ACS by ACS-Community.
the class JarSourceExtractorRunner method main.
/**
* First argument must be the jar file name to which all Java sources
* @param args
*/
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("usage: " + JarSourceExtractorRunner.class.getName() + " outputJarFile jarDirectory1 jarDirectory2 ...");
return;
}
try {
Logger logger = Logger.getLogger("ACS.JarSourceExtractorRunner");
// set up output jar file
File targetJarFile = new File(args[0]);
if (targetJarFile.exists()) {
targetJarFile.delete();
} else {
File parent = targetJarFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
}
targetJarFile.createNewFile();
if (!targetJarFile.isFile() || !targetJarFile.canWrite()) {
throw new IOException(targetJarFile + " is not a writable file.");
}
// get all input jar files
File[] dirs = getDirectories(args);
AcsJarFileFinder jarFinder = new AcsJarFileFinder(dirs, logger);
File[] jarFiles = jarFinder.getAllFiles();
// extract java sources
if (jarFiles.length > 0) {
JarSourceExtractor extractor = new JarSourceExtractor();
FileOutputStream out = new FileOutputStream(targetJarFile);
JarOutputStream jarOut = new JarOutputStream(out);
try {
for (int i = 0; i < jarFiles.length; i++) {
JarFile jarFile = new JarFile(jarFiles[i]);
if (needsProcessing(jarFile)) {
extractor.extractJavaSourcesToJar(jarFile, jarOut);
}
}
} finally {
jarOut.finish();
jarOut.close();
}
} else {
System.out.println("no jar files found.");
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
Aggregations